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.

4265 lines
166KB

  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 "cabac.h"
  31. #include "cabac_functions.h"
  32. #include "dsputil.h"
  33. #include "avcodec.h"
  34. #include "mpegvideo.h"
  35. #include "h264.h"
  36. #include "h264data.h"
  37. #include "h264_mvpred.h"
  38. #include "golomb.h"
  39. #include "mathops.h"
  40. #include "rectangle.h"
  41. #include "thread.h"
  42. #include "vdpau_internal.h"
  43. #include "libavutil/avassert.h"
  44. //#undef NDEBUG
  45. #include <assert.h>
  46. static const uint8_t rem6[QP_MAX_NUM+1]={
  47. 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,
  48. };
  49. static const uint8_t div6[QP_MAX_NUM+1]={
  50. 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,
  51. };
  52. static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
  53. PIX_FMT_DXVA2_VLD,
  54. PIX_FMT_VAAPI_VLD,
  55. PIX_FMT_VDA_VLD,
  56. PIX_FMT_YUVJ420P,
  57. PIX_FMT_NONE
  58. };
  59. /**
  60. * Check if the top & left blocks are available if needed and
  61. * change the dc mode so it only uses the available blocks.
  62. */
  63. int ff_h264_check_intra4x4_pred_mode(H264Context *h){
  64. MpegEncContext * const s = &h->s;
  65. static const int8_t top [12]= {-1, 0,LEFT_DC_PRED,-1,-1,-1,-1,-1, 0};
  66. static const int8_t left[12]= { 0,-1, TOP_DC_PRED, 0,-1,-1,-1, 0,-1,DC_128_PRED};
  67. int i;
  68. if(!(h->top_samples_available&0x8000)){
  69. for(i=0; i<4; i++){
  70. int status= top[ h->intra4x4_pred_mode_cache[scan8[0] + i] ];
  71. if(status<0){
  72. 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);
  73. return -1;
  74. } else if(status){
  75. h->intra4x4_pred_mode_cache[scan8[0] + i]= status;
  76. }
  77. }
  78. }
  79. if((h->left_samples_available&0x8888)!=0x8888){
  80. static const int mask[4]={0x8000,0x2000,0x80,0x20};
  81. for(i=0; i<4; i++){
  82. if(!(h->left_samples_available&mask[i])){
  83. int status= left[ h->intra4x4_pred_mode_cache[scan8[0] + 8*i] ];
  84. if(status<0){
  85. 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);
  86. return -1;
  87. } else if(status){
  88. h->intra4x4_pred_mode_cache[scan8[0] + 8*i]= status;
  89. }
  90. }
  91. }
  92. }
  93. return 0;
  94. } //FIXME cleanup like check_intra_pred_mode
  95. static int check_intra_pred_mode(H264Context *h, int mode, int is_chroma){
  96. MpegEncContext * const s = &h->s;
  97. static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};
  98. static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};
  99. if(mode > 6U) {
  100. 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);
  101. return -1;
  102. }
  103. if(!(h->top_samples_available&0x8000)){
  104. mode= top[ mode ];
  105. if(mode<0){
  106. 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);
  107. return -1;
  108. }
  109. }
  110. if((h->left_samples_available&0x8080) != 0x8080){
  111. mode= left[ mode ];
  112. if(is_chroma && (h->left_samples_available&0x8080)){ //mad cow disease mode, aka MBAFF + constrained_intra_pred
  113. mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);
  114. }
  115. if(mode<0){
  116. 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);
  117. return -1;
  118. }
  119. }
  120. return mode;
  121. }
  122. /**
  123. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  124. */
  125. int ff_h264_check_intra16x16_pred_mode(H264Context *h, int mode)
  126. {
  127. return check_intra_pred_mode(h, mode, 0);
  128. }
  129. /**
  130. * checks if the top & left blocks are available if needed & changes the dc mode so it only uses the available blocks.
  131. */
  132. int ff_h264_check_intra_chroma_pred_mode(H264Context *h, int mode)
  133. {
  134. return check_intra_pred_mode(h, mode, 1);
  135. }
  136. const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src, int *dst_length, int *consumed, int length){
  137. int i, si, di;
  138. uint8_t *dst;
  139. int bufidx;
  140. // src[0]&0x80; //forbidden bit
  141. h->nal_ref_idc= src[0]>>5;
  142. h->nal_unit_type= src[0]&0x1F;
  143. src++; length--;
  144. #if HAVE_FAST_UNALIGNED
  145. # if HAVE_FAST_64BIT
  146. # define RS 7
  147. for(i=0; i+1<length; i+=9){
  148. if(!((~AV_RN64A(src+i) & (AV_RN64A(src+i) - 0x0100010001000101ULL)) & 0x8000800080008080ULL))
  149. # else
  150. # define RS 3
  151. for(i=0; i+1<length; i+=5){
  152. if(!((~AV_RN32A(src+i) & (AV_RN32A(src+i) - 0x01000101U)) & 0x80008080U))
  153. # endif
  154. continue;
  155. if(i>0 && !src[i]) i--;
  156. while(src[i]) i++;
  157. #else
  158. # define RS 0
  159. for(i=0; i+1<length; i+=2){
  160. if(src[i]) continue;
  161. if(i>0 && src[i-1]==0) i--;
  162. #endif
  163. if(i+2<length && src[i+1]==0 && src[i+2]<=3){
  164. if(src[i+2]!=3){
  165. /* startcode, so we must be past the end */
  166. length=i;
  167. }
  168. break;
  169. }
  170. i-= RS;
  171. }
  172. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0; // use second escape buffer for inter data
  173. si=h->rbsp_buffer_size[bufidx];
  174. av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+FF_INPUT_BUFFER_PADDING_SIZE+MAX_MBPAIR_SIZE);
  175. dst= h->rbsp_buffer[bufidx];
  176. if(si != h->rbsp_buffer_size[bufidx])
  177. memset(dst + length, 0, FF_INPUT_BUFFER_PADDING_SIZE+MAX_MBPAIR_SIZE);
  178. if (dst == NULL){
  179. return NULL;
  180. }
  181. if(i>=length-1){ //no escaped 0
  182. *dst_length= length;
  183. *consumed= length+1; //+1 for the header
  184. if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
  185. return src;
  186. }else{
  187. memcpy(dst, src, length);
  188. return dst;
  189. }
  190. }
  191. //printf("decoding esc\n");
  192. memcpy(dst, src, i);
  193. si=di=i;
  194. while(si+2<length){
  195. //remove escapes (very rare 1:2^22)
  196. if(src[si+2]>3){
  197. dst[di++]= src[si++];
  198. dst[di++]= src[si++];
  199. }else if(src[si]==0 && src[si+1]==0){
  200. if(src[si+2]==3){ //escape
  201. dst[di++]= 0;
  202. dst[di++]= 0;
  203. si+=3;
  204. continue;
  205. }else //next start code
  206. goto nsc;
  207. }
  208. dst[di++]= src[si++];
  209. }
  210. while(si<length)
  211. dst[di++]= src[si++];
  212. nsc:
  213. memset(dst+di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  214. *dst_length= di;
  215. *consumed= si + 1;//+1 for the header
  216. //FIXME store exact number of bits in the getbitcontext (it is needed for decoding)
  217. return dst;
  218. }
  219. /**
  220. * Identify the exact end of the bitstream
  221. * @return the length of the trailing, or 0 if damaged
  222. */
  223. static int ff_h264_decode_rbsp_trailing(H264Context *h, const uint8_t *src){
  224. int v= *src;
  225. int r;
  226. tprintf(h->s.avctx, "rbsp trailing %X\n", v);
  227. for(r=1; r<9; r++){
  228. if(v&1) return r;
  229. v>>=1;
  230. }
  231. return 0;
  232. }
  233. static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n, int height,
  234. int y_offset, int list){
  235. int raw_my= h->mv_cache[list][ scan8[n] ][1];
  236. int filter_height= (raw_my&3) ? 2 : 0;
  237. int full_my= (raw_my>>2) + y_offset;
  238. int top = full_my - filter_height, bottom = full_my + height + filter_height;
  239. return FFMAX(abs(top), bottom);
  240. }
  241. static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n, int height,
  242. int y_offset, int list0, int list1, int *nrefs){
  243. MpegEncContext * const s = &h->s;
  244. int my;
  245. y_offset += 16*(s->mb_y >> MB_FIELD);
  246. if(list0){
  247. int ref_n = h->ref_cache[0][ scan8[n] ];
  248. Picture *ref= &h->ref_list[0][ref_n];
  249. // Error resilience puts the current picture in the ref list.
  250. // Don't try to wait on these as it will cause a deadlock.
  251. // Fields can wait on each other, though.
  252. if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
  253. (ref->f.reference & 3) != s->picture_structure) {
  254. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
  255. if (refs[0][ref_n] < 0) nrefs[0] += 1;
  256. refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
  257. }
  258. }
  259. if(list1){
  260. int ref_n = h->ref_cache[1][ scan8[n] ];
  261. Picture *ref= &h->ref_list[1][ref_n];
  262. if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
  263. (ref->f.reference & 3) != s->picture_structure) {
  264. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
  265. if (refs[1][ref_n] < 0) nrefs[1] += 1;
  266. refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
  267. }
  268. }
  269. }
  270. /**
  271. * Wait until all reference frames are available for MC operations.
  272. *
  273. * @param h the H264 context
  274. */
  275. static void await_references(H264Context *h){
  276. MpegEncContext * const s = &h->s;
  277. const int mb_xy= h->mb_xy;
  278. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  279. int refs[2][48];
  280. int nrefs[2] = {0};
  281. int ref, list;
  282. memset(refs, -1, sizeof(refs));
  283. if(IS_16X16(mb_type)){
  284. get_lowest_part_y(h, refs, 0, 16, 0,
  285. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  286. }else if(IS_16X8(mb_type)){
  287. get_lowest_part_y(h, refs, 0, 8, 0,
  288. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  289. get_lowest_part_y(h, refs, 8, 8, 8,
  290. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  291. }else if(IS_8X16(mb_type)){
  292. get_lowest_part_y(h, refs, 0, 16, 0,
  293. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  294. get_lowest_part_y(h, refs, 4, 16, 0,
  295. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  296. }else{
  297. int i;
  298. assert(IS_8X8(mb_type));
  299. for(i=0; i<4; i++){
  300. const int sub_mb_type= h->sub_mb_type[i];
  301. const int n= 4*i;
  302. int y_offset= (i&2)<<2;
  303. if(IS_SUB_8X8(sub_mb_type)){
  304. get_lowest_part_y(h, refs, n , 8, y_offset,
  305. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  306. }else if(IS_SUB_8X4(sub_mb_type)){
  307. get_lowest_part_y(h, refs, n , 4, y_offset,
  308. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  309. get_lowest_part_y(h, refs, n+2, 4, y_offset+4,
  310. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  311. }else if(IS_SUB_4X8(sub_mb_type)){
  312. get_lowest_part_y(h, refs, n , 8, y_offset,
  313. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  314. get_lowest_part_y(h, refs, n+1, 8, y_offset,
  315. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  316. }else{
  317. int j;
  318. assert(IS_SUB_4X4(sub_mb_type));
  319. for(j=0; j<4; j++){
  320. int sub_y_offset= y_offset + 2*(j&2);
  321. get_lowest_part_y(h, refs, n+j, 4, sub_y_offset,
  322. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1), nrefs);
  323. }
  324. }
  325. }
  326. }
  327. for(list=h->list_count-1; list>=0; list--){
  328. for(ref=0; ref<48 && nrefs[list]; ref++){
  329. int row = refs[list][ref];
  330. if(row >= 0){
  331. Picture *ref_pic = &h->ref_list[list][ref];
  332. int ref_field = ref_pic->f.reference - 1;
  333. int ref_field_picture = ref_pic->field_picture;
  334. int pic_height = 16*s->mb_height >> ref_field_picture;
  335. row <<= MB_MBAFF;
  336. nrefs[list]--;
  337. if(!FIELD_PICTURE && ref_field_picture){ // frame referencing two fields
  338. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) - !(row&1), pic_height-1), 1);
  339. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN((row >> 1) , pic_height-1), 0);
  340. }else if(FIELD_PICTURE && !ref_field_picture){ // field referencing one field of a frame
  341. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row*2 + ref_field , pic_height-1), 0);
  342. }else if(FIELD_PICTURE){
  343. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), ref_field);
  344. }else{
  345. ff_thread_await_progress((AVFrame*)ref_pic, FFMIN(row, pic_height-1), 0);
  346. }
  347. }
  348. }
  349. }
  350. }
  351. #if 0
  352. /**
  353. * DCT transforms the 16 dc values.
  354. * @param qp quantization parameter ??? FIXME
  355. */
  356. static void h264_luma_dc_dct_c(DCTELEM *block/*, int qp*/){
  357. // const int qmul= dequant_coeff[qp][0];
  358. int i;
  359. int temp[16]; //FIXME check if this is a good idea
  360. static const int x_offset[4]={0, 1*stride, 4* stride, 5*stride};
  361. static const int y_offset[4]={0, 2*stride, 8* stride, 10*stride};
  362. for(i=0; i<4; i++){
  363. const int offset= y_offset[i];
  364. const int z0= block[offset+stride*0] + block[offset+stride*4];
  365. const int z1= block[offset+stride*0] - block[offset+stride*4];
  366. const int z2= block[offset+stride*1] - block[offset+stride*5];
  367. const int z3= block[offset+stride*1] + block[offset+stride*5];
  368. temp[4*i+0]= z0+z3;
  369. temp[4*i+1]= z1+z2;
  370. temp[4*i+2]= z1-z2;
  371. temp[4*i+3]= z0-z3;
  372. }
  373. for(i=0; i<4; i++){
  374. const int offset= x_offset[i];
  375. const int z0= temp[4*0+i] + temp[4*2+i];
  376. const int z1= temp[4*0+i] - temp[4*2+i];
  377. const int z2= temp[4*1+i] - temp[4*3+i];
  378. const int z3= temp[4*1+i] + temp[4*3+i];
  379. block[stride*0 +offset]= (z0 + z3)>>1;
  380. block[stride*2 +offset]= (z1 + z2)>>1;
  381. block[stride*8 +offset]= (z1 - z2)>>1;
  382. block[stride*10+offset]= (z0 - z3)>>1;
  383. }
  384. }
  385. #endif
  386. #undef xStride
  387. #undef stride
  388. #if 0
  389. static void chroma_dc_dct_c(DCTELEM *block){
  390. const int stride= 16*2;
  391. const int xStride= 16;
  392. int a,b,c,d,e;
  393. a= block[stride*0 + xStride*0];
  394. b= block[stride*0 + xStride*1];
  395. c= block[stride*1 + xStride*0];
  396. d= block[stride*1 + xStride*1];
  397. e= a-b;
  398. a= a+b;
  399. b= c-d;
  400. c= c+d;
  401. block[stride*0 + xStride*0]= (a+c);
  402. block[stride*0 + xStride*1]= (e+b);
  403. block[stride*1 + xStride*0]= (a-c);
  404. block[stride*1 + xStride*1]= (e-b);
  405. }
  406. #endif
  407. static av_always_inline void
  408. mc_dir_part(H264Context *h, Picture *pic, int n, int square,
  409. int height, int delta, int list,
  410. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  411. int src_x_offset, int src_y_offset,
  412. qpel_mc_func *qpix_op, h264_chroma_mc_func chroma_op,
  413. int pixel_shift, int chroma_idc)
  414. {
  415. MpegEncContext * const s = &h->s;
  416. const int mx= h->mv_cache[list][ scan8[n] ][0] + src_x_offset*8;
  417. int my= h->mv_cache[list][ scan8[n] ][1] + src_y_offset*8;
  418. const int luma_xy= (mx&3) + ((my&3)<<2);
  419. int offset = ((mx>>2) << pixel_shift) + (my>>2)*h->mb_linesize;
  420. uint8_t * src_y = pic->f.data[0] + offset;
  421. uint8_t * src_cb, * src_cr;
  422. int extra_width= h->emu_edge_width;
  423. int extra_height= h->emu_edge_height;
  424. int emu=0;
  425. const int full_mx= mx>>2;
  426. const int full_my= my>>2;
  427. const int pic_width = 16*s->mb_width;
  428. const int pic_height = 16*s->mb_height >> MB_FIELD;
  429. int ysh;
  430. if(mx&7) extra_width -= 3;
  431. if(my&7) extra_height -= 3;
  432. if( full_mx < 0-extra_width
  433. || full_my < 0-extra_height
  434. || full_mx + 16/*FIXME*/ > pic_width + extra_width
  435. || full_my + 16/*FIXME*/ > pic_height + extra_height){
  436. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_y - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
  437. 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
  438. src_y= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
  439. emu=1;
  440. }
  441. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); //FIXME try variable height perhaps?
  442. if(!square){
  443. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  444. }
  445. if(CONFIG_GRAY && s->flags&CODEC_FLAG_GRAY) return;
  446. if(chroma_idc == 3 /* yuv444 */){
  447. src_cb = pic->f.data[1] + offset;
  448. if(emu){
  449. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
  450. 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
  451. src_cb= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
  452. }
  453. qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); //FIXME try variable height perhaps?
  454. if(!square){
  455. qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
  456. }
  457. src_cr = pic->f.data[2] + offset;
  458. if(emu){
  459. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr - (2 << pixel_shift) - 2*h->mb_linesize, h->mb_linesize,
  460. 16+5, 16+5/*FIXME*/, full_mx-2, full_my-2, pic_width, pic_height);
  461. src_cr= s->edge_emu_buffer + (2 << pixel_shift) + 2*h->mb_linesize;
  462. }
  463. qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); //FIXME try variable height perhaps?
  464. if(!square){
  465. qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
  466. }
  467. return;
  468. }
  469. ysh = 3 - (chroma_idc == 2 /* yuv422 */);
  470. if(chroma_idc == 1 /* yuv420 */ && MB_FIELD){
  471. // chroma offset when predicting from a field of opposite parity
  472. my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
  473. emu |= (my>>3) < 0 || (my>>3) + 8 >= (pic_height>>1);
  474. }
  475. src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) + (my >> ysh) * h->mb_uvlinesize;
  476. src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) + (my >> ysh) * h->mb_uvlinesize;
  477. if(emu){
  478. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
  479. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  480. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  481. src_cb= s->edge_emu_buffer;
  482. }
  483. chroma_op(dest_cb, src_cb, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
  484. mx&7, (my << (chroma_idc == 2 /* yuv422 */)) &7);
  485. if(emu){
  486. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
  487. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  488. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  489. src_cr= s->edge_emu_buffer;
  490. }
  491. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
  492. mx&7, (my << (chroma_idc == 2 /* yuv422 */)) &7);
  493. }
  494. static av_always_inline void
  495. mc_part_std(H264Context *h, int n, int square, int height, int delta,
  496. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  497. int x_offset, int y_offset,
  498. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  499. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  500. int list0, int list1, int pixel_shift, int chroma_idc)
  501. {
  502. MpegEncContext * const s = &h->s;
  503. qpel_mc_func *qpix_op= qpix_put;
  504. h264_chroma_mc_func chroma_op= chroma_put;
  505. dest_y += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
  506. if (chroma_idc == 3 /* yuv444 */) {
  507. dest_cb += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
  508. dest_cr += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
  509. } else if (chroma_idc == 2 /* yuv422 */) {
  510. dest_cb += ( x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
  511. dest_cr += ( x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
  512. } else /* yuv420 */ {
  513. dest_cb += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
  514. dest_cr += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
  515. }
  516. x_offset += 8*s->mb_x;
  517. y_offset += 8*(s->mb_y >> MB_FIELD);
  518. if(list0){
  519. Picture *ref= &h->ref_list[0][ h->ref_cache[0][ scan8[n] ] ];
  520. mc_dir_part(h, ref, n, square, height, delta, 0,
  521. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  522. qpix_op, chroma_op, pixel_shift, chroma_idc);
  523. qpix_op= qpix_avg;
  524. chroma_op= chroma_avg;
  525. }
  526. if(list1){
  527. Picture *ref= &h->ref_list[1][ h->ref_cache[1][ scan8[n] ] ];
  528. mc_dir_part(h, ref, n, square, height, delta, 1,
  529. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  530. qpix_op, chroma_op, pixel_shift, chroma_idc);
  531. }
  532. }
  533. static av_always_inline void
  534. mc_part_weighted(H264Context *h, int n, int square, int height, int delta,
  535. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  536. int x_offset, int y_offset,
  537. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  538. h264_weight_func luma_weight_op, h264_weight_func chroma_weight_op,
  539. h264_biweight_func luma_weight_avg, h264_biweight_func chroma_weight_avg,
  540. int list0, int list1, int pixel_shift, int chroma_idc){
  541. MpegEncContext * const s = &h->s;
  542. int chroma_height;
  543. dest_y += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
  544. if (chroma_idc == 3 /* yuv444 */) {
  545. chroma_height = height;
  546. chroma_weight_avg = luma_weight_avg;
  547. chroma_weight_op = luma_weight_op;
  548. dest_cb += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
  549. dest_cr += (2*x_offset << pixel_shift) + 2*y_offset*h->mb_linesize;
  550. } else if (chroma_idc == 2 /* yuv422 */) {
  551. chroma_height = height;
  552. dest_cb += ( x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
  553. dest_cr += ( x_offset << pixel_shift) + 2*y_offset*h->mb_uvlinesize;
  554. } else /* yuv420 */ {
  555. chroma_height = height >> 1;
  556. dest_cb += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
  557. dest_cr += ( x_offset << pixel_shift) + y_offset*h->mb_uvlinesize;
  558. }
  559. x_offset += 8*s->mb_x;
  560. y_offset += 8*(s->mb_y >> MB_FIELD);
  561. if(list0 && list1){
  562. /* don't optimize for luma-only case, since B-frames usually
  563. * use implicit weights => chroma too. */
  564. uint8_t *tmp_cb = s->obmc_scratchpad;
  565. uint8_t *tmp_cr = s->obmc_scratchpad + (16 << pixel_shift);
  566. uint8_t *tmp_y = s->obmc_scratchpad + 16*h->mb_uvlinesize;
  567. int refn0 = h->ref_cache[0][ scan8[n] ];
  568. int refn1 = h->ref_cache[1][ scan8[n] ];
  569. mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
  570. dest_y, dest_cb, dest_cr,
  571. x_offset, y_offset, qpix_put, chroma_put,
  572. pixel_shift, chroma_idc);
  573. mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
  574. tmp_y, tmp_cb, tmp_cr,
  575. x_offset, y_offset, qpix_put, chroma_put,
  576. pixel_shift, chroma_idc);
  577. if(h->use_weight == 2){
  578. int weight0 = h->implicit_weight[refn0][refn1][s->mb_y&1];
  579. int weight1 = 64 - weight0;
  580. luma_weight_avg( dest_y, tmp_y, h-> mb_linesize,
  581. height, 5, weight0, weight1, 0);
  582. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
  583. chroma_height, 5, weight0, weight1, 0);
  584. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
  585. chroma_height, 5, weight0, weight1, 0);
  586. }else{
  587. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height, h->luma_log2_weight_denom,
  588. h->luma_weight[refn0][0][0] , h->luma_weight[refn1][1][0],
  589. h->luma_weight[refn0][0][1] + h->luma_weight[refn1][1][1]);
  590. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
  591. h->chroma_weight[refn0][0][0][0] , h->chroma_weight[refn1][1][0][0],
  592. h->chroma_weight[refn0][0][0][1] + h->chroma_weight[refn1][1][0][1]);
  593. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
  594. h->chroma_weight[refn0][0][1][0] , h->chroma_weight[refn1][1][1][0],
  595. h->chroma_weight[refn0][0][1][1] + h->chroma_weight[refn1][1][1][1]);
  596. }
  597. }else{
  598. int list = list1 ? 1 : 0;
  599. int refn = h->ref_cache[list][ scan8[n] ];
  600. Picture *ref= &h->ref_list[list][refn];
  601. mc_dir_part(h, ref, n, square, height, delta, list,
  602. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  603. qpix_put, chroma_put, pixel_shift, chroma_idc);
  604. luma_weight_op(dest_y, h->mb_linesize, height, h->luma_log2_weight_denom,
  605. h->luma_weight[refn][list][0], h->luma_weight[refn][list][1]);
  606. if(h->use_weight_chroma){
  607. chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
  608. h->chroma_weight[refn][list][0][0], h->chroma_weight[refn][list][0][1]);
  609. chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height, h->chroma_log2_weight_denom,
  610. h->chroma_weight[refn][list][1][0], h->chroma_weight[refn][list][1][1]);
  611. }
  612. }
  613. }
  614. static av_always_inline void
  615. mc_part(H264Context *h, int n, int square, int height, int delta,
  616. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  617. int x_offset, int y_offset,
  618. qpel_mc_func *qpix_put, h264_chroma_mc_func chroma_put,
  619. qpel_mc_func *qpix_avg, h264_chroma_mc_func chroma_avg,
  620. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  621. int list0, int list1, int pixel_shift, int chroma_idc)
  622. {
  623. if((h->use_weight==2 && list0 && list1
  624. && (h->implicit_weight[ h->ref_cache[0][scan8[n]] ][ h->ref_cache[1][scan8[n]] ][h->s.mb_y&1] != 32))
  625. || h->use_weight==1)
  626. mc_part_weighted(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
  627. x_offset, y_offset, qpix_put, chroma_put,
  628. weight_op[0], weight_op[1], weight_avg[0],
  629. weight_avg[1], list0, list1, pixel_shift, chroma_idc);
  630. else
  631. mc_part_std(h, n, square, height, delta, dest_y, dest_cb, dest_cr,
  632. x_offset, y_offset, qpix_put, chroma_put, qpix_avg,
  633. chroma_avg, list0, list1, pixel_shift, chroma_idc);
  634. }
  635. static av_always_inline void
  636. prefetch_motion(H264Context *h, int list, int pixel_shift, int chroma_idc)
  637. {
  638. /* fetch pixels for estimated mv 4 macroblocks ahead
  639. * optimized for 64byte cache lines */
  640. MpegEncContext * const s = &h->s;
  641. const int refn = h->ref_cache[list][scan8[0]];
  642. if(refn >= 0){
  643. const int mx= (h->mv_cache[list][scan8[0]][0]>>2) + 16*s->mb_x + 8;
  644. const int my= (h->mv_cache[list][scan8[0]][1]>>2) + 16*s->mb_y;
  645. uint8_t **src = h->ref_list[list][refn].f.data;
  646. int off= (mx << pixel_shift) + (my + (s->mb_x&3)*4)*h->mb_linesize + (64 << pixel_shift);
  647. s->dsp.prefetch(src[0]+off, s->linesize, 4);
  648. if (chroma_idc == 3 /* yuv444 */) {
  649. s->dsp.prefetch(src[1]+off, s->linesize, 4);
  650. s->dsp.prefetch(src[2]+off, s->linesize, 4);
  651. }else{
  652. off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
  653. s->dsp.prefetch(src[1]+off, src[2]-src[1], 2);
  654. }
  655. }
  656. }
  657. static av_always_inline void hl_motion(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  658. qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
  659. qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
  660. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  661. int pixel_shift, int chroma_idc)
  662. {
  663. MpegEncContext * const s = &h->s;
  664. const int mb_xy= h->mb_xy;
  665. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  666. assert(IS_INTER(mb_type));
  667. if(HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))
  668. await_references(h);
  669. prefetch_motion(h, 0, pixel_shift, chroma_idc);
  670. if(IS_16X16(mb_type)){
  671. mc_part(h, 0, 1, 16, 0, dest_y, dest_cb, dest_cr, 0, 0,
  672. qpix_put[0], chroma_put[0], qpix_avg[0], chroma_avg[0],
  673. weight_op, weight_avg,
  674. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
  675. pixel_shift, chroma_idc);
  676. }else if(IS_16X8(mb_type)){
  677. mc_part(h, 0, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 0,
  678. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  679. weight_op, weight_avg,
  680. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
  681. pixel_shift, chroma_idc);
  682. mc_part(h, 8, 0, 8, 8 << pixel_shift, dest_y, dest_cb, dest_cr, 0, 4,
  683. qpix_put[1], chroma_put[0], qpix_avg[1], chroma_avg[0],
  684. weight_op, weight_avg,
  685. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
  686. pixel_shift, chroma_idc);
  687. }else if(IS_8X16(mb_type)){
  688. mc_part(h, 0, 0, 16, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 0, 0,
  689. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  690. &weight_op[1], &weight_avg[1],
  691. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1),
  692. pixel_shift, chroma_idc);
  693. mc_part(h, 4, 0, 16, 8*h->mb_linesize, dest_y, dest_cb, dest_cr, 4, 0,
  694. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  695. &weight_op[1], &weight_avg[1],
  696. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1),
  697. pixel_shift, chroma_idc);
  698. }else{
  699. int i;
  700. assert(IS_8X8(mb_type));
  701. for(i=0; i<4; i++){
  702. const int sub_mb_type= h->sub_mb_type[i];
  703. const int n= 4*i;
  704. int x_offset= (i&1)<<2;
  705. int y_offset= (i&2)<<1;
  706. if(IS_SUB_8X8(sub_mb_type)){
  707. mc_part(h, n, 1, 8, 0, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  708. qpix_put[1], chroma_put[1], qpix_avg[1], chroma_avg[1],
  709. &weight_op[1], &weight_avg[1],
  710. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  711. pixel_shift, chroma_idc);
  712. }else if(IS_SUB_8X4(sub_mb_type)){
  713. mc_part(h, n , 0, 4, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  714. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  715. &weight_op[1], &weight_avg[1],
  716. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  717. pixel_shift, chroma_idc);
  718. mc_part(h, n+2, 0, 4, 4 << pixel_shift, dest_y, dest_cb, dest_cr, x_offset, y_offset+2,
  719. qpix_put[2], chroma_put[1], qpix_avg[2], chroma_avg[1],
  720. &weight_op[1], &weight_avg[1],
  721. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  722. pixel_shift, chroma_idc);
  723. }else if(IS_SUB_4X8(sub_mb_type)){
  724. mc_part(h, n , 0, 8, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset, y_offset,
  725. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  726. &weight_op[2], &weight_avg[2],
  727. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  728. pixel_shift, chroma_idc);
  729. mc_part(h, n+1, 0, 8, 4*h->mb_linesize, dest_y, dest_cb, dest_cr, x_offset+2, y_offset,
  730. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  731. &weight_op[2], &weight_avg[2],
  732. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  733. pixel_shift, chroma_idc);
  734. }else{
  735. int j;
  736. assert(IS_SUB_4X4(sub_mb_type));
  737. for(j=0; j<4; j++){
  738. int sub_x_offset= x_offset + 2*(j&1);
  739. int sub_y_offset= y_offset + (j&2);
  740. mc_part(h, n+j, 1, 4, 0, dest_y, dest_cb, dest_cr, sub_x_offset, sub_y_offset,
  741. qpix_put[2], chroma_put[2], qpix_avg[2], chroma_avg[2],
  742. &weight_op[2], &weight_avg[2],
  743. IS_DIR(sub_mb_type, 0, 0), IS_DIR(sub_mb_type, 0, 1),
  744. pixel_shift, chroma_idc);
  745. }
  746. }
  747. }
  748. }
  749. prefetch_motion(h, 1, pixel_shift, chroma_idc);
  750. }
  751. static av_always_inline void
  752. hl_motion_420(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  753. qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
  754. qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
  755. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  756. int pixel_shift)
  757. {
  758. hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
  759. qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 1);
  760. }
  761. static av_always_inline void
  762. hl_motion_422(H264Context *h, uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  763. qpel_mc_func (*qpix_put)[16], h264_chroma_mc_func (*chroma_put),
  764. qpel_mc_func (*qpix_avg)[16], h264_chroma_mc_func (*chroma_avg),
  765. h264_weight_func *weight_op, h264_biweight_func *weight_avg,
  766. int pixel_shift)
  767. {
  768. hl_motion(h, dest_y, dest_cb, dest_cr, qpix_put, chroma_put,
  769. qpix_avg, chroma_avg, weight_op, weight_avg, pixel_shift, 2);
  770. }
  771. static void free_tables(H264Context *h, int free_rbsp){
  772. int i;
  773. H264Context *hx;
  774. av_freep(&h->intra4x4_pred_mode);
  775. av_freep(&h->chroma_pred_mode_table);
  776. av_freep(&h->cbp_table);
  777. av_freep(&h->mvd_table[0]);
  778. av_freep(&h->mvd_table[1]);
  779. av_freep(&h->direct_table);
  780. av_freep(&h->non_zero_count);
  781. av_freep(&h->slice_table_base);
  782. h->slice_table= NULL;
  783. av_freep(&h->list_counts);
  784. av_freep(&h->mb2b_xy);
  785. av_freep(&h->mb2br_xy);
  786. for(i = 0; i < MAX_THREADS; i++) {
  787. hx = h->thread_context[i];
  788. if(!hx) continue;
  789. av_freep(&hx->top_borders[1]);
  790. av_freep(&hx->top_borders[0]);
  791. av_freep(&hx->s.obmc_scratchpad);
  792. if (free_rbsp){
  793. av_freep(&hx->rbsp_buffer[1]);
  794. av_freep(&hx->rbsp_buffer[0]);
  795. hx->rbsp_buffer_size[0] = 0;
  796. hx->rbsp_buffer_size[1] = 0;
  797. }
  798. if (i) av_freep(&h->thread_context[i]);
  799. }
  800. }
  801. static void init_dequant8_coeff_table(H264Context *h){
  802. int i,j,q,x;
  803. const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
  804. for(i=0; i<6; i++ ){
  805. h->dequant8_coeff[i] = h->dequant8_buffer[i];
  806. for(j=0; j<i; j++){
  807. if(!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i], 64*sizeof(uint8_t))){
  808. h->dequant8_coeff[i] = h->dequant8_buffer[j];
  809. break;
  810. }
  811. }
  812. if(j<i)
  813. continue;
  814. for(q=0; q<max_qp+1; q++){
  815. int shift = div6[q];
  816. int idx = rem6[q];
  817. for(x=0; x<64; x++)
  818. h->dequant8_coeff[i][q][(x>>3)|((x&7)<<3)] =
  819. ((uint32_t)dequant8_coeff_init[idx][ dequant8_coeff_init_scan[((x>>1)&12) | (x&3)] ] *
  820. h->pps.scaling_matrix8[i][x]) << shift;
  821. }
  822. }
  823. }
  824. static void init_dequant4_coeff_table(H264Context *h){
  825. int i,j,q,x;
  826. const int max_qp = 51 + 6*(h->sps.bit_depth_luma-8);
  827. for(i=0; i<6; i++ ){
  828. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  829. for(j=0; j<i; j++){
  830. if(!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i], 16*sizeof(uint8_t))){
  831. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  832. break;
  833. }
  834. }
  835. if(j<i)
  836. continue;
  837. for(q=0; q<max_qp+1; q++){
  838. int shift = div6[q] + 2;
  839. int idx = rem6[q];
  840. for(x=0; x<16; x++)
  841. h->dequant4_coeff[i][q][(x>>2)|((x<<2)&0xF)] =
  842. ((uint32_t)dequant4_coeff_init[idx][(x&1) + ((x>>2)&1)] *
  843. h->pps.scaling_matrix4[i][x]) << shift;
  844. }
  845. }
  846. }
  847. static void init_dequant_tables(H264Context *h){
  848. int i,x;
  849. init_dequant4_coeff_table(h);
  850. if(h->pps.transform_8x8_mode)
  851. init_dequant8_coeff_table(h);
  852. if(h->sps.transform_bypass){
  853. for(i=0; i<6; i++)
  854. for(x=0; x<16; x++)
  855. h->dequant4_coeff[i][0][x] = 1<<6;
  856. if(h->pps.transform_8x8_mode)
  857. for(i=0; i<6; i++)
  858. for(x=0; x<64; x++)
  859. h->dequant8_coeff[i][0][x] = 1<<6;
  860. }
  861. }
  862. int ff_h264_alloc_tables(H264Context *h){
  863. MpegEncContext * const s = &h->s;
  864. const int big_mb_num= s->mb_stride * (s->mb_height+1);
  865. const int row_mb_num= 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
  866. int x,y;
  867. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode, row_mb_num * 8 * sizeof(uint8_t), fail)
  868. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count , big_mb_num * 48 * sizeof(uint8_t), fail)
  869. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base), fail)
  870. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table, big_mb_num * sizeof(uint16_t), fail)
  871. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t), fail)
  872. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0], 16*row_mb_num * sizeof(uint8_t), fail);
  873. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1], 16*row_mb_num * sizeof(uint8_t), fail);
  874. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table, 4*big_mb_num * sizeof(uint8_t) , fail);
  875. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts, big_mb_num * sizeof(uint8_t), fail)
  876. memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base));
  877. h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;
  878. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy , big_mb_num * sizeof(uint32_t), fail);
  879. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy , big_mb_num * sizeof(uint32_t), fail);
  880. for(y=0; y<s->mb_height; y++){
  881. for(x=0; x<s->mb_width; x++){
  882. const int mb_xy= x + y*s->mb_stride;
  883. const int b_xy = 4*x + 4*y*h->b_stride;
  884. h->mb2b_xy [mb_xy]= b_xy;
  885. h->mb2br_xy[mb_xy]= 8*(FMO ? mb_xy : (mb_xy % (2*s->mb_stride)));
  886. }
  887. }
  888. s->obmc_scratchpad = NULL;
  889. if(!h->dequant4_coeff[0])
  890. init_dequant_tables(h);
  891. return 0;
  892. fail:
  893. free_tables(h, 1);
  894. return -1;
  895. }
  896. /**
  897. * Mimic alloc_tables(), but for every context thread.
  898. */
  899. static void clone_tables(H264Context *dst, H264Context *src, int i){
  900. MpegEncContext * const s = &src->s;
  901. dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i*8*2*s->mb_stride;
  902. dst->non_zero_count = src->non_zero_count;
  903. dst->slice_table = src->slice_table;
  904. dst->cbp_table = src->cbp_table;
  905. dst->mb2b_xy = src->mb2b_xy;
  906. dst->mb2br_xy = src->mb2br_xy;
  907. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  908. dst->mvd_table[0] = src->mvd_table[0] + i*8*2*s->mb_stride;
  909. dst->mvd_table[1] = src->mvd_table[1] + i*8*2*s->mb_stride;
  910. dst->direct_table = src->direct_table;
  911. dst->list_counts = src->list_counts;
  912. dst->s.obmc_scratchpad = NULL;
  913. ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma, src->sps.chroma_format_idc);
  914. }
  915. /**
  916. * Init context
  917. * Allocate buffers which are not shared amongst multiple threads.
  918. */
  919. static int context_init(H264Context *h){
  920. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0], h->s.mb_width * 16*3 * sizeof(uint8_t)*2, fail)
  921. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1], h->s.mb_width * 16*3 * sizeof(uint8_t)*2, fail)
  922. h->ref_cache[0][scan8[5 ]+1] = h->ref_cache[0][scan8[7 ]+1] = h->ref_cache[0][scan8[13]+1] =
  923. h->ref_cache[1][scan8[5 ]+1] = h->ref_cache[1][scan8[7 ]+1] = h->ref_cache[1][scan8[13]+1] = PART_NOT_AVAILABLE;
  924. return 0;
  925. fail:
  926. return -1; // free_tables will clean up for us
  927. }
  928. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
  929. static av_cold void common_init(H264Context *h){
  930. MpegEncContext * const s = &h->s;
  931. s->width = s->avctx->width;
  932. s->height = s->avctx->height;
  933. s->codec_id= s->avctx->codec->id;
  934. s->avctx->bits_per_raw_sample = 8;
  935. h->cur_chroma_format_idc = 1;
  936. ff_h264dsp_init(&h->h264dsp,
  937. s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
  938. ff_h264_pred_init(&h->hpc, s->codec_id,
  939. s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
  940. h->dequant_coeff_pps= -1;
  941. s->unrestricted_mv=1;
  942. s->dsp.dct_bits = 16;
  943. dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early
  944. memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));
  945. memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));
  946. }
  947. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  948. {
  949. AVCodecContext *avctx = h->s.avctx;
  950. if(!buf || size <= 0)
  951. return -1;
  952. if(buf[0] == 1){
  953. int i, cnt, nalsize;
  954. const unsigned char *p = buf;
  955. h->is_avc = 1;
  956. if(size < 7) {
  957. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  958. return -1;
  959. }
  960. /* sps and pps in the avcC always have length coded with 2 bytes,
  961. so put a fake nal_length_size = 2 while parsing them */
  962. h->nal_length_size = 2;
  963. // Decode sps from avcC
  964. cnt = *(p+5) & 0x1f; // Number of sps
  965. p += 6;
  966. for (i = 0; i < cnt; i++) {
  967. nalsize = AV_RB16(p) + 2;
  968. if(nalsize > size - (p-buf))
  969. return -1;
  970. if(decode_nal_units(h, p, nalsize) < 0) {
  971. av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);
  972. return -1;
  973. }
  974. p += nalsize;
  975. }
  976. // Decode pps from avcC
  977. cnt = *(p++); // Number of pps
  978. for (i = 0; i < cnt; i++) {
  979. nalsize = AV_RB16(p) + 2;
  980. if(nalsize > size - (p-buf))
  981. return -1;
  982. if (decode_nal_units(h, p, nalsize) < 0) {
  983. av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);
  984. return -1;
  985. }
  986. p += nalsize;
  987. }
  988. // Now store right nal length size, that will be use to parse all other nals
  989. h->nal_length_size = (buf[4] & 0x03) + 1;
  990. } else {
  991. h->is_avc = 0;
  992. if(decode_nal_units(h, buf, size) < 0)
  993. return -1;
  994. }
  995. return size;
  996. }
  997. av_cold int ff_h264_decode_init(AVCodecContext *avctx){
  998. H264Context *h= avctx->priv_data;
  999. MpegEncContext * const s = &h->s;
  1000. int i;
  1001. MPV_decode_defaults(s);
  1002. s->avctx = avctx;
  1003. common_init(h);
  1004. s->out_format = FMT_H264;
  1005. s->workaround_bugs= avctx->workaround_bugs;
  1006. // set defaults
  1007. // s->decode_mb= ff_h263_decode_mb;
  1008. s->quarter_sample = 1;
  1009. if(!avctx->has_b_frames)
  1010. s->low_delay= 1;
  1011. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  1012. ff_h264_decode_init_vlc();
  1013. h->pixel_shift = 0;
  1014. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  1015. h->thread_context[0] = h;
  1016. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  1017. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  1018. h->last_pocs[i] = INT_MIN;
  1019. h->prev_poc_msb= 1<<16;
  1020. h->prev_frame_num= -1;
  1021. h->x264_build = -1;
  1022. ff_h264_reset_sei(h);
  1023. if(avctx->codec_id == CODEC_ID_H264){
  1024. if(avctx->ticks_per_frame == 1){
  1025. s->avctx->time_base.den *=2;
  1026. }
  1027. avctx->ticks_per_frame = 2;
  1028. }
  1029. if(avctx->extradata_size > 0 && avctx->extradata &&
  1030. ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size)<0)
  1031. return -1;
  1032. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  1033. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  1034. s->low_delay = 0;
  1035. }
  1036. return 0;
  1037. }
  1038. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b)+(size))))
  1039. static void copy_picture_range(Picture **to, Picture **from, int count, MpegEncContext *new_base, MpegEncContext *old_base)
  1040. {
  1041. int i;
  1042. for (i=0; i<count; i++){
  1043. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  1044. IN_RANGE(from[i], old_base->picture, sizeof(Picture) * old_base->picture_count) ||
  1045. !from[i]));
  1046. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  1047. }
  1048. }
  1049. static void copy_parameter_set(void **to, void **from, int count, int size)
  1050. {
  1051. int i;
  1052. for (i=0; i<count; i++){
  1053. if (to[i] && !from[i]) av_freep(&to[i]);
  1054. else if (from[i] && !to[i]) to[i] = av_malloc(size);
  1055. if (from[i]) memcpy(to[i], from[i], size);
  1056. }
  1057. }
  1058. static int decode_init_thread_copy(AVCodecContext *avctx){
  1059. H264Context *h= avctx->priv_data;
  1060. if (!avctx->internal->is_copy)
  1061. return 0;
  1062. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1063. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1064. return 0;
  1065. }
  1066. #define copy_fields(to, from, start_field, end_field) memcpy(&to->start_field, &from->start_field, (char*)&to->end_field - (char*)&to->start_field)
  1067. static int decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src){
  1068. H264Context *h= dst->priv_data, *h1= src->priv_data;
  1069. MpegEncContext * const s = &h->s, * const s1 = &h1->s;
  1070. int inited = s->context_initialized, err;
  1071. int i;
  1072. if(dst == src) return 0;
  1073. err = ff_mpeg_update_thread_context(dst, src);
  1074. if(err) return err;
  1075. //FIXME handle width/height changing
  1076. if(!inited){
  1077. for(i = 0; i < MAX_SPS_COUNT; i++)
  1078. av_freep(h->sps_buffers + i);
  1079. for(i = 0; i < MAX_PPS_COUNT; i++)
  1080. av_freep(h->pps_buffers + i);
  1081. memcpy(&h->s + 1, &h1->s + 1, sizeof(H264Context) - sizeof(MpegEncContext)); //copy all fields after MpegEnc
  1082. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1083. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1084. if (s1->context_initialized) {
  1085. if (ff_h264_alloc_tables(h) < 0) {
  1086. av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
  1087. return AVERROR(ENOMEM);
  1088. }
  1089. context_init(h);
  1090. // frame_start may not be called for the next thread (if it's decoding a bottom field)
  1091. // so this has to be allocated here
  1092. h->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
  1093. }
  1094. for(i=0; i<2; i++){
  1095. h->rbsp_buffer[i] = NULL;
  1096. h->rbsp_buffer_size[i] = 0;
  1097. }
  1098. h->thread_context[0] = h;
  1099. s->dsp.clear_blocks(h->mb);
  1100. s->dsp.clear_blocks(h->mb+(24*16<<h->pixel_shift));
  1101. }
  1102. //extradata/NAL handling
  1103. h->is_avc = h1->is_avc;
  1104. //SPS/PPS
  1105. copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
  1106. h->sps = h1->sps;
  1107. copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
  1108. h->pps = h1->pps;
  1109. //Dequantization matrices
  1110. //FIXME these are big - can they be only copied when PPS changes?
  1111. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  1112. for(i=0; i<6; i++)
  1113. h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  1114. for(i=0; i<6; i++)
  1115. h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  1116. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  1117. //POC timing
  1118. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  1119. //reference lists
  1120. copy_fields(h, h1, ref_count, list_count);
  1121. copy_fields(h, h1, ref_list, intra_gb);
  1122. copy_fields(h, h1, short_ref, cabac_init_idc);
  1123. copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
  1124. copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
  1125. copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
  1126. h->last_slice_type = h1->last_slice_type;
  1127. h->sync = h1->sync;
  1128. if(!s->current_picture_ptr) return 0;
  1129. if(!s->dropable) {
  1130. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1131. h->prev_poc_msb = h->poc_msb;
  1132. h->prev_poc_lsb = h->poc_lsb;
  1133. }
  1134. h->prev_frame_num_offset= h->frame_num_offset;
  1135. h->prev_frame_num = h->frame_num;
  1136. h->outputed_poc = h->next_outputed_poc;
  1137. return err;
  1138. }
  1139. int ff_h264_frame_start(H264Context *h){
  1140. MpegEncContext * const s = &h->s;
  1141. int i;
  1142. const int pixel_shift = h->pixel_shift;
  1143. if(MPV_frame_start(s, s->avctx) < 0)
  1144. return -1;
  1145. ff_er_frame_start(s);
  1146. /*
  1147. * MPV_frame_start uses pict_type to derive key_frame.
  1148. * This is incorrect for H.264; IDR markings must be used.
  1149. * Zero here; IDR markings per slice in frame or fields are ORed in later.
  1150. * See decode_nal_units().
  1151. */
  1152. s->current_picture_ptr->f.key_frame = 0;
  1153. s->current_picture_ptr->sync = 0;
  1154. s->current_picture_ptr->mmco_reset= 0;
  1155. assert(s->linesize && s->uvlinesize);
  1156. for(i=0; i<16; i++){
  1157. h->block_offset[i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
  1158. h->block_offset[48+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
  1159. }
  1160. for(i=0; i<16; i++){
  1161. h->block_offset[16+i]=
  1162. h->block_offset[32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1163. h->block_offset[48+16+i]=
  1164. h->block_offset[48+32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1165. }
  1166. /* can't be in alloc_tables because linesize isn't known there.
  1167. * FIXME: redo bipred weight to not require extra buffer? */
  1168. for(i = 0; i < s->slice_context_count; i++)
  1169. if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
  1170. h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
  1171. /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
  1172. memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
  1173. // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.f.reference /*|| h->contains_intra*/ || 1;
  1174. // We mark the current picture as non-reference after allocating it, so
  1175. // that if we break out due to an error it can be released automatically
  1176. // in the next MPV_frame_start().
  1177. // SVQ3 as well as most other codecs have only last/next/current and thus
  1178. // get released even with set reference, besides SVQ3 and others do not
  1179. // mark frames as reference later "naturally".
  1180. if(s->codec_id != CODEC_ID_SVQ3)
  1181. s->current_picture_ptr->f.reference = 0;
  1182. s->current_picture_ptr->field_poc[0]=
  1183. s->current_picture_ptr->field_poc[1]= INT_MAX;
  1184. h->next_output_pic = NULL;
  1185. assert(s->current_picture_ptr->long_ref==0);
  1186. return 0;
  1187. }
  1188. /**
  1189. * Run setup operations that must be run after slice header decoding.
  1190. * This includes finding the next displayed frame.
  1191. *
  1192. * @param h h264 master context
  1193. * @param setup_finished enough NALs have been read that we can call
  1194. * ff_thread_finish_setup()
  1195. */
  1196. static void decode_postinit(H264Context *h, int setup_finished){
  1197. MpegEncContext * const s = &h->s;
  1198. Picture *out = s->current_picture_ptr;
  1199. Picture *cur = s->current_picture_ptr;
  1200. int i, pics, out_of_order, out_idx;
  1201. s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
  1202. s->current_picture_ptr->f.pict_type = s->pict_type;
  1203. if (h->next_output_pic) return;
  1204. if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
  1205. //FIXME: if we have two PAFF fields in one packet, we can't start the next thread here.
  1206. //If we have one field per packet, we can. The check in decode_nal_units() is not good enough
  1207. //to find this yet, so we assume the worst for now.
  1208. //if (setup_finished)
  1209. // ff_thread_finish_setup(s->avctx);
  1210. return;
  1211. }
  1212. cur->f.interlaced_frame = 0;
  1213. cur->f.repeat_pict = 0;
  1214. /* Signal interlacing information externally. */
  1215. /* Prioritize picture timing SEI information over used decoding process if it exists. */
  1216. if(h->sps.pic_struct_present_flag){
  1217. switch (h->sei_pic_struct)
  1218. {
  1219. case SEI_PIC_STRUCT_FRAME:
  1220. break;
  1221. case SEI_PIC_STRUCT_TOP_FIELD:
  1222. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1223. cur->f.interlaced_frame = 1;
  1224. break;
  1225. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1226. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1227. if (FIELD_OR_MBAFF_PICTURE)
  1228. cur->f.interlaced_frame = 1;
  1229. else
  1230. // try to flag soft telecine progressive
  1231. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1232. break;
  1233. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1234. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1235. // Signal the possibility of telecined film externally (pic_struct 5,6)
  1236. // From these hints, let the applications decide if they apply deinterlacing.
  1237. cur->f.repeat_pict = 1;
  1238. break;
  1239. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1240. // Force progressive here, as doubling interlaced frame is a bad idea.
  1241. cur->f.repeat_pict = 2;
  1242. break;
  1243. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1244. cur->f.repeat_pict = 4;
  1245. break;
  1246. }
  1247. if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1248. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1249. }else{
  1250. /* Derive interlacing flag from used decoding process. */
  1251. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1252. }
  1253. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1254. if (cur->field_poc[0] != cur->field_poc[1]){
  1255. /* Derive top_field_first from field pocs. */
  1256. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1257. }else{
  1258. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1259. /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
  1260. if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
  1261. || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1262. cur->f.top_field_first = 1;
  1263. else
  1264. cur->f.top_field_first = 0;
  1265. }else{
  1266. /* Most likely progressive */
  1267. cur->f.top_field_first = 0;
  1268. }
  1269. }
  1270. cur->mmco_reset = h->mmco_reset;
  1271. h->mmco_reset = 0;
  1272. //FIXME do something with unavailable reference frames
  1273. /* Sort B-frames into display order */
  1274. if(h->sps.bitstream_restriction_flag
  1275. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  1276. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  1277. s->low_delay = 0;
  1278. }
  1279. if( s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
  1280. && !h->sps.bitstream_restriction_flag){
  1281. s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1282. s->low_delay= 0;
  1283. }
  1284. for (i = 0; 1; i++) {
  1285. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1286. if(i)
  1287. h->last_pocs[i-1] = cur->poc;
  1288. break;
  1289. } else if(i) {
  1290. h->last_pocs[i-1]= h->last_pocs[i];
  1291. }
  1292. }
  1293. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1294. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1295. || (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))
  1296. out_of_order = FFMAX(out_of_order, 1);
  1297. if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1298. av_log(s->avctx, AV_LOG_WARNING, "Increasing reorder buffer to %d\n", out_of_order);
  1299. s->avctx->has_b_frames = out_of_order;
  1300. s->low_delay = 0;
  1301. }
  1302. pics = 0;
  1303. while(h->delayed_pic[pics]) pics++;
  1304. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1305. h->delayed_pic[pics++] = cur;
  1306. if (cur->f.reference == 0)
  1307. cur->f.reference = DELAYED_PIC_REF;
  1308. out = h->delayed_pic[0];
  1309. out_idx = 0;
  1310. for (i = 1; h->delayed_pic[i] && !h->delayed_pic[i]->f.key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  1311. if(h->delayed_pic[i]->poc < out->poc){
  1312. out = h->delayed_pic[i];
  1313. out_idx = i;
  1314. }
  1315. if (s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1316. h->next_outputed_poc= INT_MIN;
  1317. out_of_order = out->poc < h->next_outputed_poc;
  1318. if(out_of_order || pics > s->avctx->has_b_frames){
  1319. out->f.reference &= ~DELAYED_PIC_REF;
  1320. out->owner2 = s; // for frame threading, the owner must be the second field's thread
  1321. // or else the first thread can release the picture and reuse it unsafely
  1322. for(i=out_idx; h->delayed_pic[i]; i++)
  1323. h->delayed_pic[i] = h->delayed_pic[i+1];
  1324. }
  1325. if(!out_of_order && pics > s->avctx->has_b_frames){
  1326. h->next_output_pic = out;
  1327. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1328. h->next_outputed_poc = INT_MIN;
  1329. } else
  1330. h->next_outputed_poc = out->poc;
  1331. }else{
  1332. av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1333. }
  1334. if (h->next_output_pic && h->next_output_pic->sync) {
  1335. h->sync |= 2;
  1336. }
  1337. if (setup_finished)
  1338. ff_thread_finish_setup(s->avctx);
  1339. }
  1340. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1341. uint8_t *src_cb, uint8_t *src_cr,
  1342. int linesize, int uvlinesize, int simple)
  1343. {
  1344. MpegEncContext * const s = &h->s;
  1345. uint8_t *top_border;
  1346. int top_idx = 1;
  1347. const int pixel_shift = h->pixel_shift;
  1348. int chroma444 = CHROMA444;
  1349. int chroma422 = CHROMA422;
  1350. src_y -= linesize;
  1351. src_cb -= uvlinesize;
  1352. src_cr -= uvlinesize;
  1353. if(!simple && FRAME_MBAFF){
  1354. if(s->mb_y&1){
  1355. if(!MB_MBAFF){
  1356. top_border = h->top_borders[0][s->mb_x];
  1357. AV_COPY128(top_border, src_y + 15*linesize);
  1358. if (pixel_shift)
  1359. AV_COPY128(top_border+16, src_y+15*linesize+16);
  1360. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1361. if(chroma444){
  1362. if (pixel_shift){
  1363. AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
  1364. AV_COPY128(top_border+48, src_cb + 15*uvlinesize+16);
  1365. AV_COPY128(top_border+64, src_cr + 15*uvlinesize);
  1366. AV_COPY128(top_border+80, src_cr + 15*uvlinesize+16);
  1367. } else {
  1368. AV_COPY128(top_border+16, src_cb + 15*uvlinesize);
  1369. AV_COPY128(top_border+32, src_cr + 15*uvlinesize);
  1370. }
  1371. } else if(chroma422){
  1372. if (pixel_shift) {
  1373. AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
  1374. AV_COPY128(top_border+48, src_cr + 15*uvlinesize);
  1375. } else {
  1376. AV_COPY64(top_border+16, src_cb + 15*uvlinesize);
  1377. AV_COPY64(top_border+24, src_cr + 15*uvlinesize);
  1378. }
  1379. } else {
  1380. if (pixel_shift) {
  1381. AV_COPY128(top_border+32, src_cb+7*uvlinesize);
  1382. AV_COPY128(top_border+48, src_cr+7*uvlinesize);
  1383. } else {
  1384. AV_COPY64(top_border+16, src_cb+7*uvlinesize);
  1385. AV_COPY64(top_border+24, src_cr+7*uvlinesize);
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }else if(MB_MBAFF){
  1391. top_idx = 0;
  1392. }else
  1393. return;
  1394. }
  1395. top_border = h->top_borders[top_idx][s->mb_x];
  1396. // There are two lines saved, the line above the the top macroblock of a pair,
  1397. // and the line above the bottom macroblock
  1398. AV_COPY128(top_border, src_y + 16*linesize);
  1399. if (pixel_shift)
  1400. AV_COPY128(top_border+16, src_y+16*linesize+16);
  1401. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1402. if(chroma444){
  1403. if (pixel_shift){
  1404. AV_COPY128(top_border+32, src_cb + 16*linesize);
  1405. AV_COPY128(top_border+48, src_cb + 16*linesize+16);
  1406. AV_COPY128(top_border+64, src_cr + 16*linesize);
  1407. AV_COPY128(top_border+80, src_cr + 16*linesize+16);
  1408. } else {
  1409. AV_COPY128(top_border+16, src_cb + 16*linesize);
  1410. AV_COPY128(top_border+32, src_cr + 16*linesize);
  1411. }
  1412. } else if(chroma422) {
  1413. if (pixel_shift) {
  1414. AV_COPY128(top_border+32, src_cb+16*uvlinesize);
  1415. AV_COPY128(top_border+48, src_cr+16*uvlinesize);
  1416. } else {
  1417. AV_COPY64(top_border+16, src_cb+16*uvlinesize);
  1418. AV_COPY64(top_border+24, src_cr+16*uvlinesize);
  1419. }
  1420. } else {
  1421. if (pixel_shift) {
  1422. AV_COPY128(top_border+32, src_cb+8*uvlinesize);
  1423. AV_COPY128(top_border+48, src_cr+8*uvlinesize);
  1424. } else {
  1425. AV_COPY64(top_border+16, src_cb+8*uvlinesize);
  1426. AV_COPY64(top_border+24, src_cr+8*uvlinesize);
  1427. }
  1428. }
  1429. }
  1430. }
  1431. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1432. uint8_t *src_cb, uint8_t *src_cr,
  1433. int linesize, int uvlinesize,
  1434. int xchg, int chroma444,
  1435. int simple, int pixel_shift){
  1436. MpegEncContext * const s = &h->s;
  1437. int deblock_topleft;
  1438. int deblock_top;
  1439. int top_idx = 1;
  1440. uint8_t *top_border_m1;
  1441. uint8_t *top_border;
  1442. if(!simple && FRAME_MBAFF){
  1443. if(s->mb_y&1){
  1444. if(!MB_MBAFF)
  1445. return;
  1446. }else{
  1447. top_idx = MB_MBAFF ? 0 : 1;
  1448. }
  1449. }
  1450. if(h->deblocking_filter == 2) {
  1451. deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
  1452. deblock_top = h->top_type;
  1453. } else {
  1454. deblock_topleft = (s->mb_x > 0);
  1455. deblock_top = (s->mb_y > !!MB_FIELD);
  1456. }
  1457. src_y -= linesize + 1 + pixel_shift;
  1458. src_cb -= uvlinesize + 1 + pixel_shift;
  1459. src_cr -= uvlinesize + 1 + pixel_shift;
  1460. top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
  1461. top_border = h->top_borders[top_idx][s->mb_x];
  1462. #define XCHG(a,b,xchg)\
  1463. if (pixel_shift) {\
  1464. if (xchg) {\
  1465. AV_SWAP64(b+0,a+0);\
  1466. AV_SWAP64(b+8,a+8);\
  1467. } else {\
  1468. AV_COPY128(b,a); \
  1469. }\
  1470. } else \
  1471. if (xchg) AV_SWAP64(b,a);\
  1472. else AV_COPY64(b,a);
  1473. if(deblock_top){
  1474. if(deblock_topleft){
  1475. XCHG(top_border_m1 + (8 << pixel_shift), src_y - (7 << pixel_shift), 1);
  1476. }
  1477. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1478. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1479. if(s->mb_x+1 < s->mb_width){
  1480. XCHG(h->top_borders[top_idx][s->mb_x+1], src_y + (17 << pixel_shift), 1);
  1481. }
  1482. }
  1483. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1484. if(chroma444){
  1485. if(deblock_topleft){
  1486. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1487. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1488. }
  1489. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  1490. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  1491. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  1492. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  1493. if(s->mb_x+1 < s->mb_width){
  1494. XCHG(h->top_borders[top_idx][s->mb_x+1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  1495. XCHG(h->top_borders[top_idx][s->mb_x+1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  1496. }
  1497. } else {
  1498. if(deblock_top){
  1499. if(deblock_topleft){
  1500. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1501. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1502. }
  1503. XCHG(top_border + (16 << pixel_shift), src_cb+1+pixel_shift, 1);
  1504. XCHG(top_border + (24 << pixel_shift), src_cr+1+pixel_shift, 1);
  1505. }
  1506. }
  1507. }
  1508. }
  1509. static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth, int index) {
  1510. if (high_bit_depth) {
  1511. return AV_RN32A(((int32_t*)mb) + index);
  1512. } else
  1513. return AV_RN16A(mb + index);
  1514. }
  1515. static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth, int index, int value) {
  1516. if (high_bit_depth) {
  1517. AV_WN32A(((int32_t*)mb) + index, value);
  1518. } else
  1519. AV_WN16A(mb + index, value);
  1520. }
  1521. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
  1522. int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
  1523. {
  1524. MpegEncContext * const s = &h->s;
  1525. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1526. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  1527. int i;
  1528. int qscale = p == 0 ? s->qscale : h->chroma_qp[p-1];
  1529. block_offset += 16*p;
  1530. if(IS_INTRA4x4(mb_type)){
  1531. if(simple || !s->encoding){
  1532. if(IS_8x8DCT(mb_type)){
  1533. if(transform_bypass){
  1534. idct_dc_add =
  1535. idct_add = s->dsp.add_pixels8;
  1536. }else{
  1537. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1538. idct_add = h->h264dsp.h264_idct8_add;
  1539. }
  1540. for(i=0; i<16; i+=4){
  1541. uint8_t * const ptr= dest_y + block_offset[i];
  1542. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  1543. if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
  1544. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1545. }else{
  1546. const int nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
  1547. h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
  1548. (h->topright_samples_available<<i)&0x4000, linesize);
  1549. if(nnz){
  1550. if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
  1551. idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1552. else
  1553. idct_add (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1554. }
  1555. }
  1556. }
  1557. }else{
  1558. if(transform_bypass){
  1559. idct_dc_add =
  1560. idct_add = s->dsp.add_pixels4;
  1561. }else{
  1562. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1563. idct_add = h->h264dsp.h264_idct_add;
  1564. }
  1565. for(i=0; i<16; i++){
  1566. uint8_t * const ptr= dest_y + block_offset[i];
  1567. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  1568. if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
  1569. h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1570. }else{
  1571. uint8_t *topright;
  1572. int nnz, tr;
  1573. uint64_t tr_high;
  1574. if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
  1575. const int topright_avail= (h->topright_samples_available<<i)&0x8000;
  1576. assert(s->mb_y || linesize <= block_offset[i]);
  1577. if(!topright_avail){
  1578. if (pixel_shift) {
  1579. tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
  1580. topright= (uint8_t*) &tr_high;
  1581. } else {
  1582. tr= ptr[3 - linesize]*0x01010101u;
  1583. topright= (uint8_t*) &tr;
  1584. }
  1585. }else
  1586. topright= ptr + (4 << pixel_shift) - linesize;
  1587. }else
  1588. topright= NULL;
  1589. h->hpc.pred4x4[ dir ](ptr, topright, linesize);
  1590. nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
  1591. if(nnz){
  1592. if(is_h264){
  1593. if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
  1594. idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1595. else
  1596. idct_add (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1597. } else if (CONFIG_SVQ3_DECODER)
  1598. ff_svq3_add_idct_c(ptr, h->mb + i*16+p*256, linesize, qscale, 0);
  1599. }
  1600. }
  1601. }
  1602. }
  1603. }
  1604. }else{
  1605. h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
  1606. if(is_h264){
  1607. if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX+p] ]){
  1608. if(!transform_bypass)
  1609. h->h264dsp.h264_luma_dc_dequant_idct(h->mb+(p*256 << pixel_shift), h->mb_luma_dc[p], h->dequant4_coeff[p][qscale][0]);
  1610. else{
  1611. static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
  1612. 8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
  1613. for(i = 0; i < 16; i++)
  1614. dctcoef_set(h->mb+(p*256 << pixel_shift), pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc[p], pixel_shift, i));
  1615. }
  1616. }
  1617. } else if (CONFIG_SVQ3_DECODER)
  1618. ff_svq3_luma_dc_dequant_idct_c(h->mb+p*256, h->mb_luma_dc[p], qscale);
  1619. }
  1620. }
  1621. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
  1622. int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
  1623. {
  1624. MpegEncContext * const s = &h->s;
  1625. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1626. int i;
  1627. block_offset += 16*p;
  1628. if(!IS_INTRA4x4(mb_type)){
  1629. if(is_h264){
  1630. if(IS_INTRA16x16(mb_type)){
  1631. if(transform_bypass){
  1632. if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
  1633. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize);
  1634. }else{
  1635. for(i=0; i<16; i++){
  1636. if(h->non_zero_count_cache[ scan8[i+p*16] ] || dctcoef_get(h->mb, pixel_shift, i*16+p*256))
  1637. s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
  1638. }
  1639. }
  1640. }else{
  1641. h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
  1642. }
  1643. }else if(h->cbp&15){
  1644. if(transform_bypass){
  1645. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  1646. idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
  1647. for(i=0; i<16; i+=di){
  1648. if(h->non_zero_count_cache[ scan8[i+p*16] ]){
  1649. idct_add(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
  1650. }
  1651. }
  1652. }else{
  1653. if(IS_8x8DCT(mb_type)){
  1654. h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
  1655. }else{
  1656. h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
  1657. }
  1658. }
  1659. }
  1660. } else if (CONFIG_SVQ3_DECODER) {
  1661. for(i=0; i<16; i++){
  1662. if(h->non_zero_count_cache[ scan8[i+p*16] ] || h->mb[i*16+p*256]){ //FIXME benchmark weird rule, & below
  1663. uint8_t * const ptr= dest_y + block_offset[i];
  1664. ff_svq3_add_idct_c(ptr, h->mb + i*16 + p*256, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  1665. }
  1666. }
  1667. }
  1668. }
  1669. }
  1670. static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, int pixel_shift)
  1671. {
  1672. MpegEncContext * const s = &h->s;
  1673. const int mb_x= s->mb_x;
  1674. const int mb_y= s->mb_y;
  1675. const int mb_xy= h->mb_xy;
  1676. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  1677. uint8_t *dest_y, *dest_cb, *dest_cr;
  1678. int linesize, uvlinesize /*dct_offset*/;
  1679. int i, j;
  1680. int *block_offset = &h->block_offset[0];
  1681. const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
  1682. /* is_h264 should always be true if SVQ3 is disabled. */
  1683. const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
  1684. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1685. const int block_h = 16 >> s->chroma_y_shift;
  1686. const int chroma422 = CHROMA422;
  1687. dest_y = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize ) * 16;
  1688. dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift)*8 + mb_y * s->uvlinesize * block_h;
  1689. dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift)*8 + mb_y * s->uvlinesize * block_h;
  1690. s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
  1691. s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
  1692. h->list_counts[mb_xy]= h->list_count;
  1693. if (!simple && MB_FIELD) {
  1694. linesize = h->mb_linesize = s->linesize * 2;
  1695. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  1696. block_offset = &h->block_offset[48];
  1697. if(mb_y&1){ //FIXME move out of this function?
  1698. dest_y -= s->linesize*15;
  1699. dest_cb-= s->uvlinesize * (block_h - 1);
  1700. dest_cr-= s->uvlinesize * (block_h - 1);
  1701. }
  1702. if(FRAME_MBAFF) {
  1703. int list;
  1704. for(list=0; list<h->list_count; list++){
  1705. if(!USES_LIST(mb_type, list))
  1706. continue;
  1707. if(IS_16X16(mb_type)){
  1708. int8_t *ref = &h->ref_cache[list][scan8[0]];
  1709. fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
  1710. }else{
  1711. for(i=0; i<16; i+=4){
  1712. int ref = h->ref_cache[list][scan8[i]];
  1713. if(ref >= 0)
  1714. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
  1715. }
  1716. }
  1717. }
  1718. }
  1719. } else {
  1720. linesize = h->mb_linesize = s->linesize;
  1721. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  1722. // dct_offset = s->linesize * 16;
  1723. }
  1724. if (!simple && IS_INTRA_PCM(mb_type)) {
  1725. const int bit_depth = h->sps.bit_depth_luma;
  1726. if (pixel_shift) {
  1727. int j;
  1728. GetBitContext gb;
  1729. init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
  1730. for (i = 0; i < 16; i++) {
  1731. uint16_t *tmp_y = (uint16_t*)(dest_y + i*linesize);
  1732. for (j = 0; j < 16; j++)
  1733. tmp_y[j] = get_bits(&gb, bit_depth);
  1734. }
  1735. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1736. if (!h->sps.chroma_format_idc) {
  1737. for (i = 0; i < block_h; i++) {
  1738. uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
  1739. uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
  1740. for (j = 0; j < 8; j++) {
  1741. tmp_cb[j] = tmp_cr[j] = 1 << (bit_depth - 1);
  1742. }
  1743. }
  1744. } else {
  1745. for (i = 0; i < block_h; i++) {
  1746. uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
  1747. for (j = 0; j < 8; j++)
  1748. tmp_cb[j] = get_bits(&gb, bit_depth);
  1749. }
  1750. for (i = 0; i < block_h; i++) {
  1751. uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
  1752. for (j = 0; j < 8; j++)
  1753. tmp_cr[j] = get_bits(&gb, bit_depth);
  1754. }
  1755. }
  1756. }
  1757. } else {
  1758. for (i=0; i<16; i++) {
  1759. memcpy(dest_y + i* linesize, h->mb + i*8, 16);
  1760. }
  1761. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1762. if (!h->sps.chroma_format_idc) {
  1763. for (i=0; i<8; i++) {
  1764. memset(dest_cb + i*uvlinesize, 1 << (bit_depth - 1), 8);
  1765. memset(dest_cr + i*uvlinesize, 1 << (bit_depth - 1), 8);
  1766. }
  1767. } else {
  1768. for (i=0; i<block_h; i++) {
  1769. memcpy(dest_cb + i*uvlinesize, h->mb + 128 + i*4, 8);
  1770. memcpy(dest_cr + i*uvlinesize, h->mb + 160 + i*4, 8);
  1771. }
  1772. }
  1773. }
  1774. }
  1775. } else {
  1776. if(IS_INTRA(mb_type)){
  1777. if(h->deblocking_filter)
  1778. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, 0, simple, pixel_shift);
  1779. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1780. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
  1781. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
  1782. }
  1783. hl_decode_mb_predict_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
  1784. if(h->deblocking_filter)
  1785. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, 0, simple, pixel_shift);
  1786. }else if(is_h264){
  1787. if (chroma422) {
  1788. hl_motion_422(h, dest_y, dest_cb, dest_cr,
  1789. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  1790. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  1791. h->h264dsp.weight_h264_pixels_tab,
  1792. h->h264dsp.biweight_h264_pixels_tab,
  1793. pixel_shift);
  1794. } else {
  1795. hl_motion_420(h, dest_y, dest_cb, dest_cr,
  1796. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  1797. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  1798. h->h264dsp.weight_h264_pixels_tab,
  1799. h->h264dsp.biweight_h264_pixels_tab,
  1800. pixel_shift);
  1801. }
  1802. }
  1803. hl_decode_mb_idct_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
  1804. if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
  1805. uint8_t *dest[2] = {dest_cb, dest_cr};
  1806. if(transform_bypass){
  1807. if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
  1808. h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + (16*16*1 << pixel_shift), uvlinesize);
  1809. h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 32, h->mb + (16*16*2 << pixel_shift), uvlinesize);
  1810. }else{
  1811. idct_add = s->dsp.add_pixels4;
  1812. for(j=1; j<3; j++){
  1813. for(i=j*16; i<j*16+4; i++){
  1814. if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
  1815. idct_add (dest[j-1] + block_offset[i], h->mb + (i*16 << pixel_shift), uvlinesize);
  1816. }
  1817. if (chroma422) {
  1818. for(i=j*16+4; i<j*16+8; i++){
  1819. if(h->non_zero_count_cache[ scan8[i+4] ] || dctcoef_get(h->mb, pixel_shift, i*16))
  1820. idct_add (dest[j-1] + block_offset[i+4], h->mb + (i*16 << pixel_shift), uvlinesize);
  1821. }
  1822. }
  1823. }
  1824. }
  1825. }else{
  1826. if(is_h264){
  1827. int qp[2];
  1828. if (chroma422) {
  1829. qp[0] = h->chroma_qp[0] + 3;
  1830. qp[1] = h->chroma_qp[1] + 3;
  1831. } else {
  1832. qp[0] = h->chroma_qp[0];
  1833. qp[1] = h->chroma_qp[1];
  1834. }
  1835. if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
  1836. 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]);
  1837. if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
  1838. 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]);
  1839. h->h264dsp.h264_idct_add8(dest, block_offset,
  1840. h->mb, uvlinesize,
  1841. h->non_zero_count_cache);
  1842. } else if (CONFIG_SVQ3_DECODER) {
  1843. 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]);
  1844. 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]);
  1845. for(j=1; j<3; j++){
  1846. for(i=j*16; i<j*16+4; i++){
  1847. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
  1848. uint8_t * const ptr= dest[j-1] + block_offset[i];
  1849. ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
  1850. }
  1851. }
  1852. }
  1853. }
  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 || (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
  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->err_recognition & AV_EF_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 = 0;
  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_index;
  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. goto out;
  3619. }
  3620. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  3621. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  3622. buf_size >= 4 && !memcmp("Q264", buf, 4))
  3623. return buf_size;
  3624. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3625. return -1;
  3626. }
  3627. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  3628. if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h, 1);
  3629. field_end(h, 0);
  3630. *data_size = 0; /* Wait for second field. */
  3631. if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
  3632. *data_size = sizeof(AVFrame);
  3633. *pict = *(AVFrame*)h->next_output_pic;
  3634. }
  3635. }
  3636. assert(pict->data[0] || !*data_size);
  3637. ff_print_debug_info(s, pict);
  3638. //printf("out %d\n", (int)pict->data[0]);
  3639. return get_consumed_bytes(s, buf_index, buf_size);
  3640. }
  3641. #if 0
  3642. static inline void fill_mb_avail(H264Context *h){
  3643. MpegEncContext * const s = &h->s;
  3644. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3645. if(s->mb_y){
  3646. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  3647. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  3648. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  3649. }else{
  3650. h->mb_avail[0]=
  3651. h->mb_avail[1]=
  3652. h->mb_avail[2]= 0;
  3653. }
  3654. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  3655. h->mb_avail[4]= 1; //FIXME move out
  3656. h->mb_avail[5]= 0; //FIXME move out
  3657. }
  3658. #endif
  3659. av_cold void ff_h264_free_context(H264Context *h)
  3660. {
  3661. int i;
  3662. free_tables(h, 1); //FIXME cleanup init stuff perhaps
  3663. for(i = 0; i < MAX_SPS_COUNT; i++)
  3664. av_freep(h->sps_buffers + i);
  3665. for(i = 0; i < MAX_PPS_COUNT; i++)
  3666. av_freep(h->pps_buffers + i);
  3667. }
  3668. av_cold int ff_h264_decode_end(AVCodecContext *avctx)
  3669. {
  3670. H264Context *h = avctx->priv_data;
  3671. MpegEncContext *s = &h->s;
  3672. ff_h264_remove_all_refs(h);
  3673. ff_h264_free_context(h);
  3674. MPV_common_end(s);
  3675. // memset(h, 0, sizeof(H264Context));
  3676. return 0;
  3677. }
  3678. static const AVProfile profiles[] = {
  3679. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3680. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3681. { FF_PROFILE_H264_MAIN, "Main" },
  3682. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3683. { FF_PROFILE_H264_HIGH, "High" },
  3684. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3685. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3686. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3687. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3688. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3689. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3690. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3691. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3692. { FF_PROFILE_UNKNOWN },
  3693. };
  3694. static const AVOption h264_options[] = {
  3695. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
  3696. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 4, 0},
  3697. {NULL}
  3698. };
  3699. static const AVClass h264_class = {
  3700. "H264 Decoder",
  3701. av_default_item_name,
  3702. h264_options,
  3703. LIBAVUTIL_VERSION_INT,
  3704. };
  3705. static const AVClass h264_vdpau_class = {
  3706. "H264 VDPAU Decoder",
  3707. av_default_item_name,
  3708. h264_options,
  3709. LIBAVUTIL_VERSION_INT,
  3710. };
  3711. AVCodec ff_h264_decoder = {
  3712. .name = "h264",
  3713. .type = AVMEDIA_TYPE_VIDEO,
  3714. .id = CODEC_ID_H264,
  3715. .priv_data_size = sizeof(H264Context),
  3716. .init = ff_h264_decode_init,
  3717. .close = ff_h264_decode_end,
  3718. .decode = decode_frame,
  3719. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY |
  3720. CODEC_CAP_SLICE_THREADS | CODEC_CAP_FRAME_THREADS,
  3721. .flush= flush_dpb,
  3722. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  3723. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  3724. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  3725. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3726. .priv_class = &h264_class,
  3727. };
  3728. #if CONFIG_H264_VDPAU_DECODER
  3729. AVCodec ff_h264_vdpau_decoder = {
  3730. .name = "h264_vdpau",
  3731. .type = AVMEDIA_TYPE_VIDEO,
  3732. .id = CODEC_ID_H264,
  3733. .priv_data_size = sizeof(H264Context),
  3734. .init = ff_h264_decode_init,
  3735. .close = ff_h264_decode_end,
  3736. .decode = decode_frame,
  3737. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  3738. .flush= flush_dpb,
  3739. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  3740. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
  3741. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3742. .priv_class = &h264_vdpau_class,
  3743. };
  3744. #endif