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.

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