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.

4335 lines
167KB

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