You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3948 lines
149KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * H.264 / AVC / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #include "libavutil/imgutils.h"
  27. #include "internal.h"
  28. #include "dsputil.h"
  29. #include "avcodec.h"
  30. #include "mpegvideo.h"
  31. #include "h264.h"
  32. #include "h264data.h"
  33. #include "h264_mvpred.h"
  34. #include "golomb.h"
  35. #include "mathops.h"
  36. #include "rectangle.h"
  37. #include "thread.h"
  38. #include "vdpau_internal.h"
  39. #include "libavutil/avassert.h"
  40. #include "cabac.h"
  41. //#undef NDEBUG
  42. #include <assert.h>
  43. static const uint8_t rem6[QP_MAX_NUM+1]={
  44. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
  45. };
  46. static const uint8_t div6[QP_MAX_NUM+1]={
  47. 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,
  48. };
  49. static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
  50. PIX_FMT_DXVA2_VLD,
  51. PIX_FMT_VAAPI_VLD,
  52. PIX_FMT_YUVJ420P,
  53. PIX_FMT_NONE
  54. };
  55. void ff_h264_write_back_intra_pred_mode(H264Context *h){
  56. int8_t *mode= h->intra4x4_pred_mode + h->mb2br_xy[h->mb_xy];
  57. AV_COPY32(mode, h->intra4x4_pred_mode_cache + 4 + 8*4);
  58. mode[4]= h->intra4x4_pred_mode_cache[7+8*3];
  59. mode[5]= h->intra4x4_pred_mode_cache[7+8*2];
  60. mode[6]= h->intra4x4_pred_mode_cache[7+8*1];
  61. }
  62. /**
  63. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  64. */
  65. int ff_h264_check_intra4x4_pred_mode(H264Context *h){
  66. MpegEncContext * const s = &h->s;
  67. static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
  68. static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
  69. int i;
  70. if(!(h->top_samples_available&0x8000)){
  71. for(i=0; i<4; i++){
  72. int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
  73. if(status<0){
  74. av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
  75. return -1;
  76. } else if(status){
  77. h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
  78. }
  79. }
  80. }
  81. if((h->left_samples_available&0x8888)!=0x8888){
  82. static const int mask[4]={0x8000,0x2000,0x80,0x20};
  83. for(i=0; i<4; i++){
  84. if(!(h->left_samples_available&mask[i])){
  85. int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
  86. if(status<0){
  87. av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra4x4 mode %d at %d %d\n", status, s->mb_x, s->mb_y);
  88. return -1;
  89. } else if(status){
  90. h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
  91. }
  92. }
  93. }
  94. }
  95. return 0;
  96. } //FIXME cleanup like ff_h264_check_intra_pred_mode
  97. /**
  98. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  99. */
  100. int ff_h264_check_intra_pred_mode(H264Context *h, int mode){
  101. MpegEncContext * const s = &h->s;
  102. static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
  103. static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
  104. if(mode > 6U) {
  105. av_log(h->s.avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", s->mb_x, s->mb_y);
  106. return -1;
  107. }
  108. if(!(h->top_samples_available&0x8000)){
  109. mode= top[ mode ];
  110. if(mode<0){
  111. av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
  112. return -1;
  113. }
  114. }
  115. if((h->left_samples_available&0x8080) != 0x8080){
  116. mode= left[ mode ];
  117. if(h->left_samples_available&0x8080){ //mad cow disease mode, aka MBAFF + constrained_intra_pred
  118. mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);
  119. }
  120. if(mode<0){
  121. av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);
  122. return -1;
  123. }
  124. }
  125. return mode;
  126. }
  127. const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
  128. int i, si, di;
  129. uint8_t *dst;
  130. int bufidx;
  131. // src[0]&0x80; //forbidden bit
  132. h->nal_ref_idc= src[0]>>5;
  133. h->nal_unit_type= src[0]&0x1F;
  134. src++; length--;
  135. #if HAVE_FAST_UNALIGNED
  136. # if HAVE_FAST_64BIT
  137. # define RS 7
  138. for(i=0; i+1<length; i+=9){
  139. if(!((~AV_RN64A(src+i) & (AV_RN64A(src+i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL))
  140. # else
  141. # define RS 3
  142. for(i=0; i+1<length; i+=5){
  143. if(!((~AV_RN32A(src+i) & (AV_RN32A(src+i) - 0x01000101U)) & 0x80008080U))
  144. # endif
  145. continue;
  146. if(i>0 && !src[i]) i--;
  147. while(src[i]) i++;
  148. #else
  149. # define RS 0
  150. for(i=0; i+1<length; i+=2){
  151. if(src[i]) continue;
  152. if(i>0 && src[i-1]==0) i--;
  153. #endif
  154. if(i+2<length && src[i+1]==0 && src[i+2]<=3){
  155. if(src[i+2]!=3){
  156. /* startcode, so we must be past the end */
  157. length=i;
  158. }
  159. break;
  160. }
  161. i-= RS;
  162. }
  163. if(i>=length-1){ //no escaped 0
  164. *dst_length= length;
  165. *consumed= length+1; //+1 for the header
  166. return src;
  167. }
  168. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
  169. av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+FF_INPUT_BUFFER_PADDING_SIZE);
  170. dst= h->rbsp_buffer[bufidx];
  171. if (dst == NULL){
  172. return NULL;
  173. }
  174. //printf("decoding esc\n");
  175. memcpy(dst, src, i);
  176. si=di=i;
  177. while(si+2<length){
  178. //remove escapes (very rare 1:2^22)
  179. if(src[si+2]>3){
  180. dst[di++]= src[si++];
  181. dst[di++]= src[si++];
  182. }else if(src[si]==0 && src[si+1]==0){
  183. if(src[si+2]==3){ //escape
  184. dst[di++]= 0;
  185. dst[di++]= 0;
  186. si+=3;
  187. continue;
  188. }else //next start code
  189. goto nsc;
  190. }
  191. dst[di++]= src[si++];
  192. }
  193. while(si<length)
  194. dst[di++]= src[si++];
  195. nsc:
  196. memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  197. *dst_length= di;
  198. *consumed= si + 1;//+1 for the header
  199. //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
  200. return dst;
  201. }
  202. /**
  203. * Identify the exact end of the bitstream
  204. * @return the length of the trailing, or 0 if damaged
  205. */
  206. static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
  207. int v= *src;
  208. int r;
  209. tprintf(h->s.avctx, "rbsp trailing %X\n", v);
  210. for(r=1; r<9; r++){
  211. if(v&1) return r;
  212. v>>=1;
  213. }
  214. return 0;
  215. }
  216. static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n, int height,
  217. int y_offset, int list){
  218. int raw_my= h->mv_cache[list][ scan8[n] ][1];
  219. int filter_height= (raw_my&3) ? 2 : 0;
  220. int full_my= (raw_my>>2) + y_offset;
  221. int top = full_my - filter_height, bottom = full_my + height + filter_height;
  222. return FFMAX(abs(top), bottom);
  223. }
  224. static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n, int height,
  225. int y_offset, int list0, int list1, int *nrefs){
  226. MpegEncContext * const s = &h->s;
  227. int my;
  228. y_offset += 16*(s->mb_y >> MB_FIELD);
  229. if(list0){
  230. int ref_n = h->ref_cache[0][ scan8[n] ];
  231. Picture *ref= &h->ref_list[0][ref_n];
  232. // Error resilience puts the current picture in the ref list.
  233. // Don't try to wait on these as it will cause a deadlock.
  234. // Fields can wait on each other, though.
  235. if(ref->thread_opaque != s->current_picture.thread_opaque ||
  236. (ref->reference&3) != s->picture_structure) {
  237. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
  238. if (refs[0][ref_n] < 0) nrefs[0] += 1;
  239. refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
  240. }
  241. }
  242. if(list1){
  243. int ref_n = h->ref_cache[1][ scan8[n] ];
  244. Picture *ref= &h->ref_list[1][ref_n];
  245. if(ref->thread_opaque != s->current_picture.thread_opaque ||
  246. (ref->reference&3) != s->picture_structure) {
  247. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
  248. if (refs[1][ref_n] < 0) nrefs[1] += 1;
  249. refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
  250. }
  251. }
  252. }
  253. /**
  254. * Wait until all reference frames are available for MC operations.
  255. *
  256. * @param h the H264 context
  257. */
  258. static void await_references(H264Context *h){
  259. MpegEncContext * const s = &h->s;
  260. const int mb_xy= h->mb_xy;
  261. const int mb_type= s->current_picture.mb_type[mb_xy];
  262. int refs[2][48];
  263. int nrefs[2] = {0};
  264. int ref, list;
  265. memset(refs, -1, sizeof(refs));
  266. if(IS_16X16(mb_type)){
  267. get_lowest_part_y(h, refs, 0, 16, 0,
  268. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  269. }else if(IS_16X8(mb_type)){
  270. get_lowest_part_y(h, refs, 0, 8, 0,
  271. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  272. get_lowest_part_y(h, refs, 8, 8, 8,
  273. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  274. }else if(IS_8X16(mb_type)){
  275. get_lowest_part_y(h, refs, 0, 16, 0,
  276. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  277. get_lowest_part_y(h, refs, 4, 16, 0,
  278. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  279. }else{
  280. int i;
  281. assert(IS_8X8(mb_type));
  282. for(i=0; i<4; i++){
  283. const int sub_mb_type= h->sub_mb_type[i];
  284. const int n= 4*i;
  285. int y_offset= (i&2)<<2;
  286. if(IS_SUB_8X8(sub_mb_type)){
  287. get_lowest_part_y(h, refs, n , 8, y_offset,
  288. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  289. }else if(IS_SUB_8X4(sub_mb_type)){
  290. get_lowest_part_y(h, refs, n , 4, y_offset,
  291. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  292. get_lowest_part_y(h, refs, n+2, 4, y_offset+4,
  293. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  294. }else if(IS_SUB_4X8(sub_mb_type)){
  295. get_lowest_part_y(h, refs, n , 8, y_offset,
  296. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  297. get_lowest_part_y(h, refs, n+1, 8, y_offset,
  298. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  299. }else{
  300. int j;
  301. assert(IS_SUB_4X4(sub_mb_type));
  302. for(j=0; j<4; j++){
  303. int sub_y_offset= y_offset + 2*(j&2);
  304. get_lowest_part_y(h, refs, n+j, 4, sub_y_offset,
  305. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  306. }
  307. }
  308. }
  309. }
  310. for(list=h->list_count-1; list>=0; list--){
  311. for(ref=0; ref<48 && nrefs[list]; ref++){
  312. int row = refs[list][ref];
  313. if(row >= 0){
  314. Picture *ref_pic = &h->ref_list[list][ref];
  315. int ref_field = ref_pic->reference - 1;
  316. int ref_field_picture = ref_pic->field_picture;
  317. int pic_height = 16*s->mb_height >> ref_field_picture;
  318. row <<= MB_MBAFF;
  319. nrefs[list]--;
  320. if(!FIELD_PICTURE && ref_field_picture){ // frame referencing two fields
  321. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) - !(row&1), pic_height-1), 1);
  322. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) , pic_height-1), 0);
  323. }else if(FIELD_PICTURE && !ref_field_picture){ // field referencing one field of a frame
  324. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row*2 + ref_field , pic_height-1), 0);
  325. }else if(FIELD_PICTURE){
  326. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), ref_field);
  327. }else{
  328. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), 0);
  329. }
  330. }
  331. }
  332. }
  333. }
  334. #if 0
  335. /**
  336. * DCT transforms the 16 dc values.
  337. * @param qp quantization parameter ??? FIXME
  338. */
  339. static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
  340. // const int qmul= dequant_coeff[qp][0];
  341. int i;
  342. int temp[16]; //FIXME check if this is a good idea
  343. static const int x_offset[4]={0, 1*stride, 4* stride, 5*stride};
  344. static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
  345. for(i=0; i<4; i++){
  346. const int offset= y_offset[i];
  347. const int z0= block[offset+stride*0] + block[offset+stride*4];
  348. const int z1= block[offset+stride*0] - block[offset+stride*4];
  349. const int z2= block[offset+stride*1] - block[offset+stride*5];
  350. const int z3= block[offset+stride*1] + block[offset+stride*5];
  351. temp[4*i+0]= z0+z3;
  352. temp[4*i+1]= z1+z2;
  353. temp[4*i+2]= z1-z2;
  354. temp[4*i+3]= z0-z3;
  355. }
  356. for(i=0; i<4; i++){
  357. const int offset= x_offset[i];
  358. const int z0= temp[4*0+i] + temp[4*2+i];
  359. const int z1= temp[4*0+i] - temp[4*2+i];
  360. const int z2= temp[4*1+i] - temp[4*3+i];
  361. const int z3= temp[4*1+i] + temp[4*3+i];
  362. block[stride*0 +offset]= (z0 + z3)>>1;
  363. block[stride*2 +offset]= (z1 + z2)>>1;
  364. block[stride*8 +offset]= (z1 - z2)>>1;
  365. block[stride*10+offset]= (z0 - z3)>>1;
  366. }
  367. }
  368. #endif
  369. #undef xStride
  370. #undef stride
  371. #if 0
  372. static void chroma_dc_dct_c(DCTELEM *block){
  373. const int stride= 16*2;
  374. const int xStride= 16;
  375. int a,b,c,d,e;
  376. a= block[stride*0 + xStride*0];
  377. b= block[stride*0 + xStride*1];
  378. c= block[stride*1 + xStride*0];
  379. d= block[stride*1 + xStride*1];
  380. e= a-b;
  381. a= a+b;
  382. b= c-d;
  383. c= c+d;
  384. block[stride*0 + xStride*0]= (a+c);
  385. block[stride*0 + xStride*1]= (e+b);
  386. block[stride*1 + xStride*0]= (a-c);
  387. block[stride*1 + xStride*1]= (e-b);
  388. }
  389. #endif
  390. static inline void mc_dir_part(H264Context *h, Picture *pic, int n, int square, int chroma_height, int delta, int list,
  391. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  392. int src_x_offset, int src_y_offset,
  393. qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op,
  394. int pixel_shift){
  395. MpegEncContext * const s = &h->s;
  396. const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
  397. int my= h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
  398. const int luma_xy= (mx&3) + ((my&3)<<2);
  399. uint8_t * src_y = pic->data[0] + ((mx>>2) << pixel_shift) + (my>>2)*h->mb_linesize;
  400. uint8_t * src_cb, * src_cr;
  401. int extra_width= h->emu_edge_width;
  402. int extra_height= h->emu_edge_height;
  403. int emu=0;
  404. const int full_mx= mx>>2;
  405. const int full_my= my>>2;
  406. const int pic_width = 16*s->mb_width;
  407. const int pic_height = 16*s->mb_height >> MB_FIELD;
  408. if(mx&7) extra_width -= 3;
  409. if(my&7) extra_height -= 3;
  410. if( full_mx < 0-extra_width
  411. || full_my < 0-extra_height
  412. || full_mx + 16/*FIXME*/ > pic_width + extra_width
  413. || full_my + 16/*FIXME*/ > pic_height + extra_height){
  414. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize, 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
  415. src_y= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
  416. emu=1;
  417. }
  418. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
  419. if(!square){
  420. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  421. }
  422. if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
  423. if(MB_FIELD){
  424. // chroma offset when predicting from a field of opposite parity
  425. my += 2 * ((s->mb_y & 1) - (pic->reference - 1));
  426. emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
  427. }
  428. src_cb= pic->data[1] + ((mx>>3) << pixel_shift) + (my>>3)*h->mb_uvlinesize;
  429. src_cr= pic->data[2] + ((mx>>3) << pixel_shift) + (my>>3)*h->mb_uvlinesize;
  430. if(emu){
  431. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
  432. src_cb= s->edge_emu_buffer;
  433. }
  434. chroma_op(dest_cb, src_cb, h->mb_uvlinesize, chroma_height, mx&7, my&7);
  435. if(emu){
  436. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize, 9, 9/*FIXME*/, (mx>>3), (my>>3), pic_width>>1, pic_height>>1);
  437. src_cr= s->edge_emu_buffer;
  438. }
  439. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, chroma_height, mx&7, my&7);
  440. }
  441. static inline void mc_part_std(H264Context *h, int n, int square, int chroma_height, int delta,
  442. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  443. int x_offset, int y_offset,
  444. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  445. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  446. int list0, int list1, int pixel_shift){
  447. MpegEncContext * const s = &h->s;
  448. qpel_mc_func *qpix_op= qpix_put;
  449. h264_chroma_mc_func chroma_op= chroma_put;
  450. dest_y += (2*x_offset << pixel_shift) + 2*y_offset*h-> mb_linesize;
  451. dest_cb += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
  452. dest_cr += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
  453. x_offset += 8*s->mb_x;
  454. y_offset += 8*(s->mb_y >> MB_FIELD);
  455. if(list0){
  456. Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
  457. mc_dir_part(h, ref, n, square, chroma_height, delta, 0,
  458. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  459. qpix_op, chroma_op, pixel_shift);
  460. qpix_op= qpix_avg;
  461. chroma_op= chroma_avg;
  462. }
  463. if(list1){
  464. Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
  465. mc_dir_part(h, ref, n, square, chroma_height, delta, 1,
  466. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  467. qpix_op, chroma_op, pixel_shift);
  468. }
  469. }
  470. static inline void mc_part_weighted(H264Context *h, int n, int square, int chroma_height, int delta,
  471. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  472. int x_offset, int y_offset,
  473. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  474. h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
  475. h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
  476. int list0, int list1, int pixel_shift){
  477. MpegEncContext * const s = &h->s;
  478. dest_y += (2*x_offset << pixel_shift) + 2*y_offset*h-> mb_linesize;
  479. dest_cb += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
  480. dest_cr += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
  481. x_offset += 8*s->mb_x;
  482. y_offset += 8*(s->mb_y >> MB_FIELD);
  483. if(list0 && list1){
  484. /* don't optimize for luma-only case, since B-frames usually
  485. * use implicit weights => chroma too. */
  486. uint8_t *tmp_cb = s->obmc_scratchpad;
  487. uint8_t *tmp_cr = s->obmc_scratchpad + (8 << pixel_shift);
  488. uint8_t *tmp_y = s->obmc_scratchpad + 8*h->mb_uvlinesize;
  489. int refn0 = h->ref_cache[0][ scan8[n] ];
  490. int refn1 = h->ref_cache[1][ scan8[n] ];
  491. mc_dir_part(h, &h->ref_list[0][refn0], n, square, chroma_height, delta, 0,
  492. dest_y, dest_cb, dest_cr,
  493. x_offset, y_offset, qpix_put, chroma_put, pixel_shift);
  494. mc_dir_part(h, &h->ref_list[1][refn1], n, square, chroma_height, delta, 1,
  495. tmp_y, tmp_cb, tmp_cr,
  496. x_offset, y_offset, qpix_put, chroma_put, pixel_shift);
  497. if(h->use_weight == 2){
  498. int weight0 = h->implicit_weight[refn0][refn1][s->mb_y&1];
  499. int weight1 = 64 - weight0;
  500. luma_weight_avg( dest_y, tmp_y, h-> mb_linesize, 5, weight0, weight1, 0);
  501. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, 5, weight0, weight1, 0);
  502. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, 5, weight0, weight1, 0);
  503. }else{
  504. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, h->luma_log2_weight_denom,
  505. h->luma_weight[refn0][0][0] , h->luma_weight[refn1][1][0],
  506. h->luma_weight[refn0][0][1] + h->luma_weight[refn1][1][1]);
  507. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  508. h->chroma_weight[refn0][0][0][0] , h->chroma_weight[refn1][1][0][0],
  509. h->chroma_weight[refn0][0][0][1] + h->chroma_weight[refn1][1][0][1]);
  510. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  511. h->chroma_weight[refn0][0][1][0] , h->chroma_weight[refn1][1][1][0],
  512. h->chroma_weight[refn0][0][1][1] + h->chroma_weight[refn1][1][1][1]);
  513. }
  514. }else{
  515. int list = list1 ? 1 : 0;
  516. int refn = h->ref_cache[list][ scan8[n] ];
  517. Picture *ref= &h->ref_list[list][refn];
  518. mc_dir_part(h, ref, n, square, chroma_height, delta, list,
  519. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  520. qpix_put, chroma_put, pixel_shift);
  521. luma_weight_op(dest_y, h->mb_linesize, h->luma_log2_weight_denom,
  522. h->luma_weight[refn][list][0], h->luma_weight[refn][list][1]);
  523. if(h->use_weight_chroma){
  524. chroma_weight_op(dest_cb, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  525. h->chroma_weight[refn][list][0][0], h->chroma_weight[refn][list][0][1]);
  526. chroma_weight_op(dest_cr, h->mb_uvlinesize, h->chroma_log2_weight_denom,
  527. h->chroma_weight[refn][list][1][0], h->chroma_weight[refn][list][1][1]);
  528. }
  529. }
  530. }
  531. static inline void mc_part(H264Context *h, int n, int square, int chroma_height, int delta,
  532. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  533. int x_offset, int y_offset,
  534. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  535. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  536. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  537. int list0, int list1, int pixel_shift){
  538. if((h->use_weight==2 && list0 && list1
  539. && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ][h->s.mb_y&1] != 32))
  540. || h->use_weight==1)
  541. mc_part_weighted(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
  542. x_offset, y_offset, qpix_put, chroma_put,
  543. weight_op[0], weight_op[3], weight_avg[0],
  544. weight_avg[3], list0, list1, pixel_shift);
  545. else
  546. mc_part_std(h, n, square, chroma_height, delta, dest_y, dest_cb, dest_cr,
  547. x_offset, y_offset, qpix_put, chroma_put, qpix_avg,
  548. chroma_avg, list0, list1, pixel_shift);
  549. }
  550. static inline void prefetch_motion(H264Context *h, int list, int pixel_shift){
  551. /* fetch pixels for estimated mv 4 macroblocks ahead
  552. * optimized for 64byte cache lines */
  553. MpegEncContext * const s = &h->s;
  554. const int refn = h->ref_cache[list][scan8[0]];
  555. if(refn >= 0){
  556. const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
  557. const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
  558. uint8_t **src= h->ref_list[list][refn].data;
  559. int off= (mx << pixel_shift) + (my + (s->mb_x&3)*4)*h->mb_linesize + (64 << pixel_shift);
  560. s->dsp.prefetch(src[0]+off, s->linesize, 4);
  561. off= ((mx>>1) << pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize + (64 << pixel_shift);
  562. s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
  563. }
  564. }
  565. static av_always_inline void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  566. qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
  567. qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
  568. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  569. int pixel_shift){
  570. MpegEncContext * const s = &h->s;
  571. const int mb_xy= h->mb_xy;
  572. const int mb_type= s->current_picture.mb_type[mb_xy];
  573. assert(IS_INTER(mb_type));
  574. if(HAVE_PTHREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
  575. await_references(h);
  576. prefetch_motion(h, 0, pixel_shift);
  577. if(IS_16X16(mb_type)){
  578. mc_part(h, 0, 1, 8, 0, dest_y, dest_cb, dest_cr, 0, 0,
  579. qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
  580. weight_op, weight_avg,
  581. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
  582. pixel_shift);
  583. }else if(IS_16X8(mb_type)){
  584. mc_part(h, 0, 0, 4, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 0,
  585. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  586. &weight_op[1], &weight_avg[1],
  587. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
  588. pixel_shift);
  589. mc_part(h, 8, 0, 4, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 4,
  590. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  591. &weight_op[1], &weight_avg[1],
  592. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
  593. pixel_shift);
  594. }else if(IS_8X16(mb_type)){
  595. mc_part(h, 0, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
  596. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  597. &weight_op[2], &weight_avg[2],
  598. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
  599. pixel_shift);
  600. mc_part(h, 4, 0, 8, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
  601. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  602. &weight_op[2], &weight_avg[2],
  603. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
  604. pixel_shift);
  605. }else{
  606. int i;
  607. assert(IS_8X8(mb_type));
  608. for(i=0; i<4; i++){
  609. const int sub_mb_type= h->sub_mb_type[i];
  610. const int n= 4*i;
  611. int x_offset= (i&1)<<2;
  612. int y_offset= (i&2)<<1;
  613. if(IS_SUB_8X8(sub_mb_type)){
  614. mc_part(h, n, 1, 4, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  615. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  616. &weight_op[3], &weight_avg[3],
  617. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  618. pixel_shift);
  619. }else if(IS_SUB_8X4(sub_mb_type)){
  620. mc_part(h, n , 0, 2, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  621. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  622. &weight_op[4], &weight_avg[4],
  623. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  624. pixel_shift);
  625. mc_part(h, n+2, 0, 2, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
  626. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  627. &weight_op[4], &weight_avg[4],
  628. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  629. pixel_shift);
  630. }else if(IS_SUB_4X8(sub_mb_type)){
  631. mc_part(h, n , 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  632. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  633. &weight_op[5], &weight_avg[5],
  634. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  635. pixel_shift);
  636. mc_part(h, n+1, 0, 4, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
  637. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  638. &weight_op[5], &weight_avg[5],
  639. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  640. pixel_shift);
  641. }else{
  642. int j;
  643. assert(IS_SUB_4X4(sub_mb_type));
  644. for(j=0; j<4; j++){
  645. int sub_x_offset= x_offset + 2*(j&1);
  646. int sub_y_offset= y_offset + (j&2);
  647. mc_part(h, n+j, 1, 2, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
  648. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  649. &weight_op[6], &weight_avg[6],
  650. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  651. pixel_shift);
  652. }
  653. }
  654. }
  655. }
  656. prefetch_motion(h, 1, pixel_shift);
  657. }
  658. #define hl_motion_fn(sh, bits) \
  659. static av_always_inline void hl_motion_ ## bits(H264Context *h, \
  660. uint8_t *dest_y, \
  661. uint8_t *dest_cb, uint8_t *dest_cr, \
  662. qpel_mc_func (*qpix_put)[16], \
  663. h264_chroma_mc_func (*chroma_put), \
  664. qpel_mc_func (*qpix_avg)[16], \
  665. h264_chroma_mc_func (*chroma_avg), \
  666. h264_weight_func *weight_op, \
  667. h264_biweight_func *weight_avg) \
  668. { \
  669. hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put, \
  670. qpix_avg, chroma_avg, weight_op, weight_avg, sh); \
  671. }
  672. hl_motion_fn(0, 8);
  673. hl_motion_fn(1, 16);
  674. static void free_tables(H264Context *h, int free_rbsp){
  675. int i;
  676. H264Context *hx;
  677. av_freep(&h->intra4x4_pred_mode);
  678. av_freep(&h->chroma_pred_mode_table);
  679. av_freep(&h->cbp_table);
  680. av_freep(&h->mvd_table[0]);
  681. av_freep(&h->mvd_table[1]);
  682. av_freep(&h->direct_table);
  683. av_freep(&h->non_zero_count);
  684. av_freep(&h->slice_table_base);
  685. h->slice_table= NULL;
  686. av_freep(&h->list_counts);
  687. av_freep(&h->mb2b_xy);
  688. av_freep(&h->mb2br_xy);
  689. for(i = 0; i < MAX_THREADS; i++) {
  690. hx = h->thread_context[i];
  691. if(!hx) continue;
  692. av_freep(&hx->top_borders[1]);
  693. av_freep(&hx->top_borders[0]);
  694. av_freep(&hx->s.obmc_scratchpad);
  695. if (free_rbsp){
  696. av_freep(&hx->rbsp_buffer[1]);
  697. av_freep(&hx->rbsp_buffer[0]);
  698. hx->rbsp_buffer_size[0] = 0;
  699. hx->rbsp_buffer_size[1] = 0;
  700. }
  701. if (i) av_freep(&h->thread_context[i]);
  702. }
  703. }
  704. static void init_dequant8_coeff_table(H264Context *h){
  705. int i,q,x;
  706. const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
  707. h->dequant8_coeff[0] = h->dequant8_buffer[0];
  708. h->dequant8_coeff[1] = h->dequant8_buffer[1];
  709. for(i=0; i<2; i++ ){
  710. if(i && !memcmp(h->pps.scaling_matrix8[0], h->pps.scaling_matrix8[1], 64*sizeof(uint8_t))){
  711. h->dequant8_coeff[1] = h->dequant8_buffer[0];
  712. break;
  713. }
  714. for(q=0; q<max_qp+1; q++){
  715. int shift = div6[q];
  716. int idx = rem6[q];
  717. for(x=0; x<64; x++)
  718. h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
  719. ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
  720. h->pps.scaling_matrix8[i][x]) << shift;
  721. }
  722. }
  723. }
  724. static void init_dequant4_coeff_table(H264Context *h){
  725. int i,j,q,x;
  726. const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
  727. for(i=0; i<6; i++ ){
  728. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  729. for(j=0; j<i; j++){
  730. if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
  731. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  732. break;
  733. }
  734. }
  735. if(j<i)
  736. continue;
  737. for(q=0; q<max_qp+1; q++){
  738. int shift = div6[q] + 2;
  739. int idx = rem6[q];
  740. for(x=0; x<16; x++)
  741. h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
  742. ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
  743. h->pps.scaling_matrix4[i][x]) << shift;
  744. }
  745. }
  746. }
  747. static void init_dequant_tables(H264Context *h){
  748. int i,x;
  749. init_dequant4_coeff_table(h);
  750. if(h->pps.transform_8x8_mode)
  751. init_dequant8_coeff_table(h);
  752. if(h->sps.transform_bypass){
  753. for(i=0; i<6; i++)
  754. for(x=0; x<16; x++)
  755. h->dequant4_coeff[i][0][x] = 1<<6;
  756. if(h->pps.transform_8x8_mode)
  757. for(i=0; i<2; i++)
  758. for(x=0; x<64; x++)
  759. h->dequant8_coeff[i][0][x] = 1<<6;
  760. }
  761. }
  762. int ff_h264_alloc_tables(H264Context *h){
  763. MpegEncContext * const s = &h->s;
  764. const int big_mb_num= s->mb_stride * (s->mb_height+1);
  765. const int row_mb_num= 2*s->mb_stride*s->avctx->thread_count;
  766. int x,y;
  767. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, row_mb_num * 8 * sizeof(uint8_t), fail)
  768. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count , big_mb_num * 32 * sizeof(uint8_t), fail)
  769. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
  770. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
  771. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
  772. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
  773. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
  774. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
  775. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
  776. memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base));
  777. h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
  778. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy , big_mb_num * sizeof(uint32_t), fail);
  779. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
  780. for(y=0; y<s->mb_height; y++){
  781. for(x=0; x<s->mb_width; x++){
  782. const int mb_xy= x + y*s->mb_stride;
  783. const int b_xy = 4*x + 4*y*h->b_stride;
  784. h->mb2b_xy [mb_xy]= b_xy;
  785. h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
  786. }
  787. }
  788. s->obmc_scratchpad = NULL;
  789. if(!h->dequant4_coeff[0])
  790. init_dequant_tables(h);
  791. return 0;
  792. fail:
  793. free_tables(h, 1);
  794. return -1;
  795. }
  796. /**
  797. * Mimic alloc_tables(), but for every context thread.
  798. */
  799. static void clone_tables(H264Context *dst, H264Context *src, int i){
  800. MpegEncContext * const s = &src->s;
  801. dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
  802. dst->non_zero_count = src->non_zero_count;
  803. dst->slice_table = src->slice_table;
  804. dst->cbp_table = src->cbp_table;
  805. dst->mb2b_xy = src->mb2b_xy;
  806. dst->mb2br_xy = src->mb2br_xy;
  807. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  808. dst->mvd_table[0] = src->mvd_table[0] + i*8*2*s->mb_stride;
  809. dst->mvd_table[1] = src->mvd_table[1] + i*8*2*s->mb_stride;
  810. dst->direct_table = src->direct_table;
  811. dst->list_counts = src->list_counts;
  812. dst->s.obmc_scratchpad = NULL;
  813. ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma);
  814. }
  815. /**
  816. * Init context
  817. * Allocate buffers which are not shared amongst multiple threads.
  818. */
  819. static int context_init(H264Context *h){
  820. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * (16+8+8) * sizeof(uint8_t)*2, fail)
  821. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * (16+8+8) * sizeof(uint8_t)*2, fail)
  822. h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
  823. h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
  824. return 0;
  825. fail:
  826. return -1; // free_tables will clean up for us
  827. }
  828. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
  829. static av_cold void common_init(H264Context *h){
  830. MpegEncContext * const s = &h->s;
  831. s->width = s->avctx->width;
  832. s->height = s->avctx->height;
  833. s->codec_id= s->avctx->codec->id;
  834. ff_h264dsp_init(&h->h264dsp, 8);
  835. ff_h264_pred_init(&h->hpc, s->codec_id, 8);
  836. h->dequant_coeff_pps= -1;
  837. s->unrestricted_mv=1;
  838. s->decode=1; //FIXME
  839. dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early
  840. memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  841. memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  842. }
  843. int ff_h264_decode_extradata(H264Context *h)
  844. {
  845. AVCodecContext *avctx = h->s.avctx;
  846. if(*(char *)avctx->extradata == 1){
  847. int i, cnt, nalsize;
  848. unsigned char *p = avctx->extradata;
  849. h->is_avc = 1;
  850. if(avctx->extradata_size < 7) {
  851. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  852. return -1;
  853. }
  854. /* sps and pps in the avcC always have length coded with 2 bytes,
  855. so put a fake nal_length_size = 2 while parsing them */
  856. h->nal_length_size = 2;
  857. // Decode sps from avcC
  858. cnt = *(p+5) & 0x1f; // Number of sps
  859. p += 6;
  860. for (i = 0; i < cnt; i++) {
  861. nalsize = AV_RB16(p) + 2;
  862. if(decode_nal_units(h, p, nalsize) < 0) {
  863. av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
  864. return -1;
  865. }
  866. p += nalsize;
  867. }
  868. // Decode pps from avcC
  869. cnt = *(p++); // Number of pps
  870. for (i = 0; i < cnt; i++) {
  871. nalsize = AV_RB16(p) + 2;
  872. if(decode_nal_units(h, p, nalsize) != nalsize) {
  873. av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
  874. return -1;
  875. }
  876. p += nalsize;
  877. }
  878. // Now store right nal length size, that will be use to parse all other nals
  879. h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;
  880. } else {
  881. h->is_avc = 0;
  882. if(decode_nal_units(h, avctx->extradata, avctx->extradata_size) < 0)
  883. return -1;
  884. }
  885. return 0;
  886. }
  887. av_cold int ff_h264_decode_init(AVCodecContext *avctx){
  888. H264Context *h= avctx->priv_data;
  889. MpegEncContext * const s = &h->s;
  890. MPV_decode_defaults(s);
  891. s->avctx = avctx;
  892. common_init(h);
  893. s->out_format = FMT_H264;
  894. s->workaround_bugs= avctx->workaround_bugs;
  895. // set defaults
  896. // s->decode_mb= ff_h263_decode_mb;
  897. s->quarter_sample = 1;
  898. if(!avctx->has_b_frames)
  899. s->low_delay= 1;
  900. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  901. ff_h264_decode_init_vlc();
  902. h->pixel_shift = 0;
  903. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  904. h->thread_context[0] = h;
  905. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  906. h->prev_poc_msb= 1<<16;
  907. h->x264_build = -1;
  908. ff_h264_reset_sei(h);
  909. if(avctx->codec_id == CODEC_ID_H264){
  910. if(avctx->ticks_per_frame == 1){
  911. s->avctx->time_base.den *=2;
  912. }
  913. avctx->ticks_per_frame = 2;
  914. }
  915. if(avctx->extradata_size > 0 && avctx->extradata &&
  916. ff_h264_decode_extradata(h))
  917. return -1;
  918. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  919. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  920. s->low_delay = 0;
  921. }
  922. return 0;
  923. }
  924. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b)+(size))))
  925. static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
  926. {
  927. int i;
  928. for (i=0; i<count; i++){
  929. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  930. IN_RANGE(from[i], old_base->picture, sizeof(Picture) * old_base->picture_count) ||
  931. !from[i]));
  932. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  933. }
  934. }
  935. static void copy_parameter_set(void **to, void **from, int count, int size)
  936. {
  937. int i;
  938. for (i=0; i<count; i++){
  939. if (to[i] && !from[i]) av_freep(&to[i]);
  940. else if (from[i] && !to[i]) to[i] = av_malloc(size);
  941. if (from[i]) memcpy(to[i], from[i], size);
  942. }
  943. }
  944. static int decode_init_thread_copy(AVCodecContext *avctx){
  945. H264Context *h= avctx->priv_data;
  946. if (!avctx->is_copy) return 0;
  947. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  948. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  949. return 0;
  950. }
  951. #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
  952. static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
  953. H264Context *h= dst->priv_data, *h1= src->priv_data;
  954. MpegEncContext * const s = &h->s, * const s1 = &h1->s;
  955. int inited = s->context_initialized, err;
  956. int i;
  957. if(dst == src || !s1->context_initialized) return 0;
  958. err = ff_mpeg_update_thread_context(dst, src);
  959. if(err) return err;
  960. //FIXME handle width/height changing
  961. if(!inited){
  962. for(i = 0; i < MAX_SPS_COUNT; i++)
  963. av_freep(h->sps_buffers + i);
  964. for(i = 0; i < MAX_PPS_COUNT; i++)
  965. av_freep(h->pps_buffers + i);
  966. memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
  967. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  968. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  969. ff_h264_alloc_tables(h);
  970. context_init(h);
  971. for(i=0; i<2; i++){
  972. h->rbsp_buffer[i] = NULL;
  973. h->rbsp_buffer_size[i] = 0;
  974. }
  975. h->thread_context[0] = h;
  976. // frame_start may not be called for the next thread (if it's decoding a bottom field)
  977. // so this has to be allocated here
  978. h->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
  979. s->dsp.clear_blocks(h->mb);
  980. }
  981. //extradata/NAL handling
  982. h->is_avc = h1->is_avc;
  983. //SPS/PPS
  984. copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
  985. h->sps = h1->sps;
  986. copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
  987. h->pps = h1->pps;
  988. //Dequantization matrices
  989. //FIXME these are big - can they be only copied when PPS changes?
  990. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  991. for(i=0; i<6; i++)
  992. h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  993. for(i=0; i<2; i++)
  994. h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  995. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  996. //POC timing
  997. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  998. //reference lists
  999. copy_fields(h, h1, ref_count, list_count);
  1000. copy_fields(h, h1, ref_list, intra_gb);
  1001. copy_fields(h, h1, short_ref, cabac_init_idc);
  1002. copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
  1003. copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
  1004. copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
  1005. h->last_slice_type = h1->last_slice_type;
  1006. if(!s->current_picture_ptr) return 0;
  1007. if(!s->dropable) {
  1008. ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1009. h->prev_poc_msb = h->poc_msb;
  1010. h->prev_poc_lsb = h->poc_lsb;
  1011. }
  1012. h->prev_frame_num_offset= h->frame_num_offset;
  1013. h->prev_frame_num = h->frame_num;
  1014. h->outputed_poc = h->next_outputed_poc;
  1015. return 0;
  1016. }
  1017. int ff_h264_frame_start(H264Context *h){
  1018. MpegEncContext * const s = &h->s;
  1019. int i;
  1020. const int pixel_shift = h->pixel_shift;
  1021. int thread_count = (s->avctx->active_thread_type & FF_THREAD_SLICE) ? s->avctx->thread_count : 1;
  1022. if(MPV_frame_start(s, s->avctx) < 0)
  1023. return -1;
  1024. ff_er_frame_start(s);
  1025. /*
  1026. * MPV_frame_start uses pict_type to derive key_frame.
  1027. * This is incorrect for H.264; IDR markings must be used.
  1028. * Zero here; IDR markings per slice in frame or fields are ORed in later.
  1029. * See decode_nal_units().
  1030. */
  1031. s->current_picture_ptr->key_frame= 0;
  1032. s->current_picture_ptr->mmco_reset= 0;
  1033. assert(s->linesize && s->uvlinesize);
  1034. for(i=0; i<16; i++){
  1035. h->block_offset[i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
  1036. h->block_offset[24+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
  1037. }
  1038. for(i=0; i<4; i++){
  1039. h->block_offset[16+i]=
  1040. h->block_offset[20+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1041. h->block_offset[24+16+i]=
  1042. h->block_offset[24+20+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1043. }
  1044. /* can't be in alloc_tables because linesize isn't known there.
  1045. * FIXME: redo bipred weight to not require extra buffer? */
  1046. for(i = 0; i < thread_count; i++)
  1047. if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
  1048. h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*2*s->linesize + 8*2*s->uvlinesize);
  1049. /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
  1050. memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
  1051. // s->decode= (s->flags&CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.reference /*|| h->contains_intra*/ || 1;
  1052. // We mark the current picture as non-reference after allocating it, so
  1053. // that if we break out due to an error it can be released automatically
  1054. // in the next MPV_frame_start().
  1055. // SVQ3 as well as most other codecs have only last/next/current and thus
  1056. // get released even with set reference, besides SVQ3 and others do not
  1057. // mark frames as reference later "naturally".
  1058. if(s->codec_id != CODEC_ID_SVQ3)
  1059. s->current_picture_ptr->reference= 0;
  1060. s->current_picture_ptr->field_poc[0]=
  1061. s->current_picture_ptr->field_poc[1]= INT_MAX;
  1062. h->next_output_pic = NULL;
  1063. assert(s->current_picture_ptr->long_ref==0);
  1064. return 0;
  1065. }
  1066. /**
  1067. * Run setup operations that must be run after slice header decoding.
  1068. * This includes finding the next displayed frame.
  1069. *
  1070. * @param h h264 master context
  1071. * @param setup_finished enough NALs have been read that we can call
  1072. * ff_thread_finish_setup()
  1073. */
  1074. static void decode_postinit(H264Context *h, int setup_finished){
  1075. MpegEncContext * const s = &h->s;
  1076. Picture *out = s->current_picture_ptr;
  1077. Picture *cur = s->current_picture_ptr;
  1078. int i, pics, out_of_order, out_idx;
  1079. s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;
  1080. s->current_picture_ptr->pict_type= s->pict_type;
  1081. if (h->next_output_pic) return;
  1082. if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
  1083. //FIXME: if we have two PAFF fields in one packet, we can't start the next thread here.
  1084. //If we have one field per packet, we can. The check in decode_nal_units() is not good enough
  1085. //to find this yet, so we assume the worst for now.
  1086. //if (setup_finished)
  1087. // ff_thread_finish_setup(s->avctx);
  1088. return;
  1089. }
  1090. cur->interlaced_frame = 0;
  1091. cur->repeat_pict = 0;
  1092. /* Signal interlacing information externally. */
  1093. /* Prioritize picture timing SEI information over used decoding process if it exists. */
  1094. if(h->sps.pic_struct_present_flag){
  1095. switch (h->sei_pic_struct)
  1096. {
  1097. case SEI_PIC_STRUCT_FRAME:
  1098. break;
  1099. case SEI_PIC_STRUCT_TOP_FIELD:
  1100. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1101. cur->interlaced_frame = 1;
  1102. break;
  1103. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1104. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1105. if (FIELD_OR_MBAFF_PICTURE)
  1106. cur->interlaced_frame = 1;
  1107. else
  1108. // try to flag soft telecine progressive
  1109. cur->interlaced_frame = h->prev_interlaced_frame;
  1110. break;
  1111. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1112. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1113. // Signal the possibility of telecined film externally (pic_struct 5,6)
  1114. // From these hints, let the applications decide if they apply deinterlacing.
  1115. cur->repeat_pict = 1;
  1116. break;
  1117. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1118. // Force progressive here, as doubling interlaced frame is a bad idea.
  1119. cur->repeat_pict = 2;
  1120. break;
  1121. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1122. cur->repeat_pict = 4;
  1123. break;
  1124. }
  1125. if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1126. cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;
  1127. }else{
  1128. /* Derive interlacing flag from used decoding process. */
  1129. cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1130. }
  1131. h->prev_interlaced_frame = cur->interlaced_frame;
  1132. if (cur->field_poc[0] != cur->field_poc[1]){
  1133. /* Derive top_field_first from field pocs. */
  1134. cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1135. }else{
  1136. if(cur->interlaced_frame || h->sps.pic_struct_present_flag){
  1137. /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
  1138. if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
  1139. || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1140. cur->top_field_first = 1;
  1141. else
  1142. cur->top_field_first = 0;
  1143. }else{
  1144. /* Most likely progressive */
  1145. cur->top_field_first = 0;
  1146. }
  1147. }
  1148. //FIXME do something with unavailable reference frames
  1149. /* Sort B-frames into display order */
  1150. if(h->sps.bitstream_restriction_flag
  1151. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  1152. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  1153. s->low_delay = 0;
  1154. }
  1155. if( s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
  1156. && !h->sps.bitstream_restriction_flag){
  1157. s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
  1158. s->low_delay= 0;
  1159. }
  1160. pics = 0;
  1161. while(h->delayed_pic[pics]) pics++;
  1162. assert(pics <= MAX_DELAYED_PIC_COUNT);
  1163. h->delayed_pic[pics++] = cur;
  1164. if(cur->reference == 0)
  1165. cur->reference = DELAYED_PIC_REF;
  1166. out = h->delayed_pic[0];
  1167. out_idx = 0;
  1168. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  1169. if(h->delayed_pic[i]->poc < out->poc){
  1170. out = h->delayed_pic[i];
  1171. out_idx = i;
  1172. }
  1173. if(s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset))
  1174. h->next_outputed_poc= INT_MIN;
  1175. out_of_order = out->poc < h->next_outputed_poc;
  1176. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
  1177. { }
  1178. else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
  1179. || (s->low_delay &&
  1180. ((h->next_outputed_poc != INT_MIN && out->poc > h->next_outputed_poc + 2)
  1181. || cur->pict_type == AV_PICTURE_TYPE_B)))
  1182. {
  1183. s->low_delay = 0;
  1184. s->avctx->has_b_frames++;
  1185. }
  1186. if(out_of_order || pics > s->avctx->has_b_frames){
  1187. out->reference &= ~DELAYED_PIC_REF;
  1188. out->owner2 = s; // for frame threading, the owner must be the second field's thread
  1189. // or else the first thread can release the picture and reuse it unsafely
  1190. for(i=out_idx; h->delayed_pic[i]; i++)
  1191. h->delayed_pic[i] = h->delayed_pic[i+1];
  1192. }
  1193. if(!out_of_order && pics > s->avctx->has_b_frames){
  1194. h->next_output_pic = out;
  1195. if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
  1196. h->next_outputed_poc = INT_MIN;
  1197. } else
  1198. h->next_outputed_poc = out->poc;
  1199. }else{
  1200. av_log(s->avctx, AV_LOG_DEBUG, "no picture\n");
  1201. }
  1202. if (setup_finished)
  1203. ff_thread_finish_setup(s->avctx);
  1204. }
  1205. static inline void backup_mb_border(H264Context *h, uint8_t *src_y, uint8_t *src_cb, uint8_t *src_cr, int linesize, int uvlinesize, int simple){
  1206. MpegEncContext * const s = &h->s;
  1207. uint8_t *top_border;
  1208. int top_idx = 1;
  1209. const int pixel_shift = h->pixel_shift;
  1210. src_y -= linesize;
  1211. src_cb -= uvlinesize;
  1212. src_cr -= uvlinesize;
  1213. if(!simple && FRAME_MBAFF){
  1214. if(s->mb_y&1){
  1215. if(!MB_MBAFF){
  1216. top_border = h->top_borders[0][s->mb_x];
  1217. AV_COPY128(top_border, src_y + 15*linesize);
  1218. if (pixel_shift)
  1219. AV_COPY128(top_border+16, src_y+15*linesize+16);
  1220. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1221. if (pixel_shift) {
  1222. AV_COPY128(top_border+32, src_cb+7*uvlinesize);
  1223. AV_COPY128(top_border+48, src_cr+7*uvlinesize);
  1224. } else {
  1225. AV_COPY64(top_border+16, src_cb+7*uvlinesize);
  1226. AV_COPY64(top_border+24, src_cr+7*uvlinesize);
  1227. }
  1228. }
  1229. }
  1230. }else if(MB_MBAFF){
  1231. top_idx = 0;
  1232. }else
  1233. return;
  1234. }
  1235. top_border = h->top_borders[top_idx][s->mb_x];
  1236. // There are two lines saved, the line above the the top macroblock of a pair,
  1237. // and the line above the bottom macroblock
  1238. AV_COPY128(top_border, src_y + 16*linesize);
  1239. if (pixel_shift)
  1240. AV_COPY128(top_border+16, src_y+16*linesize+16);
  1241. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1242. if (pixel_shift) {
  1243. AV_COPY128(top_border+32, src_cb+8*uvlinesize);
  1244. AV_COPY128(top_border+48, src_cr+8*uvlinesize);
  1245. } else {
  1246. AV_COPY64(top_border+16, src_cb+8*uvlinesize);
  1247. AV_COPY64(top_border+24, src_cr+8*uvlinesize);
  1248. }
  1249. }
  1250. }
  1251. static inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1252. uint8_t *src_cb, uint8_t *src_cr,
  1253. int linesize, int uvlinesize,
  1254. int xchg, int simple, int pixel_shift){
  1255. MpegEncContext * const s = &h->s;
  1256. int deblock_topleft;
  1257. int deblock_top;
  1258. int top_idx = 1;
  1259. uint8_t *top_border_m1;
  1260. uint8_t *top_border;
  1261. if(!simple && FRAME_MBAFF){
  1262. if(s->mb_y&1){
  1263. if(!MB_MBAFF)
  1264. return;
  1265. }else{
  1266. top_idx = MB_MBAFF ? 0 : 1;
  1267. }
  1268. }
  1269. if(h->deblocking_filter == 2) {
  1270. deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
  1271. deblock_top = h->top_type;
  1272. } else {
  1273. deblock_topleft = (s->mb_x > 0);
  1274. deblock_top = (s->mb_y > !!MB_FIELD);
  1275. }
  1276. src_y -= linesize + 1 + pixel_shift;
  1277. src_cb -= uvlinesize + 1 + pixel_shift;
  1278. src_cr -= uvlinesize + 1 + pixel_shift;
  1279. top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
  1280. top_border = h->top_borders[top_idx][s->mb_x];
  1281. #define XCHG(a,b,xchg)\
  1282. if (pixel_shift) {\
  1283. if (xchg) {\
  1284. AV_SWAP64(b+0,a+0);\
  1285. AV_SWAP64(b+8,a+8);\
  1286. } else {\
  1287. AV_COPY128(b,a); \
  1288. }\
  1289. } else \
  1290. if (xchg) AV_SWAP64(b,a);\
  1291. else AV_COPY64(b,a);
  1292. if(deblock_top){
  1293. if(deblock_topleft){
  1294. XCHG(top_border_m1 + (8 << pixel_shift), src_y - (7 << pixel_shift), 1);
  1295. }
  1296. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1297. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1298. if(s->mb_x+1 < s->mb_width){
  1299. XCHG(h->top_borders[top_idx][s->mb_x+1], src_y + (17 << pixel_shift), 1);
  1300. }
  1301. }
  1302. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1303. if(deblock_top){
  1304. if(deblock_topleft){
  1305. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1306. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1307. }
  1308. XCHG(top_border + (16 << pixel_shift), src_cb+1+pixel_shift, 1);
  1309. XCHG(top_border + (24 << pixel_shift), src_cr+1+pixel_shift, 1);
  1310. }
  1311. }
  1312. }
  1313. static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth, int index) {
  1314. if (high_bit_depth) {
  1315. return AV_RN32A(((int32_t*)mb) + index);
  1316. } else
  1317. return AV_RN16A(mb + index);
  1318. }
  1319. static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth, int index, int value) {
  1320. if (high_bit_depth) {
  1321. AV_WN32A(((int32_t*)mb) + index, value);
  1322. } else
  1323. AV_WN16A(mb + index, value);
  1324. }
  1325. static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, int pixel_shift){
  1326. MpegEncContext * const s = &h->s;
  1327. const int mb_x= s->mb_x;
  1328. const int mb_y= s->mb_y;
  1329. const int mb_xy= h->mb_xy;
  1330. const int mb_type= s->current_picture.mb_type[mb_xy];
  1331. uint8_t *dest_y, *dest_cb, *dest_cr;
  1332. int linesize, uvlinesize /*dct_offset*/;
  1333. int i;
  1334. int *block_offset = &h->block_offset[0];
  1335. const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
  1336. /* is_h264 should always be true if SVQ3 is disabled. */
  1337. const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
  1338. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1339. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  1340. dest_y = s->current_picture.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize ) * 16;
  1341. dest_cb = s->current_picture.data[1] + ((mb_x << pixel_shift) + mb_y * s->uvlinesize) * 8;
  1342. dest_cr = s->current_picture.data[2] + ((mb_x << pixel_shift) + mb_y * s->uvlinesize) * 8;
  1343. s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
  1344. s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
  1345. h->list_counts[mb_xy]= h->list_count;
  1346. if (!simple && MB_FIELD) {
  1347. linesize = h->mb_linesize = s->linesize * 2;
  1348. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  1349. block_offset = &h->block_offset[24];
  1350. if(mb_y&1){ //FIXME move out of this function?
  1351. dest_y -= s->linesize*15;
  1352. dest_cb-= s->uvlinesize*7;
  1353. dest_cr-= s->uvlinesize*7;
  1354. }
  1355. if(FRAME_MBAFF) {
  1356. int list;
  1357. for(list=0; list<h->list_count; list++){
  1358. if(!USES_LIST(mb_type, list))
  1359. continue;
  1360. if(IS_16X16(mb_type)){
  1361. int8_t *ref = &h->ref_cache[list][scan8[0]];
  1362. fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
  1363. }else{
  1364. for(i=0; i<16; i+=4){
  1365. int ref = h->ref_cache[list][scan8[i]];
  1366. if(ref >= 0)
  1367. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
  1368. }
  1369. }
  1370. }
  1371. }
  1372. } else {
  1373. linesize = h->mb_linesize = s->linesize;
  1374. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  1375. // dct_offset = s->linesize * 16;
  1376. }
  1377. if (!simple && IS_INTRA_PCM(mb_type)) {
  1378. if (pixel_shift) {
  1379. const int bit_depth = h->sps.bit_depth_luma;
  1380. int j;
  1381. GetBitContext gb;
  1382. init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
  1383. for (i = 0; i < 16; i++) {
  1384. uint16_t *tmp_y = (uint16_t*)(dest_y + i*linesize);
  1385. for (j = 0; j < 16; j++)
  1386. tmp_y[j] = get_bits(&gb, bit_depth);
  1387. }
  1388. for (i = 0; i < 8; i++) {
  1389. uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
  1390. for (j = 0; j < 8; j++)
  1391. tmp_cb[j] = get_bits(&gb, bit_depth);
  1392. }
  1393. for (i = 0; i < 8; i++) {
  1394. uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
  1395. for (j = 0; j < 8; j++)
  1396. tmp_cr[j] = get_bits(&gb, bit_depth);
  1397. }
  1398. } else {
  1399. for (i=0; i<16; i++) {
  1400. memcpy(dest_y + i* linesize, h->mb + i*8, 16);
  1401. }
  1402. for (i=0; i<8; i++) {
  1403. memcpy(dest_cb+ i*uvlinesize, h->mb + 128 + i*4, 8);
  1404. memcpy(dest_cr+ i*uvlinesize, h->mb + 160 + i*4, 8);
  1405. }
  1406. }
  1407. } else {
  1408. if(IS_INTRA(mb_type)){
  1409. if(h->deblocking_filter)
  1410. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, simple, pixel_shift);
  1411. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1412. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
  1413. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
  1414. }
  1415. if(IS_INTRA4x4(mb_type)){
  1416. if(simple || !s->encoding){
  1417. if(IS_8x8DCT(mb_type)){
  1418. if(transform_bypass){
  1419. idct_dc_add =
  1420. idct_add = s->dsp.add_pixels8;
  1421. }else{
  1422. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1423. idct_add = h->h264dsp.h264_idct8_add;
  1424. }
  1425. for(i=0; i<16; i+=4){
  1426. uint8_t * const ptr= dest_y + block_offset[i];
  1427. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  1428. if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
  1429. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16 << pixel_shift), linesize);
  1430. }else{
  1431. const int nnz = h->non_zero_count_cache[ scan8[i] ];
  1432. h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
  1433. (h->topright_samples_available<<i)&0x4000, linesize);
  1434. if(nnz){
  1435. if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16))
  1436. idct_dc_add(ptr, h->mb + (i*16 << pixel_shift), linesize);
  1437. else
  1438. idct_add (ptr, h->mb + (i*16 << pixel_shift), linesize);
  1439. }
  1440. }
  1441. }
  1442. }else{
  1443. if(transform_bypass){
  1444. idct_dc_add =
  1445. idct_add = s->dsp.add_pixels4;
  1446. }else{
  1447. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1448. idct_add = h->h264dsp.h264_idct_add;
  1449. }
  1450. for(i=0; i<16; i++){
  1451. uint8_t * const ptr= dest_y + block_offset[i];
  1452. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  1453. if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
  1454. h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16 << pixel_shift), linesize);
  1455. }else{
  1456. uint8_t *topright;
  1457. int nnz, tr;
  1458. uint64_t tr_high;
  1459. if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
  1460. const int topright_avail= (h->topright_samples_available<<i)&0x8000;
  1461. assert(mb_y || linesize <= block_offset[i]);
  1462. if(!topright_avail){
  1463. if (pixel_shift) {
  1464. tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
  1465. topright= (uint8_t*) &tr_high;
  1466. } else {
  1467. tr= ptr[3 - linesize]*0x01010101;
  1468. topright= (uint8_t*) &tr;
  1469. }
  1470. }else
  1471. topright= ptr + (4 << pixel_shift) - linesize;
  1472. }else
  1473. topright= NULL;
  1474. h->hpc.pred4x4[ dir ](ptr, topright, linesize);
  1475. nnz = h->non_zero_count_cache[ scan8[i] ];
  1476. if(nnz){
  1477. if(is_h264){
  1478. if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16))
  1479. idct_dc_add(ptr, h->mb + (i*16 << pixel_shift), linesize);
  1480. else
  1481. idct_add (ptr, h->mb + (i*16 << pixel_shift), linesize);
  1482. }else
  1483. ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, 0);
  1484. }
  1485. }
  1486. }
  1487. }
  1488. }
  1489. }else{
  1490. h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
  1491. if(is_h264){
  1492. if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX] ]){
  1493. if(!transform_bypass)
  1494. h->h264dsp.h264_luma_dc_dequant_idct(h->mb, h->mb_luma_dc, h->dequant4_coeff[0][s->qscale][0]);
  1495. else{
  1496. static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
  1497. 8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
  1498. for(i = 0; i < 16; i++)
  1499. dctcoef_set(h->mb, pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc, pixel_shift, i));
  1500. }
  1501. }
  1502. }else
  1503. ff_svq3_luma_dc_dequant_idct_c(h->mb, h->mb_luma_dc, s->qscale);
  1504. }
  1505. if(h->deblocking_filter)
  1506. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, simple, pixel_shift);
  1507. }else if(is_h264){
  1508. if (pixel_shift) {
  1509. hl_motion_16(h, dest_y, dest_cb, dest_cr,
  1510. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  1511. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  1512. h->h264dsp.weight_h264_pixels_tab,
  1513. h->h264dsp.biweight_h264_pixels_tab);
  1514. } else
  1515. hl_motion_8(h, dest_y, dest_cb, dest_cr,
  1516. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  1517. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  1518. h->h264dsp.weight_h264_pixels_tab,
  1519. h->h264dsp.biweight_h264_pixels_tab);
  1520. }
  1521. if(!IS_INTRA4x4(mb_type)){
  1522. if(is_h264){
  1523. if(IS_INTRA16x16(mb_type)){
  1524. if(transform_bypass){
  1525. if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
  1526. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb, linesize);
  1527. }else{
  1528. for(i=0; i<16; i++){
  1529. if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
  1530. s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + (i*16 << pixel_shift), linesize);
  1531. }
  1532. }
  1533. }else{
  1534. h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
  1535. }
  1536. }else if(h->cbp&15){
  1537. if(transform_bypass){
  1538. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  1539. idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
  1540. for(i=0; i<16; i+=di){
  1541. if(h->non_zero_count_cache[ scan8[i] ]){
  1542. idct_add(dest_y + block_offset[i], h->mb + (i*16 << pixel_shift), linesize);
  1543. }
  1544. }
  1545. }else{
  1546. if(IS_8x8DCT(mb_type)){
  1547. h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
  1548. }else{
  1549. h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb, linesize, h->non_zero_count_cache);
  1550. }
  1551. }
  1552. }
  1553. }else{
  1554. for(i=0; i<16; i++){
  1555. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){ //FIXME benchmark weird rule, & below
  1556. uint8_t * const ptr= dest_y + block_offset[i];
  1557. ff_svq3_add_idct_c(ptr, h->mb + i*16, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  1558. }
  1559. }
  1560. }
  1561. }
  1562. if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
  1563. uint8_t *dest[2] = {dest_cb, dest_cr};
  1564. if(transform_bypass){
  1565. if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
  1566. h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + (16*16 << pixel_shift), uvlinesize);
  1567. h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 20, h->mb + (20*16 << pixel_shift), uvlinesize);
  1568. }else{
  1569. idct_add = s->dsp.add_pixels4;
  1570. for(i=16; i<16+8; i++){
  1571. if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
  1572. idct_add (dest[(i&4)>>2] + block_offset[i], h->mb + (i*16 << pixel_shift), uvlinesize);
  1573. }
  1574. }
  1575. }else{
  1576. if(is_h264){
  1577. if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
  1578. h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + (16*16 << pixel_shift) , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
  1579. if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
  1580. h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + ((16*16+4*16) << pixel_shift), h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
  1581. h->h264dsp.h264_idct_add8(dest, block_offset,
  1582. h->mb, uvlinesize,
  1583. h->non_zero_count_cache);
  1584. }else{
  1585. h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16 , h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
  1586. h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16+4*16, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
  1587. for(i=16; i<16+8; i++){
  1588. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
  1589. uint8_t * const ptr= dest[(i&4)>>2] + block_offset[i];
  1590. ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
  1591. }
  1592. }
  1593. }
  1594. }
  1595. }
  1596. }
  1597. if(h->cbp || IS_INTRA(mb_type))
  1598. s->dsp.clear_blocks(h->mb);
  1599. }
  1600. /**
  1601. * Process a macroblock; this case avoids checks for expensive uncommon cases.
  1602. */
  1603. #define hl_decode_mb_simple(sh, bits) \
  1604. static void hl_decode_mb_simple_ ## bits(H264Context *h){ \
  1605. hl_decode_mb_internal(h, 1, sh); \
  1606. }
  1607. hl_decode_mb_simple(0, 8);
  1608. hl_decode_mb_simple(1, 16);
  1609. /**
  1610. * Process a macroblock; this handles edge cases, such as interlacing.
  1611. */
  1612. static void av_noinline hl_decode_mb_complex(H264Context *h){
  1613. hl_decode_mb_internal(h, 0, h->pixel_shift);
  1614. }
  1615. void ff_h264_hl_decode_mb(H264Context *h){
  1616. MpegEncContext * const s = &h->s;
  1617. const int mb_xy= h->mb_xy;
  1618. const int mb_type= s->current_picture.mb_type[mb_xy];
  1619. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
  1620. if (is_complex) {
  1621. hl_decode_mb_complex(h);
  1622. } else if (h->pixel_shift) {
  1623. hl_decode_mb_simple_16(h);
  1624. } else
  1625. hl_decode_mb_simple_8(h);
  1626. }
  1627. static int pred_weight_table(H264Context *h){
  1628. MpegEncContext * const s = &h->s;
  1629. int list, i;
  1630. int luma_def, chroma_def;
  1631. h->use_weight= 0;
  1632. h->use_weight_chroma= 0;
  1633. h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
  1634. if(CHROMA)
  1635. h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
  1636. luma_def = 1<<h->luma_log2_weight_denom;
  1637. chroma_def = 1<<h->chroma_log2_weight_denom;
  1638. for(list=0; list<2; list++){
  1639. h->luma_weight_flag[list] = 0;
  1640. h->chroma_weight_flag[list] = 0;
  1641. for(i=0; i<h->ref_count[list]; i++){
  1642. int luma_weight_flag, chroma_weight_flag;
  1643. luma_weight_flag= get_bits1(&s->gb);
  1644. if(luma_weight_flag){
  1645. h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
  1646. h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
  1647. if( h->luma_weight[i][list][0] != luma_def
  1648. || h->luma_weight[i][list][1] != 0) {
  1649. h->use_weight= 1;
  1650. h->luma_weight_flag[list]= 1;
  1651. }
  1652. }else{
  1653. h->luma_weight[i][list][0]= luma_def;
  1654. h->luma_weight[i][list][1]= 0;
  1655. }
  1656. if(CHROMA){
  1657. chroma_weight_flag= get_bits1(&s->gb);
  1658. if(chroma_weight_flag){
  1659. int j;
  1660. for(j=0; j<2; j++){
  1661. h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
  1662. h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
  1663. if( h->chroma_weight[i][list][j][0] != chroma_def
  1664. || h->chroma_weight[i][list][j][1] != 0) {
  1665. h->use_weight_chroma= 1;
  1666. h->chroma_weight_flag[list]= 1;
  1667. }
  1668. }
  1669. }else{
  1670. int j;
  1671. for(j=0; j<2; j++){
  1672. h->chroma_weight[i][list][j][0]= chroma_def;
  1673. h->chroma_weight[i][list][j][1]= 0;
  1674. }
  1675. }
  1676. }
  1677. }
  1678. if(h->slice_type_nos != AV_PICTURE_TYPE_B) break;
  1679. }
  1680. h->use_weight= h->use_weight || h->use_weight_chroma;
  1681. return 0;
  1682. }
  1683. /**
  1684. * Initialize implicit_weight table.
  1685. * @param field 0/1 initialize the weight for interlaced MBAFF
  1686. * -1 initializes the rest
  1687. */
  1688. static void implicit_weight_table(H264Context *h, int field){
  1689. MpegEncContext * const s = &h->s;
  1690. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  1691. for (i = 0; i < 2; i++) {
  1692. h->luma_weight_flag[i] = 0;
  1693. h->chroma_weight_flag[i] = 0;
  1694. }
  1695. if(field < 0){
  1696. cur_poc = s->current_picture_ptr->poc;
  1697. if( h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
  1698. && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
  1699. h->use_weight= 0;
  1700. h->use_weight_chroma= 0;
  1701. return;
  1702. }
  1703. ref_start= 0;
  1704. ref_count0= h->ref_count[0];
  1705. ref_count1= h->ref_count[1];
  1706. }else{
  1707. cur_poc = s->current_picture_ptr->field_poc[field];
  1708. ref_start= 16;
  1709. ref_count0= 16+2*h->ref_count[0];
  1710. ref_count1= 16+2*h->ref_count[1];
  1711. }
  1712. h->use_weight= 2;
  1713. h->use_weight_chroma= 2;
  1714. h->luma_log2_weight_denom= 5;
  1715. h->chroma_log2_weight_denom= 5;
  1716. for(ref0=ref_start; ref0 < ref_count0; ref0++){
  1717. int poc0 = h->ref_list[0][ref0].poc;
  1718. for(ref1=ref_start; ref1 < ref_count1; ref1++){
  1719. int poc1 = h->ref_list[1][ref1].poc;
  1720. int td = av_clip(poc1 - poc0, -128, 127);
  1721. int w= 32;
  1722. if(td){
  1723. int tb = av_clip(cur_poc - poc0, -128, 127);
  1724. int tx = (16384 + (FFABS(td) >> 1)) / td;
  1725. int dist_scale_factor = (tb*tx + 32) >> 8;
  1726. if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
  1727. w = 64 - dist_scale_factor;
  1728. }
  1729. if(field<0){
  1730. h->implicit_weight[ref0][ref1][0]=
  1731. h->implicit_weight[ref0][ref1][1]= w;
  1732. }else{
  1733. h->implicit_weight[ref0][ref1][field]=w;
  1734. }
  1735. }
  1736. }
  1737. }
  1738. /**
  1739. * instantaneous decoder refresh.
  1740. */
  1741. static void idr(H264Context *h){
  1742. ff_h264_remove_all_refs(h);
  1743. h->prev_frame_num= 0;
  1744. h->prev_frame_num_offset= 0;
  1745. h->prev_poc_msb=
  1746. h->prev_poc_lsb= 0;
  1747. }
  1748. /* forget old pics after a seek */
  1749. static void flush_dpb(AVCodecContext *avctx){
  1750. H264Context *h= avctx->priv_data;
  1751. int i;
  1752. for(i=0; i<MAX_DELAYED_PIC_COUNT; i++) {
  1753. if(h->delayed_pic[i])
  1754. h->delayed_pic[i]->reference= 0;
  1755. h->delayed_pic[i]= NULL;
  1756. }
  1757. h->outputed_poc=h->next_outputed_poc= INT_MIN;
  1758. h->prev_interlaced_frame = 1;
  1759. idr(h);
  1760. if(h->s.current_picture_ptr)
  1761. h->s.current_picture_ptr->reference= 0;
  1762. h->s.first_field= 0;
  1763. ff_h264_reset_sei(h);
  1764. ff_mpeg_flush(avctx);
  1765. }
  1766. static int init_poc(H264Context *h){
  1767. MpegEncContext * const s = &h->s;
  1768. const int max_frame_num= 1<<h->sps.log2_max_frame_num;
  1769. int field_poc[2];
  1770. Picture *cur = s->current_picture_ptr;
  1771. h->frame_num_offset= h->prev_frame_num_offset;
  1772. if(h->frame_num < h->prev_frame_num)
  1773. h->frame_num_offset += max_frame_num;
  1774. if(h->sps.poc_type==0){
  1775. const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
  1776. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
  1777. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  1778. else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)
  1779. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  1780. else
  1781. h->poc_msb = h->prev_poc_msb;
  1782. //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
  1783. field_poc[0] =
  1784. field_poc[1] = h->poc_msb + h->poc_lsb;
  1785. if(s->picture_structure == PICT_FRAME)
  1786. field_poc[1] += h->delta_poc_bottom;
  1787. }else if(h->sps.poc_type==1){
  1788. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  1789. int i;
  1790. if(h->sps.poc_cycle_length != 0)
  1791. abs_frame_num = h->frame_num_offset + h->frame_num;
  1792. else
  1793. abs_frame_num = 0;
  1794. if(h->nal_ref_idc==0 && abs_frame_num > 0)
  1795. abs_frame_num--;
  1796. expected_delta_per_poc_cycle = 0;
  1797. for(i=0; i < h->sps.poc_cycle_length; i++)
  1798. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
  1799. if(abs_frame_num > 0){
  1800. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1801. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1802. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1803. for(i = 0; i <= frame_num_in_poc_cycle; i++)
  1804. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
  1805. } else
  1806. expectedpoc = 0;
  1807. if(h->nal_ref_idc == 0)
  1808. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1809. field_poc[0] = expectedpoc + h->delta_poc[0];
  1810. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1811. if(s->picture_structure == PICT_FRAME)
  1812. field_poc[1] += h->delta_poc[1];
  1813. }else{
  1814. int poc= 2*(h->frame_num_offset + h->frame_num);
  1815. if(!h->nal_ref_idc)
  1816. poc--;
  1817. field_poc[0]= poc;
  1818. field_poc[1]= poc;
  1819. }
  1820. if(s->picture_structure != PICT_BOTTOM_FIELD)
  1821. s->current_picture_ptr->field_poc[0]= field_poc[0];
  1822. if(s->picture_structure != PICT_TOP_FIELD)
  1823. s->current_picture_ptr->field_poc[1]= field_poc[1];
  1824. cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
  1825. return 0;
  1826. }
  1827. /**
  1828. * initialize scan tables
  1829. */
  1830. static void init_scan_tables(H264Context *h){
  1831. int i;
  1832. for(i=0; i<16; i++){
  1833. #define T(x) (x>>2) | ((x<<2) & 0xF)
  1834. h->zigzag_scan[i] = T(zigzag_scan[i]);
  1835. h-> field_scan[i] = T( field_scan[i]);
  1836. #undef T
  1837. }
  1838. for(i=0; i<64; i++){
  1839. #define T(x) (x>>3) | ((x&7)<<3)
  1840. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  1841. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  1842. h->field_scan8x8[i] = T(field_scan8x8[i]);
  1843. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  1844. #undef T
  1845. }
  1846. if(h->sps.transform_bypass){ //FIXME same ugly
  1847. h->zigzag_scan_q0 = zigzag_scan;
  1848. h->zigzag_scan8x8_q0 = ff_zigzag_direct;
  1849. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  1850. h->field_scan_q0 = field_scan;
  1851. h->field_scan8x8_q0 = field_scan8x8;
  1852. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  1853. }else{
  1854. h->zigzag_scan_q0 = h->zigzag_scan;
  1855. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  1856. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  1857. h->field_scan_q0 = h->field_scan;
  1858. h->field_scan8x8_q0 = h->field_scan8x8;
  1859. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  1860. }
  1861. }
  1862. static void field_end(H264Context *h, int in_setup){
  1863. MpegEncContext * const s = &h->s;
  1864. AVCodecContext * const avctx= s->avctx;
  1865. s->mb_y= 0;
  1866. if (!in_setup && !s->dropable)
  1867. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
  1868. s->picture_structure==PICT_BOTTOM_FIELD);
  1869. if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  1870. ff_vdpau_h264_set_reference_frames(s);
  1871. if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
  1872. if(!s->dropable) {
  1873. ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1874. h->prev_poc_msb= h->poc_msb;
  1875. h->prev_poc_lsb= h->poc_lsb;
  1876. }
  1877. h->prev_frame_num_offset= h->frame_num_offset;
  1878. h->prev_frame_num= h->frame_num;
  1879. h->outputed_poc = h->next_outputed_poc;
  1880. }
  1881. if (avctx->hwaccel) {
  1882. if (avctx->hwaccel->end_frame(avctx) < 0)
  1883. av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
  1884. }
  1885. if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  1886. ff_vdpau_h264_picture_complete(s);
  1887. /*
  1888. * FIXME: Error handling code does not seem to support interlaced
  1889. * when slices span multiple rows
  1890. * The ff_er_add_slice calls don't work right for bottom
  1891. * fields; they cause massive erroneous error concealing
  1892. * Error marking covers both fields (top and bottom).
  1893. * This causes a mismatched s->error_count
  1894. * and a bad error table. Further, the error count goes to
  1895. * INT_MAX when called for bottom field, because mb_y is
  1896. * past end by one (callers fault) and resync_mb_y != 0
  1897. * causes problems for the first MB line, too.
  1898. */
  1899. if (!FIELD_PICTURE)
  1900. ff_er_frame_end(s);
  1901. MPV_frame_end(s);
  1902. h->current_slice=0;
  1903. }
  1904. /**
  1905. * Replicate H264 "master" context to thread contexts.
  1906. */
  1907. static void clone_slice(H264Context *dst, H264Context *src)
  1908. {
  1909. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  1910. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  1911. dst->s.current_picture = src->s.current_picture;
  1912. dst->s.linesize = src->s.linesize;
  1913. dst->s.uvlinesize = src->s.uvlinesize;
  1914. dst->s.first_field = src->s.first_field;
  1915. dst->prev_poc_msb = src->prev_poc_msb;
  1916. dst->prev_poc_lsb = src->prev_poc_lsb;
  1917. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  1918. dst->prev_frame_num = src->prev_frame_num;
  1919. dst->short_ref_count = src->short_ref_count;
  1920. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  1921. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  1922. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  1923. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  1924. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  1925. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  1926. }
  1927. /**
  1928. * computes profile from profile_idc and constraint_set?_flags
  1929. *
  1930. * @param sps SPS
  1931. *
  1932. * @return profile as defined by FF_PROFILE_H264_*
  1933. */
  1934. int ff_h264_get_profile(SPS *sps)
  1935. {
  1936. int profile = sps->profile_idc;
  1937. switch(sps->profile_idc) {
  1938. case FF_PROFILE_H264_BASELINE:
  1939. // constraint_set1_flag set to 1
  1940. profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  1941. break;
  1942. case FF_PROFILE_H264_HIGH_10:
  1943. case FF_PROFILE_H264_HIGH_422:
  1944. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  1945. // constraint_set3_flag set to 1
  1946. profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
  1947. break;
  1948. }
  1949. return profile;
  1950. }
  1951. /**
  1952. * decodes a slice header.
  1953. * This will also call MPV_common_init() and frame_start() as needed.
  1954. *
  1955. * @param h h264context
  1956. * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
  1957. *
  1958. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  1959. */
  1960. static int decode_slice_header(H264Context *h, H264Context *h0){
  1961. MpegEncContext * const s = &h->s;
  1962. MpegEncContext * const s0 = &h0->s;
  1963. unsigned int first_mb_in_slice;
  1964. unsigned int pps_id;
  1965. int num_ref_idx_active_override_flag;
  1966. unsigned int slice_type, tmp, i, j;
  1967. int default_ref_list_done = 0;
  1968. int last_pic_structure;
  1969. s->dropable= h->nal_ref_idc == 0;
  1970. if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc){
  1971. s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
  1972. s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
  1973. }else{
  1974. s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
  1975. s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
  1976. }
  1977. first_mb_in_slice= get_ue_golomb(&s->gb);
  1978. if(first_mb_in_slice == 0){ //FIXME better field boundary detection
  1979. if(h0->current_slice && FIELD_PICTURE){
  1980. field_end(h, 1);
  1981. }
  1982. h0->current_slice = 0;
  1983. if (!s0->first_field)
  1984. s->current_picture_ptr= NULL;
  1985. }
  1986. slice_type= get_ue_golomb_31(&s->gb);
  1987. if(slice_type > 9){
  1988. av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);
  1989. return -1;
  1990. }
  1991. if(slice_type > 4){
  1992. slice_type -= 5;
  1993. h->slice_type_fixed=1;
  1994. }else
  1995. h->slice_type_fixed=0;
  1996. slice_type= golomb_to_pict_type[ slice_type ];
  1997. if (slice_type == AV_PICTURE_TYPE_I
  1998. || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
  1999. default_ref_list_done = 1;
  2000. }
  2001. h->slice_type= slice_type;
  2002. h->slice_type_nos= slice_type & 3;
  2003. s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
  2004. pps_id= get_ue_golomb(&s->gb);
  2005. if(pps_id>=MAX_PPS_COUNT){
  2006. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
  2007. return -1;
  2008. }
  2009. if(!h0->pps_buffers[pps_id]) {
  2010. av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
  2011. return -1;
  2012. }
  2013. h->pps= *h0->pps_buffers[pps_id];
  2014. if(!h0->sps_buffers[h->pps.sps_id]) {
  2015. av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
  2016. return -1;
  2017. }
  2018. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2019. s->avctx->profile = ff_h264_get_profile(&h->sps);
  2020. s->avctx->level = h->sps.level_idc;
  2021. s->avctx->refs = h->sps.ref_frame_count;
  2022. if(h == h0 && h->dequant_coeff_pps != pps_id){
  2023. h->dequant_coeff_pps = pps_id;
  2024. init_dequant_tables(h);
  2025. }
  2026. s->mb_width= h->sps.mb_width;
  2027. s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2028. h->b_stride= s->mb_width*4;
  2029. s->width = 16*s->mb_width - 2*FFMIN(h->sps.crop_right, 7);
  2030. if(h->sps.frame_mbs_only_flag)
  2031. s->height= 16*s->mb_height - 2*FFMIN(h->sps.crop_bottom, 7);
  2032. else
  2033. s->height= 16*s->mb_height - 4*FFMIN(h->sps.crop_bottom, 7);
  2034. if (s->context_initialized
  2035. && ( s->width != s->avctx->width || s->height != s->avctx->height
  2036. || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
  2037. if(h != h0) {
  2038. av_log_missing_feature(s->avctx, "Width/height changing with threads is", 0);
  2039. return -1; // width / height changed during parallelized decoding
  2040. }
  2041. free_tables(h, 0);
  2042. flush_dpb(s->avctx);
  2043. MPV_common_end(s);
  2044. }
  2045. if (!s->context_initialized) {
  2046. if(h != h0)
  2047. return -1; // we cant (re-)initialize context during parallel decoding
  2048. avcodec_set_dimensions(s->avctx, s->width, s->height);
  2049. s->avctx->sample_aspect_ratio= h->sps.sar;
  2050. av_assert0(s->avctx->sample_aspect_ratio.den);
  2051. h->s.avctx->coded_width = 16*s->mb_width;
  2052. h->s.avctx->coded_height = 16*s->mb_height;
  2053. if(h->sps.video_signal_type_present_flag){
  2054. s->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  2055. if(h->sps.colour_description_present_flag){
  2056. s->avctx->color_primaries = h->sps.color_primaries;
  2057. s->avctx->color_trc = h->sps.color_trc;
  2058. s->avctx->colorspace = h->sps.colorspace;
  2059. }
  2060. }
  2061. if(h->sps.timing_info_present_flag){
  2062. int64_t den= h->sps.time_scale;
  2063. if(h->x264_build < 44U)
  2064. den *= 2;
  2065. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  2066. h->sps.num_units_in_tick, den, 1<<30);
  2067. }
  2068. switch (h->sps.bit_depth_luma) {
  2069. case 9 :
  2070. s->avctx->pix_fmt = PIX_FMT_YUV420P9;
  2071. break;
  2072. case 10 :
  2073. s->avctx->pix_fmt = PIX_FMT_YUV420P10;
  2074. break;
  2075. default:
  2076. s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
  2077. s->avctx->codec->pix_fmts ?
  2078. s->avctx->codec->pix_fmts :
  2079. s->avctx->color_range == AVCOL_RANGE_JPEG ?
  2080. hwaccel_pixfmt_list_h264_jpeg_420 :
  2081. ff_hwaccel_pixfmt_list_420);
  2082. }
  2083. s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
  2084. if (MPV_common_init(s) < 0)
  2085. return -1;
  2086. s->first_field = 0;
  2087. h->prev_interlaced_frame = 1;
  2088. init_scan_tables(h);
  2089. ff_h264_alloc_tables(h);
  2090. if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
  2091. if (context_init(h) < 0)
  2092. return -1;
  2093. } else {
  2094. for(i = 1; i < s->avctx->thread_count; i++) {
  2095. H264Context *c;
  2096. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  2097. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  2098. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  2099. c->h264dsp = h->h264dsp;
  2100. c->sps = h->sps;
  2101. c->pps = h->pps;
  2102. c->pixel_shift = h->pixel_shift;
  2103. init_scan_tables(c);
  2104. clone_tables(c, h, i);
  2105. }
  2106. for(i = 0; i < s->avctx->thread_count; i++)
  2107. if(context_init(h->thread_context[i]) < 0)
  2108. return -1;
  2109. }
  2110. }
  2111. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  2112. h->mb_mbaff = 0;
  2113. h->mb_aff_frame = 0;
  2114. last_pic_structure = s0->picture_structure;
  2115. if(h->sps.frame_mbs_only_flag){
  2116. s->picture_structure= PICT_FRAME;
  2117. }else{
  2118. if(get_bits1(&s->gb)) { //field_pic_flag
  2119. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  2120. } else {
  2121. s->picture_structure= PICT_FRAME;
  2122. h->mb_aff_frame = h->sps.mb_aff;
  2123. }
  2124. }
  2125. h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
  2126. if(h0->current_slice == 0){
  2127. if(h->frame_num != h->prev_frame_num &&
  2128. (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num) < (h->frame_num - h->sps.ref_frame_count))
  2129. h->prev_frame_num = h->frame_num - h->sps.ref_frame_count - 1;
  2130. while(h->frame_num != h->prev_frame_num &&
  2131. h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
  2132. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2133. av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
  2134. if (ff_h264_frame_start(h) < 0)
  2135. return -1;
  2136. h->prev_frame_num++;
  2137. h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
  2138. s->current_picture_ptr->frame_num= h->prev_frame_num;
  2139. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
  2140. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
  2141. ff_generate_sliding_window_mmcos(h);
  2142. ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2143. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2144. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  2145. * about there being no actual duplicates.
  2146. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  2147. * concealing a lost frame, this probably isn't noticable by comparison, but it should
  2148. * be fixed. */
  2149. if (h->short_ref_count) {
  2150. if (prev) {
  2151. av_image_copy(h->short_ref[0]->data, h->short_ref[0]->linesize,
  2152. (const uint8_t**)prev->data, prev->linesize,
  2153. s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
  2154. h->short_ref[0]->poc = prev->poc+2;
  2155. }
  2156. h->short_ref[0]->frame_num = h->prev_frame_num;
  2157. }
  2158. }
  2159. /* See if we have a decoded first field looking for a pair... */
  2160. if (s0->first_field) {
  2161. assert(s0->current_picture_ptr);
  2162. assert(s0->current_picture_ptr->data[0]);
  2163. assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
  2164. /* figure out if we have a complementary field pair */
  2165. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2166. /*
  2167. * Previous field is unmatched. Don't display it, but let it
  2168. * remain for reference if marked as such.
  2169. */
  2170. s0->current_picture_ptr = NULL;
  2171. s0->first_field = FIELD_PICTURE;
  2172. } else {
  2173. if (h->nal_ref_idc &&
  2174. s0->current_picture_ptr->reference &&
  2175. s0->current_picture_ptr->frame_num != h->frame_num) {
  2176. /*
  2177. * This and previous field were reference, but had
  2178. * different frame_nums. Consider this field first in
  2179. * pair. Throw away previous field except for reference
  2180. * purposes.
  2181. */
  2182. s0->first_field = 1;
  2183. s0->current_picture_ptr = NULL;
  2184. } else {
  2185. /* Second field in complementary pair */
  2186. s0->first_field = 0;
  2187. }
  2188. }
  2189. } else {
  2190. /* Frame or first field in a potentially complementary pair */
  2191. assert(!s0->current_picture_ptr);
  2192. s0->first_field = FIELD_PICTURE;
  2193. }
  2194. if(!FIELD_PICTURE || s0->first_field) {
  2195. if (ff_h264_frame_start(h) < 0) {
  2196. s0->first_field = 0;
  2197. return -1;
  2198. }
  2199. } else {
  2200. ff_release_unused_pictures(s, 0);
  2201. }
  2202. }
  2203. if(h != h0)
  2204. clone_slice(h, h0);
  2205. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  2206. assert(s->mb_num == s->mb_width * s->mb_height);
  2207. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  2208. first_mb_in_slice >= s->mb_num){
  2209. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2210. return -1;
  2211. }
  2212. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  2213. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  2214. if (s->picture_structure == PICT_BOTTOM_FIELD)
  2215. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  2216. assert(s->mb_y < s->mb_height);
  2217. if(s->picture_structure==PICT_FRAME){
  2218. h->curr_pic_num= h->frame_num;
  2219. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  2220. }else{
  2221. h->curr_pic_num= 2*h->frame_num + 1;
  2222. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  2223. }
  2224. if(h->nal_unit_type == NAL_IDR_SLICE){
  2225. get_ue_golomb(&s->gb); /* idr_pic_id */
  2226. }
  2227. if(h->sps.poc_type==0){
  2228. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  2229. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  2230. h->delta_poc_bottom= get_se_golomb(&s->gb);
  2231. }
  2232. }
  2233. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  2234. h->delta_poc[0]= get_se_golomb(&s->gb);
  2235. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  2236. h->delta_poc[1]= get_se_golomb(&s->gb);
  2237. }
  2238. init_poc(h);
  2239. if(h->pps.redundant_pic_cnt_present){
  2240. h->redundant_pic_count= get_ue_golomb(&s->gb);
  2241. }
  2242. //set defaults, might be overridden a few lines later
  2243. h->ref_count[0]= h->pps.ref_count[0];
  2244. h->ref_count[1]= h->pps.ref_count[1];
  2245. if(h->slice_type_nos != AV_PICTURE_TYPE_I){
  2246. if(h->slice_type_nos == AV_PICTURE_TYPE_B){
  2247. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  2248. }
  2249. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  2250. if(num_ref_idx_active_override_flag){
  2251. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  2252. if(h->slice_type_nos==AV_PICTURE_TYPE_B)
  2253. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  2254. if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
  2255. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  2256. h->ref_count[0]= h->ref_count[1]= 1;
  2257. return -1;
  2258. }
  2259. }
  2260. if(h->slice_type_nos == AV_PICTURE_TYPE_B)
  2261. h->list_count= 2;
  2262. else
  2263. h->list_count= 1;
  2264. }else
  2265. h->list_count= 0;
  2266. if(!default_ref_list_done){
  2267. ff_h264_fill_default_ref_list(h);
  2268. }
  2269. if(h->slice_type_nos!=AV_PICTURE_TYPE_I && ff_h264_decode_ref_pic_list_reordering(h) < 0)
  2270. return -1;
  2271. if(h->slice_type_nos!=AV_PICTURE_TYPE_I){
  2272. s->last_picture_ptr= &h->ref_list[0][0];
  2273. ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  2274. }
  2275. if(h->slice_type_nos==AV_PICTURE_TYPE_B){
  2276. s->next_picture_ptr= &h->ref_list[1][0];
  2277. ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  2278. }
  2279. if( (h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P )
  2280. || (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== AV_PICTURE_TYPE_B ) )
  2281. pred_weight_table(h);
  2282. else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
  2283. implicit_weight_table(h, -1);
  2284. }else {
  2285. h->use_weight = 0;
  2286. for (i = 0; i < 2; i++) {
  2287. h->luma_weight_flag[i] = 0;
  2288. h->chroma_weight_flag[i] = 0;
  2289. }
  2290. }
  2291. if(h->nal_ref_idc)
  2292. ff_h264_decode_ref_pic_marking(h0, &s->gb);
  2293. if(FRAME_MBAFF){
  2294. ff_h264_fill_mbaff_ref_list(h);
  2295. if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
  2296. implicit_weight_table(h, 0);
  2297. implicit_weight_table(h, 1);
  2298. }
  2299. }
  2300. if(h->slice_type_nos==AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  2301. ff_h264_direct_dist_scale_factor(h);
  2302. ff_h264_direct_ref_list_init(h);
  2303. if( h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac ){
  2304. tmp = get_ue_golomb_31(&s->gb);
  2305. if(tmp > 2){
  2306. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  2307. return -1;
  2308. }
  2309. h->cabac_init_idc= tmp;
  2310. }
  2311. h->last_qscale_diff = 0;
  2312. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  2313. if(tmp>51+6*(h->sps.bit_depth_luma-8)){
  2314. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  2315. return -1;
  2316. }
  2317. s->qscale= tmp;
  2318. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2319. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2320. //FIXME qscale / qp ... stuff
  2321. if(h->slice_type == AV_PICTURE_TYPE_SP){
  2322. get_bits1(&s->gb); /* sp_for_switch_flag */
  2323. }
  2324. if(h->slice_type==AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI){
  2325. get_se_golomb(&s->gb); /* slice_qs_delta */
  2326. }
  2327. h->deblocking_filter = 1;
  2328. h->slice_alpha_c0_offset = 52;
  2329. h->slice_beta_offset = 52;
  2330. if( h->pps.deblocking_filter_parameters_present ) {
  2331. tmp= get_ue_golomb_31(&s->gb);
  2332. if(tmp > 2){
  2333. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  2334. return -1;
  2335. }
  2336. h->deblocking_filter= tmp;
  2337. if(h->deblocking_filter < 2)
  2338. h->deblocking_filter^= 1; // 1<->0
  2339. if( h->deblocking_filter ) {
  2340. h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
  2341. h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
  2342. if( h->slice_alpha_c0_offset > 104U
  2343. || h->slice_beta_offset > 104U){
  2344. av_log(s->avctx, AV_LOG_ERROR, "deblocking filter parameters %d %d out of range\n", h->slice_alpha_c0_offset, h->slice_beta_offset);
  2345. return -1;
  2346. }
  2347. }
  2348. }
  2349. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  2350. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I)
  2351. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B)
  2352. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  2353. h->deblocking_filter= 0;
  2354. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  2355. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  2356. /* Cheat slightly for speed:
  2357. Do not bother to deblock across slices. */
  2358. h->deblocking_filter = 2;
  2359. } else {
  2360. h0->max_contexts = 1;
  2361. if(!h0->single_decode_warning) {
  2362. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  2363. h0->single_decode_warning = 1;
  2364. }
  2365. if(h != h0)
  2366. return 1; // deblocking switched inside frame
  2367. }
  2368. }
  2369. h->qp_thresh= 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]);
  2370. #if 0 //FMO
  2371. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  2372. slice_group_change_cycle= get_bits(&s->gb, ?);
  2373. #endif
  2374. h0->last_slice_type = slice_type;
  2375. h->slice_num = ++h0->current_slice;
  2376. if(h->slice_num >= MAX_SLICES){
  2377. av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
  2378. }
  2379. for(j=0; j<2; j++){
  2380. int id_list[16];
  2381. int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
  2382. for(i=0; i<16; i++){
  2383. id_list[i]= 60;
  2384. if(h->ref_list[j][i].data[0]){
  2385. int k;
  2386. uint8_t *base= h->ref_list[j][i].base[0];
  2387. for(k=0; k<h->short_ref_count; k++)
  2388. if(h->short_ref[k]->base[0] == base){
  2389. id_list[i]= k;
  2390. break;
  2391. }
  2392. for(k=0; k<h->long_ref_count; k++)
  2393. if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
  2394. id_list[i]= h->short_ref_count + k;
  2395. break;
  2396. }
  2397. }
  2398. }
  2399. ref2frm[0]=
  2400. ref2frm[1]= -1;
  2401. for(i=0; i<16; i++)
  2402. ref2frm[i+2]= 4*id_list[i]
  2403. +(h->ref_list[j][i].reference&3);
  2404. ref2frm[18+0]=
  2405. ref2frm[18+1]= -1;
  2406. for(i=16; i<48; i++)
  2407. ref2frm[i+4]= 4*id_list[(i-16)>>1]
  2408. +(h->ref_list[j][i].reference&3);
  2409. }
  2410. //FIXME: fix draw_edges+PAFF+frame threads
  2411. h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE || (!h->sps.frame_mbs_only_flag && s->avctx->active_thread_type)) ? 0 : 16;
  2412. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  2413. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  2414. av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
  2415. h->slice_num,
  2416. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  2417. first_mb_in_slice,
  2418. av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  2419. pps_id, h->frame_num,
  2420. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  2421. h->ref_count[0], h->ref_count[1],
  2422. s->qscale,
  2423. h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
  2424. h->use_weight,
  2425. h->use_weight==1 && h->use_weight_chroma ? "c" : "",
  2426. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
  2427. );
  2428. }
  2429. return 0;
  2430. }
  2431. int ff_h264_get_slice_type(const H264Context *h)
  2432. {
  2433. switch (h->slice_type) {
  2434. case AV_PICTURE_TYPE_P: return 0;
  2435. case AV_PICTURE_TYPE_B: return 1;
  2436. case AV_PICTURE_TYPE_I: return 2;
  2437. case AV_PICTURE_TYPE_SP: return 3;
  2438. case AV_PICTURE_TYPE_SI: return 4;
  2439. default: return -1;
  2440. }
  2441. }
  2442. /**
  2443. *
  2444. * @return non zero if the loop filter can be skiped
  2445. */
  2446. static int fill_filter_caches(H264Context *h, int mb_type){
  2447. MpegEncContext * const s = &h->s;
  2448. const int mb_xy= h->mb_xy;
  2449. int top_xy, left_xy[2];
  2450. int top_type, left_type[2];
  2451. top_xy = mb_xy - (s->mb_stride << MB_FIELD);
  2452. //FIXME deblocking could skip the intra and nnz parts.
  2453. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  2454. * stuff, I can't imagine that these complex rules are worth it. */
  2455. left_xy[1] = left_xy[0] = mb_xy-1;
  2456. if(FRAME_MBAFF){
  2457. const int left_mb_field_flag = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
  2458. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  2459. if(s->mb_y&1){
  2460. if (left_mb_field_flag != curr_mb_field_flag) {
  2461. left_xy[0] -= s->mb_stride;
  2462. }
  2463. }else{
  2464. if(curr_mb_field_flag){
  2465. top_xy += s->mb_stride & (((s->current_picture.mb_type[top_xy ]>>7)&1)-1);
  2466. }
  2467. if (left_mb_field_flag != curr_mb_field_flag) {
  2468. left_xy[1] += s->mb_stride;
  2469. }
  2470. }
  2471. }
  2472. h->top_mb_xy = top_xy;
  2473. h->left_mb_xy[0] = left_xy[0];
  2474. h->left_mb_xy[1] = left_xy[1];
  2475. {
  2476. //for sufficiently low qp, filtering wouldn't do anything
  2477. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  2478. int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
  2479. int qp = s->current_picture.qscale_table[mb_xy];
  2480. if(qp <= qp_thresh
  2481. && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
  2482. && (top_xy < 0 || ((qp + s->current_picture.qscale_table[top_xy ] + 1)>>1) <= qp_thresh)){
  2483. if(!FRAME_MBAFF)
  2484. return 1;
  2485. if( (left_xy[0]< 0 || ((qp + s->current_picture.qscale_table[left_xy[1] ] + 1)>>1) <= qp_thresh)
  2486. && (top_xy < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy -s->mb_stride] + 1)>>1) <= qp_thresh))
  2487. return 1;
  2488. }
  2489. }
  2490. top_type = s->current_picture.mb_type[top_xy] ;
  2491. left_type[0] = s->current_picture.mb_type[left_xy[0]];
  2492. left_type[1] = s->current_picture.mb_type[left_xy[1]];
  2493. if(h->deblocking_filter == 2){
  2494. if(h->slice_table[top_xy ] != h->slice_num) top_type= 0;
  2495. if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
  2496. }else{
  2497. if(h->slice_table[top_xy ] == 0xFFFF) top_type= 0;
  2498. if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
  2499. }
  2500. h->top_type = top_type ;
  2501. h->left_type[0]= left_type[0];
  2502. h->left_type[1]= left_type[1];
  2503. if(IS_INTRA(mb_type))
  2504. return 0;
  2505. AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
  2506. AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
  2507. AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
  2508. AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
  2509. AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
  2510. h->cbp= h->cbp_table[mb_xy];
  2511. {
  2512. int list;
  2513. for(list=0; list<h->list_count; list++){
  2514. int8_t *ref;
  2515. int y, b_stride;
  2516. int16_t (*mv_dst)[2];
  2517. int16_t (*mv_src)[2];
  2518. if(!USES_LIST(mb_type, list)){
  2519. fill_rectangle( h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
  2520. AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2521. AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2522. AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2523. AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2524. continue;
  2525. }
  2526. ref = &s->current_picture.ref_index[list][4*mb_xy];
  2527. {
  2528. int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2529. AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2530. AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2531. ref += 2;
  2532. AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2533. AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2534. }
  2535. b_stride = h->b_stride;
  2536. mv_dst = &h->mv_cache[list][scan8[0]];
  2537. mv_src = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
  2538. for(y=0; y<4; y++){
  2539. AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
  2540. }
  2541. }
  2542. }
  2543. /*
  2544. 0 . T T. T T T T
  2545. 1 L . .L . . . .
  2546. 2 L . .L . . . .
  2547. 3 . T TL . . . .
  2548. 4 L . .L . . . .
  2549. 5 L . .. . . . .
  2550. */
  2551. //FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
  2552. if(top_type){
  2553. AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
  2554. }
  2555. if(left_type[0]){
  2556. h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
  2557. h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
  2558. h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
  2559. h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
  2560. }
  2561. // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
  2562. if(!CABAC && h->pps.transform_8x8_mode){
  2563. if(IS_8x8DCT(top_type)){
  2564. h->non_zero_count_cache[4+8*0]=
  2565. h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
  2566. h->non_zero_count_cache[6+8*0]=
  2567. h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
  2568. }
  2569. if(IS_8x8DCT(left_type[0])){
  2570. h->non_zero_count_cache[3+8*1]=
  2571. h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
  2572. }
  2573. if(IS_8x8DCT(left_type[1])){
  2574. h->non_zero_count_cache[3+8*3]=
  2575. h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
  2576. }
  2577. if(IS_8x8DCT(mb_type)){
  2578. h->non_zero_count_cache[scan8[0 ]]= h->non_zero_count_cache[scan8[1 ]]=
  2579. h->non_zero_count_cache[scan8[2 ]]= h->non_zero_count_cache[scan8[3 ]]= h->cbp & 1;
  2580. h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
  2581. h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
  2582. h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
  2583. h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
  2584. h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
  2585. h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
  2586. }
  2587. }
  2588. if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
  2589. int list;
  2590. for(list=0; list<h->list_count; list++){
  2591. if(USES_LIST(top_type, list)){
  2592. const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
  2593. const int b8_xy= 4*top_xy + 2;
  2594. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2595. AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
  2596. h->ref_cache[list][scan8[0] + 0 - 1*8]=
  2597. h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
  2598. h->ref_cache[list][scan8[0] + 2 - 1*8]=
  2599. h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
  2600. }else{
  2601. AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
  2602. AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2603. }
  2604. if(!IS_INTERLACED(mb_type^left_type[0])){
  2605. if(USES_LIST(left_type[0], list)){
  2606. const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
  2607. const int b8_xy= 4*left_xy[0] + 1;
  2608. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2609. AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
  2610. AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
  2611. AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
  2612. AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
  2613. h->ref_cache[list][scan8[0] - 1 + 0 ]=
  2614. h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
  2615. h->ref_cache[list][scan8[0] - 1 +16 ]=
  2616. h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
  2617. }else{
  2618. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
  2619. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
  2620. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
  2621. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
  2622. h->ref_cache[list][scan8[0] - 1 + 0 ]=
  2623. h->ref_cache[list][scan8[0] - 1 + 8 ]=
  2624. h->ref_cache[list][scan8[0] - 1 + 16 ]=
  2625. h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
  2626. }
  2627. }
  2628. }
  2629. }
  2630. return 0;
  2631. }
  2632. static void loop_filter(H264Context *h, int start_x, int end_x){
  2633. MpegEncContext * const s = &h->s;
  2634. uint8_t *dest_y, *dest_cb, *dest_cr;
  2635. int linesize, uvlinesize, mb_x, mb_y;
  2636. const int end_mb_y= s->mb_y + FRAME_MBAFF;
  2637. const int old_slice_type= h->slice_type;
  2638. const int pixel_shift = h->pixel_shift;
  2639. if(h->deblocking_filter) {
  2640. for(mb_x= start_x; mb_x<end_x; mb_x++){
  2641. for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
  2642. int mb_xy, mb_type;
  2643. mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
  2644. h->slice_num= h->slice_table[mb_xy];
  2645. mb_type= s->current_picture.mb_type[mb_xy];
  2646. h->list_count= h->list_counts[mb_xy];
  2647. if(FRAME_MBAFF)
  2648. h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  2649. s->mb_x= mb_x;
  2650. s->mb_y= mb_y;
  2651. dest_y = s->current_picture.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize ) * 16;
  2652. dest_cb = s->current_picture.data[1] + ((mb_x << pixel_shift) + mb_y * s->uvlinesize) * 8;
  2653. dest_cr = s->current_picture.data[2] + ((mb_x << pixel_shift) + mb_y * s->uvlinesize) * 8;
  2654. //FIXME simplify above
  2655. if (MB_FIELD) {
  2656. linesize = h->mb_linesize = s->linesize * 2;
  2657. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  2658. if(mb_y&1){ //FIXME move out of this function?
  2659. dest_y -= s->linesize*15;
  2660. dest_cb-= s->uvlinesize*7;
  2661. dest_cr-= s->uvlinesize*7;
  2662. }
  2663. } else {
  2664. linesize = h->mb_linesize = s->linesize;
  2665. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  2666. }
  2667. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
  2668. if(fill_filter_caches(h, mb_type))
  2669. continue;
  2670. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
  2671. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
  2672. if (FRAME_MBAFF) {
  2673. ff_h264_filter_mb (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2674. } else {
  2675. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2676. }
  2677. }
  2678. }
  2679. }
  2680. h->slice_type= old_slice_type;
  2681. s->mb_x= end_x;
  2682. s->mb_y= end_mb_y - FRAME_MBAFF;
  2683. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2684. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2685. }
  2686. static void predict_field_decoding_flag(H264Context *h){
  2687. MpegEncContext * const s = &h->s;
  2688. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  2689. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  2690. ? s->current_picture.mb_type[mb_xy-1]
  2691. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  2692. ? s->current_picture.mb_type[mb_xy-s->mb_stride]
  2693. : 0;
  2694. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  2695. }
  2696. /**
  2697. * Draw edges and report progress for the last MB row.
  2698. */
  2699. static void decode_finish_row(H264Context *h){
  2700. MpegEncContext * const s = &h->s;
  2701. int top = 16*(s->mb_y >> FIELD_PICTURE);
  2702. int height = 16 << FRAME_MBAFF;
  2703. int deblock_border = (16 + 4) << FRAME_MBAFF;
  2704. int pic_height = 16*s->mb_height >> FIELD_PICTURE;
  2705. if (h->deblocking_filter) {
  2706. if((top + height) >= pic_height)
  2707. height += deblock_border;
  2708. top -= deblock_border;
  2709. }
  2710. if (top >= pic_height || (top + height) < h->emu_edge_height)
  2711. return;
  2712. height = FFMIN(height, pic_height - top);
  2713. if (top < h->emu_edge_height) {
  2714. height = top+height;
  2715. top = 0;
  2716. }
  2717. ff_draw_horiz_band(s, top, height);
  2718. if (s->dropable) return;
  2719. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
  2720. s->picture_structure==PICT_BOTTOM_FIELD);
  2721. }
  2722. static int decode_slice(struct AVCodecContext *avctx, void *arg){
  2723. H264Context *h = *(void**)arg;
  2724. MpegEncContext * const s = &h->s;
  2725. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  2726. int lf_x_start = s->mb_x;
  2727. s->mb_skip_run= -1;
  2728. h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
  2729. (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
  2730. if( h->pps.cabac ) {
  2731. /* realign */
  2732. align_get_bits( &s->gb );
  2733. /* init cabac */
  2734. ff_init_cabac_states( &h->cabac);
  2735. ff_init_cabac_decoder( &h->cabac,
  2736. s->gb.buffer + get_bits_count(&s->gb)/8,
  2737. (get_bits_left(&s->gb) + 7)/8);
  2738. ff_h264_init_cabac_states(h);
  2739. for(;;){
  2740. //START_TIMER
  2741. int ret = ff_h264_decode_mb_cabac(h);
  2742. int eos;
  2743. //STOP_TIMER("decode_mb_cabac")
  2744. if(ret>=0) ff_h264_hl_decode_mb(h);
  2745. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  2746. s->mb_y++;
  2747. ret = ff_h264_decode_mb_cabac(h);
  2748. if(ret>=0) ff_h264_hl_decode_mb(h);
  2749. s->mb_y--;
  2750. }
  2751. eos = get_cabac_terminate( &h->cabac );
  2752. if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
  2753. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2754. if (s->mb_x >= lf_x_start) loop_filter(h, lf_x_start, s->mb_x + 1);
  2755. return 0;
  2756. }
  2757. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  2758. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream (%td)\n", s->mb_x, s->mb_y, h->cabac.bytestream_end - h->cabac.bytestream);
  2759. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2760. return -1;
  2761. }
  2762. if( ++s->mb_x >= s->mb_width ) {
  2763. loop_filter(h, lf_x_start, s->mb_x);
  2764. s->mb_x = lf_x_start = 0;
  2765. decode_finish_row(h);
  2766. ++s->mb_y;
  2767. if(FIELD_OR_MBAFF_PICTURE) {
  2768. ++s->mb_y;
  2769. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  2770. predict_field_decoding_flag(h);
  2771. }
  2772. }
  2773. if( eos || s->mb_y >= s->mb_height ) {
  2774. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2775. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2776. if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);
  2777. return 0;
  2778. }
  2779. }
  2780. } else {
  2781. for(;;){
  2782. int ret = ff_h264_decode_mb_cavlc(h);
  2783. if(ret>=0) ff_h264_hl_decode_mb(h);
  2784. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  2785. s->mb_y++;
  2786. ret = ff_h264_decode_mb_cavlc(h);
  2787. if(ret>=0) ff_h264_hl_decode_mb(h);
  2788. s->mb_y--;
  2789. }
  2790. if(ret<0){
  2791. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  2792. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2793. return -1;
  2794. }
  2795. if(++s->mb_x >= s->mb_width){
  2796. loop_filter(h, lf_x_start, s->mb_x);
  2797. s->mb_x = lf_x_start = 0;
  2798. decode_finish_row(h);
  2799. ++s->mb_y;
  2800. if(FIELD_OR_MBAFF_PICTURE) {
  2801. ++s->mb_y;
  2802. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  2803. predict_field_decoding_flag(h);
  2804. }
  2805. if(s->mb_y >= s->mb_height){
  2806. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2807. if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {
  2808. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2809. return 0;
  2810. }else{
  2811. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2812. return -1;
  2813. }
  2814. }
  2815. }
  2816. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  2817. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2818. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  2819. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2820. if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);
  2821. return 0;
  2822. }else{
  2823. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2824. return -1;
  2825. }
  2826. }
  2827. }
  2828. }
  2829. #if 0
  2830. for(;s->mb_y < s->mb_height; s->mb_y++){
  2831. for(;s->mb_x < s->mb_width; s->mb_x++){
  2832. int ret= decode_mb(h);
  2833. ff_h264_hl_decode_mb(h);
  2834. if(ret<0){
  2835. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  2836. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2837. return -1;
  2838. }
  2839. if(++s->mb_x >= s->mb_width){
  2840. s->mb_x=0;
  2841. if(++s->mb_y >= s->mb_height){
  2842. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  2843. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2844. return 0;
  2845. }else{
  2846. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2847. return -1;
  2848. }
  2849. }
  2850. }
  2851. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  2852. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  2853. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);
  2854. return 0;
  2855. }else{
  2856. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);
  2857. return -1;
  2858. }
  2859. }
  2860. }
  2861. s->mb_x=0;
  2862. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  2863. }
  2864. #endif
  2865. return -1; //not reached
  2866. }
  2867. /**
  2868. * Call decode_slice() for each context.
  2869. *
  2870. * @param h h264 master context
  2871. * @param context_count number of contexts to execute
  2872. */
  2873. static void execute_decode_slices(H264Context *h, int context_count){
  2874. MpegEncContext * const s = &h->s;
  2875. AVCodecContext * const avctx= s->avctx;
  2876. H264Context *hx;
  2877. int i;
  2878. if (s->avctx->hwaccel)
  2879. return;
  2880. if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2881. return;
  2882. if(context_count == 1) {
  2883. decode_slice(avctx, &h);
  2884. } else {
  2885. for(i = 1; i < context_count; i++) {
  2886. hx = h->thread_context[i];
  2887. hx->s.error_recognition = avctx->error_recognition;
  2888. hx->s.error_count = 0;
  2889. }
  2890. avctx->execute(avctx, (void *)decode_slice,
  2891. h->thread_context, NULL, context_count, sizeof(void*));
  2892. /* pull back stuff from slices to master context */
  2893. hx = h->thread_context[context_count - 1];
  2894. s->mb_x = hx->s.mb_x;
  2895. s->mb_y = hx->s.mb_y;
  2896. s->dropable = hx->s.dropable;
  2897. s->picture_structure = hx->s.picture_structure;
  2898. for(i = 1; i < context_count; i++)
  2899. h->s.error_count += h->thread_context[i]->s.error_count;
  2900. }
  2901. }
  2902. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
  2903. MpegEncContext * const s = &h->s;
  2904. AVCodecContext * const avctx= s->avctx;
  2905. H264Context *hx; ///< thread context
  2906. int buf_index;
  2907. int context_count;
  2908. int next_avc;
  2909. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  2910. int nals_needed=0; ///< number of NALs that need decoding before the next frame thread starts
  2911. int nal_index;
  2912. h->max_contexts = (HAVE_THREADS && (s->avctx->active_thread_type&FF_THREAD_SLICE)) ? avctx->thread_count : 1;
  2913. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  2914. h->current_slice = 0;
  2915. if (!s->first_field)
  2916. s->current_picture_ptr= NULL;
  2917. ff_h264_reset_sei(h);
  2918. }
  2919. for(;pass <= 1;pass++){
  2920. buf_index = 0;
  2921. context_count = 0;
  2922. next_avc = h->is_avc ? 0 : buf_size;
  2923. nal_index = 0;
  2924. for(;;){
  2925. int consumed;
  2926. int dst_length;
  2927. int bit_length;
  2928. const uint8_t *ptr;
  2929. int i, nalsize = 0;
  2930. int err;
  2931. if(buf_index >= next_avc) {
  2932. if(buf_index >= buf_size) break;
  2933. nalsize = 0;
  2934. for(i = 0; i < h->nal_length_size; i++)
  2935. nalsize = (nalsize << 8) | buf[buf_index++];
  2936. if(nalsize <= 0 || nalsize > buf_size - buf_index){
  2937. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  2938. break;
  2939. }
  2940. next_avc= buf_index + nalsize;
  2941. } else {
  2942. // start code prefix search
  2943. for(; buf_index + 3 < next_avc; buf_index++){
  2944. // This should always succeed in the first iteration.
  2945. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  2946. break;
  2947. }
  2948. if(buf_index+3 >= buf_size) break;
  2949. buf_index+=3;
  2950. if(buf_index >= next_avc) continue;
  2951. }
  2952. hx = h->thread_context[context_count];
  2953. ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
  2954. if (ptr==NULL || dst_length < 0){
  2955. return -1;
  2956. }
  2957. i= buf_index + consumed;
  2958. if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
  2959. buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
  2960. s->workaround_bugs |= FF_BUG_TRUNCATED;
  2961. if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
  2962. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  2963. dst_length--;
  2964. }
  2965. bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
  2966. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  2967. av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d at %d/%d length %d\n", hx->nal_unit_type, buf_index, buf_size, dst_length);
  2968. }
  2969. if (h->is_avc && (nalsize != consumed) && nalsize){
  2970. av_log(h->s.avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  2971. }
  2972. buf_index += consumed;
  2973. nal_index++;
  2974. if(pass == 0) {
  2975. // packets can sometimes contain multiple PPS/SPS
  2976. // e.g. two PAFF field pictures in one packet, or a demuxer which splits NALs strangely
  2977. // if so, when frame threading we can't start the next thread until we've read all of them
  2978. switch (hx->nal_unit_type) {
  2979. case NAL_SPS:
  2980. case NAL_PPS:
  2981. nals_needed = nal_index;
  2982. }
  2983. continue;
  2984. }
  2985. //FIXME do not discard SEI id
  2986. if(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  2987. continue;
  2988. again:
  2989. err = 0;
  2990. switch(hx->nal_unit_type){
  2991. case NAL_IDR_SLICE:
  2992. if (h->nal_unit_type != NAL_IDR_SLICE) {
  2993. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  2994. return -1;
  2995. }
  2996. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  2997. case NAL_SLICE:
  2998. init_get_bits(&hx->s.gb, ptr, bit_length);
  2999. hx->intra_gb_ptr=
  3000. hx->inter_gb_ptr= &hx->s.gb;
  3001. hx->s.data_partitioning = 0;
  3002. if((err = decode_slice_header(hx, h)))
  3003. break;
  3004. s->current_picture_ptr->key_frame |=
  3005. (hx->nal_unit_type == NAL_IDR_SLICE) ||
  3006. (h->sei_recovery_frame_cnt >= 0);
  3007. if (h->current_slice == 1) {
  3008. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
  3009. decode_postinit(h, nal_index >= nals_needed);
  3010. }
  3011. if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
  3012. return -1;
  3013. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  3014. ff_vdpau_h264_picture_start(s);
  3015. }
  3016. if(hx->redundant_pic_count==0
  3017. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  3018. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=AV_PICTURE_TYPE_B)
  3019. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)
  3020. && avctx->skip_frame < AVDISCARD_ALL){
  3021. if(avctx->hwaccel) {
  3022. if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
  3023. return -1;
  3024. }else
  3025. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
  3026. static const uint8_t start_code[] = {0x00, 0x00, 0x01};
  3027. ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
  3028. ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
  3029. }else
  3030. context_count++;
  3031. }
  3032. break;
  3033. case NAL_DPA:
  3034. init_get_bits(&hx->s.gb, ptr, bit_length);
  3035. hx->intra_gb_ptr=
  3036. hx->inter_gb_ptr= NULL;
  3037. if ((err = decode_slice_header(hx, h)) < 0)
  3038. break;
  3039. hx->s.data_partitioning = 1;
  3040. break;
  3041. case NAL_DPB:
  3042. init_get_bits(&hx->intra_gb, ptr, bit_length);
  3043. hx->intra_gb_ptr= &hx->intra_gb;
  3044. break;
  3045. case NAL_DPC:
  3046. init_get_bits(&hx->inter_gb, ptr, bit_length);
  3047. hx->inter_gb_ptr= &hx->inter_gb;
  3048. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  3049. && s->context_initialized
  3050. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  3051. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=AV_PICTURE_TYPE_B)
  3052. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)
  3053. && avctx->skip_frame < AVDISCARD_ALL)
  3054. context_count++;
  3055. break;
  3056. case NAL_SEI:
  3057. init_get_bits(&s->gb, ptr, bit_length);
  3058. ff_h264_decode_sei(h);
  3059. break;
  3060. case NAL_SPS:
  3061. init_get_bits(&s->gb, ptr, bit_length);
  3062. ff_h264_decode_seq_parameter_set(h);
  3063. if(s->flags& CODEC_FLAG_LOW_DELAY)
  3064. s->low_delay=1;
  3065. if(avctx->has_b_frames < 2)
  3066. avctx->has_b_frames= !s->low_delay;
  3067. if (avctx->bits_per_raw_sample != h->sps.bit_depth_luma) {
  3068. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
  3069. avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  3070. h->pixel_shift = h->sps.bit_depth_luma > 8;
  3071. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma);
  3072. ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma);
  3073. dsputil_init(&s->dsp, s->avctx);
  3074. } else {
  3075. av_log(avctx, AV_LOG_DEBUG, "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
  3076. return -1;
  3077. }
  3078. }
  3079. break;
  3080. case NAL_PPS:
  3081. init_get_bits(&s->gb, ptr, bit_length);
  3082. ff_h264_decode_picture_parameter_set(h, bit_length);
  3083. break;
  3084. case NAL_AUD:
  3085. case NAL_END_SEQUENCE:
  3086. case NAL_END_STREAM:
  3087. case NAL_FILLER_DATA:
  3088. case NAL_SPS_EXT:
  3089. case NAL_AUXILIARY_SLICE:
  3090. break;
  3091. default:
  3092. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
  3093. }
  3094. if(context_count == h->max_contexts) {
  3095. execute_decode_slices(h, context_count);
  3096. context_count = 0;
  3097. }
  3098. if (err < 0)
  3099. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  3100. else if(err == 1) {
  3101. /* Slice could not be decoded in parallel mode, copy down
  3102. * NAL unit stuff to context 0 and restart. Note that
  3103. * rbsp_buffer is not transferred, but since we no longer
  3104. * run in parallel mode this should not be an issue. */
  3105. h->nal_unit_type = hx->nal_unit_type;
  3106. h->nal_ref_idc = hx->nal_ref_idc;
  3107. hx = h;
  3108. goto again;
  3109. }
  3110. }
  3111. }
  3112. if(context_count)
  3113. execute_decode_slices(h, context_count);
  3114. return buf_index;
  3115. }
  3116. /**
  3117. * returns the number of bytes consumed for building the current frame
  3118. */
  3119. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  3120. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  3121. if(pos+10>buf_size) pos=buf_size; // oops ;)
  3122. return pos;
  3123. }
  3124. static int decode_frame(AVCodecContext *avctx,
  3125. void *data, int *data_size,
  3126. AVPacket *avpkt)
  3127. {
  3128. const uint8_t *buf = avpkt->data;
  3129. int buf_size = avpkt->size;
  3130. H264Context *h = avctx->priv_data;
  3131. MpegEncContext *s = &h->s;
  3132. AVFrame *pict = data;
  3133. int buf_index;
  3134. s->flags= avctx->flags;
  3135. s->flags2= avctx->flags2;
  3136. /* end of stream, output what is still in the buffers */
  3137. out:
  3138. if (buf_size == 0) {
  3139. Picture *out;
  3140. int i, out_idx;
  3141. s->current_picture_ptr = NULL;
  3142. //FIXME factorize this with the output code below
  3143. out = h->delayed_pic[0];
  3144. out_idx = 0;
  3145. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  3146. if(h->delayed_pic[i]->poc < out->poc){
  3147. out = h->delayed_pic[i];
  3148. out_idx = i;
  3149. }
  3150. for(i=out_idx; h->delayed_pic[i]; i++)
  3151. h->delayed_pic[i] = h->delayed_pic[i+1];
  3152. if(out){
  3153. *data_size = sizeof(AVFrame);
  3154. *pict= *(AVFrame*)out;
  3155. }
  3156. return 0;
  3157. }
  3158. buf_index=decode_nal_units(h, buf, buf_size);
  3159. if(buf_index < 0)
  3160. return -1;
  3161. if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  3162. buf_size = 0;
  3163. goto out;
  3164. }
  3165. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  3166. if (avctx->skip_frame >= AVDISCARD_NONREF)
  3167. return 0;
  3168. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3169. return -1;
  3170. }
  3171. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  3172. if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h, 1);
  3173. field_end(h, 0);
  3174. if (!h->next_output_pic) {
  3175. /* Wait for second field. */
  3176. *data_size = 0;
  3177. } else {
  3178. *data_size = sizeof(AVFrame);
  3179. *pict = *(AVFrame*)h->next_output_pic;
  3180. }
  3181. }
  3182. assert(pict->data[0] || !*data_size);
  3183. ff_print_debug_info(s, pict);
  3184. //printf("out %d\n", (int)pict->data[0]);
  3185. return get_consumed_bytes(s, buf_index, buf_size);
  3186. }
  3187. #if 0
  3188. static inline void fill_mb_avail(H264Context *h){
  3189. MpegEncContext * const s = &h->s;
  3190. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3191. if(s->mb_y){
  3192. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  3193. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  3194. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  3195. }else{
  3196. h->mb_avail[0]=
  3197. h->mb_avail[1]=
  3198. h->mb_avail[2]= 0;
  3199. }
  3200. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  3201. h->mb_avail[4]= 1; //FIXME move out
  3202. h->mb_avail[5]= 0; //FIXME move out
  3203. }
  3204. #endif
  3205. #ifdef TEST
  3206. #undef printf
  3207. #undef random
  3208. #define COUNT 8000
  3209. #define SIZE (COUNT*40)
  3210. int main(void){
  3211. int i;
  3212. uint8_t temp[SIZE];
  3213. PutBitContext pb;
  3214. GetBitContext gb;
  3215. // int int_temp[10000];
  3216. DSPContext dsp;
  3217. AVCodecContext avctx;
  3218. dsputil_init(&dsp, &avctx);
  3219. init_put_bits(&pb, temp, SIZE);
  3220. printf("testing unsigned exp golomb\n");
  3221. for(i=0; i<COUNT; i++){
  3222. START_TIMER
  3223. set_ue_golomb(&pb, i);
  3224. STOP_TIMER("set_ue_golomb");
  3225. }
  3226. flush_put_bits(&pb);
  3227. init_get_bits(&gb, temp, 8*SIZE);
  3228. for(i=0; i<COUNT; i++){
  3229. int j, s;
  3230. s= show_bits(&gb, 24);
  3231. START_TIMER
  3232. j= get_ue_golomb(&gb);
  3233. if(j != i){
  3234. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  3235. // return -1;
  3236. }
  3237. STOP_TIMER("get_ue_golomb");
  3238. }
  3239. init_put_bits(&pb, temp, SIZE);
  3240. printf("testing signed exp golomb\n");
  3241. for(i=0; i<COUNT; i++){
  3242. START_TIMER
  3243. set_se_golomb(&pb, i - COUNT/2);
  3244. STOP_TIMER("set_se_golomb");
  3245. }
  3246. flush_put_bits(&pb);
  3247. init_get_bits(&gb, temp, 8*SIZE);
  3248. for(i=0; i<COUNT; i++){
  3249. int j, s;
  3250. s= show_bits(&gb, 24);
  3251. START_TIMER
  3252. j= get_se_golomb(&gb);
  3253. if(j != i - COUNT/2){
  3254. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  3255. // return -1;
  3256. }
  3257. STOP_TIMER("get_se_golomb");
  3258. }
  3259. #if 0
  3260. printf("testing 4x4 (I)DCT\n");
  3261. DCTELEM block[16];
  3262. uint8_t src[16], ref[16];
  3263. uint64_t error= 0, max_error=0;
  3264. for(i=0; i<COUNT; i++){
  3265. int j;
  3266. // printf("%d %d %d\n", r1, r2, (r2-r1)*16);
  3267. for(j=0; j<16; j++){
  3268. ref[j]= random()%255;
  3269. src[j]= random()%255;
  3270. }
  3271. h264_diff_dct_c(block, src, ref, 4);
  3272. //normalize
  3273. for(j=0; j<16; j++){
  3274. // printf("%d ", block[j]);
  3275. block[j]= block[j]*4;
  3276. if(j&1) block[j]= (block[j]*4 + 2)/5;
  3277. if(j&4) block[j]= (block[j]*4 + 2)/5;
  3278. }
  3279. // printf("\n");
  3280. h->h264dsp.h264_idct_add(ref, block, 4);
  3281. /* for(j=0; j<16; j++){
  3282. printf("%d ", ref[j]);
  3283. }
  3284. printf("\n");*/
  3285. for(j=0; j<16; j++){
  3286. int diff= FFABS(src[j] - ref[j]);
  3287. error+= diff*diff;
  3288. max_error= FFMAX(max_error, diff);
  3289. }
  3290. }
  3291. printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
  3292. printf("testing quantizer\n");
  3293. for(qp=0; qp<52; qp++){
  3294. for(i=0; i<16; i++)
  3295. src1_block[i]= src2_block[i]= random()%255;
  3296. }
  3297. printf("Testing NAL layer\n");
  3298. uint8_t bitstream[COUNT];
  3299. uint8_t nal[COUNT*2];
  3300. H264Context h;
  3301. memset(&h, 0, sizeof(H264Context));
  3302. for(i=0; i<COUNT; i++){
  3303. int zeros= i;
  3304. int nal_length;
  3305. int consumed;
  3306. int out_length;
  3307. uint8_t *out;
  3308. int j;
  3309. for(j=0; j<COUNT; j++){
  3310. bitstream[j]= (random() % 255) + 1;
  3311. }
  3312. for(j=0; j<zeros; j++){
  3313. int pos= random() % COUNT;
  3314. while(bitstream[pos] == 0){
  3315. pos++;
  3316. pos %= COUNT;
  3317. }
  3318. bitstream[pos]=0;
  3319. }
  3320. START_TIMER
  3321. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  3322. if(nal_length<0){
  3323. printf("encoding failed\n");
  3324. return -1;
  3325. }
  3326. out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
  3327. STOP_TIMER("NAL")
  3328. if(out_length != COUNT){
  3329. printf("incorrect length %d %d\n", out_length, COUNT);
  3330. return -1;
  3331. }
  3332. if(consumed != nal_length){
  3333. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  3334. return -1;
  3335. }
  3336. if(memcmp(bitstream, out, COUNT)){
  3337. printf("mismatch\n");
  3338. return -1;
  3339. }
  3340. }
  3341. #endif
  3342. printf("Testing RBSP\n");
  3343. return 0;
  3344. }
  3345. #endif /* TEST */
  3346. av_cold void ff_h264_free_context(H264Context *h)
  3347. {
  3348. int i;
  3349. free_tables(h, 1); //FIXME cleanup init stuff perhaps
  3350. for(i = 0; i < MAX_SPS_COUNT; i++)
  3351. av_freep(h->sps_buffers + i);
  3352. for(i = 0; i < MAX_PPS_COUNT; i++)
  3353. av_freep(h->pps_buffers + i);
  3354. }
  3355. av_cold int ff_h264_decode_end(AVCodecContext *avctx)
  3356. {
  3357. H264Context *h = avctx->priv_data;
  3358. MpegEncContext *s = &h->s;
  3359. ff_h264_free_context(h);
  3360. MPV_common_end(s);
  3361. // memset(h, 0, sizeof(H264Context));
  3362. return 0;
  3363. }
  3364. static const AVProfile profiles[] = {
  3365. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3366. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3367. { FF_PROFILE_H264_MAIN, "Main" },
  3368. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3369. { FF_PROFILE_H264_HIGH, "High" },
  3370. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3371. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3372. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3373. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3374. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3375. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3376. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3377. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3378. { FF_PROFILE_UNKNOWN },
  3379. };
  3380. AVCodec ff_h264_decoder = {
  3381. "h264",
  3382. AVMEDIA_TYPE_VIDEO,
  3383. CODEC_ID_H264,
  3384. sizeof(H264Context),
  3385. ff_h264_decode_init,
  3386. NULL,
  3387. ff_h264_decode_end,
  3388. decode_frame,
  3389. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY |
  3390. CODEC_CAP_SLICE_THREADS | CODEC_CAP_FRAME_THREADS,
  3391. .flush= flush_dpb,
  3392. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  3393. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  3394. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  3395. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3396. };
  3397. #if CONFIG_H264_VDPAU_DECODER
  3398. AVCodec ff_h264_vdpau_decoder = {
  3399. "h264_vdpau",
  3400. AVMEDIA_TYPE_VIDEO,
  3401. CODEC_ID_H264,
  3402. sizeof(H264Context),
  3403. ff_h264_decode_init,
  3404. NULL,
  3405. ff_h264_decode_end,
  3406. decode_frame,
  3407. CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  3408. .flush= flush_dpb,
  3409. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  3410. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
  3411. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3412. };
  3413. #endif