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.

4333 lines
167KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * H.264 / AVC / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #define UNCHECKED_BITSTREAM_READER 1
  27. #include "libavutil/imgutils.h"
  28. #include "libavutil/opt.h"
  29. #include "internal.h"
  30. #include "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 0;
  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))
  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 || !s1->context_initialized) 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 (ff_h264_alloc_tables(h) < 0) {
  1085. av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
  1086. return AVERROR(ENOMEM);
  1087. }
  1088. context_init(h);
  1089. for(i=0; i<2; i++){
  1090. h->rbsp_buffer[i] = NULL;
  1091. h->rbsp_buffer_size[i] = 0;
  1092. }
  1093. h->thread_context[0] = h;
  1094. // frame_start may not be called for the next thread (if it's decoding a bottom field)
  1095. // so this has to be allocated here
  1096. h->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
  1097. s->dsp.clear_blocks(h->mb);
  1098. s->dsp.clear_blocks(h->mb+(24*16<<h->pixel_shift));
  1099. }
  1100. //extradata/NAL handling
  1101. h->is_avc = h1->is_avc;
  1102. //SPS/PPS
  1103. copy_parameter_set((void**)h->sps_buffers, (void**)h1->sps_buffers, MAX_SPS_COUNT, sizeof(SPS));
  1104. h->sps = h1->sps;
  1105. copy_parameter_set((void**)h->pps_buffers, (void**)h1->pps_buffers, MAX_PPS_COUNT, sizeof(PPS));
  1106. h->pps = h1->pps;
  1107. //Dequantization matrices
  1108. //FIXME these are big - can they be only copied when PPS changes?
  1109. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  1110. for(i=0; i<6; i++)
  1111. h->dequant4_coeff[i] = h->dequant4_buffer[0] + (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  1112. for(i=0; i<6; i++)
  1113. h->dequant8_coeff[i] = h->dequant8_buffer[0] + (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  1114. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  1115. //POC timing
  1116. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  1117. //reference lists
  1118. copy_fields(h, h1, ref_count, list_count);
  1119. copy_fields(h, h1, ref_list, intra_gb);
  1120. copy_fields(h, h1, short_ref, cabac_init_idc);
  1121. copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
  1122. copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
  1123. copy_picture_range(h->delayed_pic, h1->delayed_pic, MAX_DELAYED_PIC_COUNT+2, s, s1);
  1124. h->last_slice_type = h1->last_slice_type;
  1125. h->sync = h1->sync;
  1126. if(!s->current_picture_ptr) return 0;
  1127. if(!s->dropable) {
  1128. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1129. h->prev_poc_msb = h->poc_msb;
  1130. h->prev_poc_lsb = h->poc_lsb;
  1131. }
  1132. h->prev_frame_num_offset= h->frame_num_offset;
  1133. h->prev_frame_num = h->frame_num;
  1134. h->outputed_poc = h->next_outputed_poc;
  1135. return err;
  1136. }
  1137. int ff_h264_frame_start(H264Context *h){
  1138. MpegEncContext * const s = &h->s;
  1139. int i;
  1140. const int pixel_shift = h->pixel_shift;
  1141. if(MPV_frame_start(s, s->avctx) < 0)
  1142. return -1;
  1143. ff_er_frame_start(s);
  1144. /*
  1145. * MPV_frame_start uses pict_type to derive key_frame.
  1146. * This is incorrect for H.264; IDR markings must be used.
  1147. * Zero here; IDR markings per slice in frame or fields are ORed in later.
  1148. * See decode_nal_units().
  1149. */
  1150. s->current_picture_ptr->f.key_frame = 0;
  1151. s->current_picture_ptr->sync = 0;
  1152. s->current_picture_ptr->mmco_reset= 0;
  1153. assert(s->linesize && s->uvlinesize);
  1154. for(i=0; i<16; i++){
  1155. h->block_offset[i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->linesize*((scan8[i] - scan8[0])>>3);
  1156. h->block_offset[48+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->linesize*((scan8[i] - scan8[0])>>3);
  1157. }
  1158. for(i=0; i<16; i++){
  1159. h->block_offset[16+i]=
  1160. h->block_offset[32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 4*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1161. h->block_offset[48+16+i]=
  1162. h->block_offset[48+32+i]= (4*((scan8[i] - scan8[0])&7) << pixel_shift) + 8*s->uvlinesize*((scan8[i] - scan8[0])>>3);
  1163. }
  1164. /* can't be in alloc_tables because linesize isn't known there.
  1165. * FIXME: redo bipred weight to not require extra buffer? */
  1166. for(i = 0; i < s->slice_context_count; i++)
  1167. if(h->thread_context[i] && !h->thread_context[i]->s.obmc_scratchpad)
  1168. h->thread_context[i]->s.obmc_scratchpad = av_malloc(16*6*s->linesize);
  1169. /* some macroblocks can be accessed before they're available in case of lost slices, mbaff or threading*/
  1170. memset(h->slice_table, -1, (s->mb_height*s->mb_stride-1) * sizeof(*h->slice_table));
  1171. // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding || s->current_picture.f.reference /*|| h->contains_intra*/ || 1;
  1172. // We mark the current picture as non-reference after allocating it, so
  1173. // that if we break out due to an error it can be released automatically
  1174. // in the next MPV_frame_start().
  1175. // SVQ3 as well as most other codecs have only last/next/current and thus
  1176. // get released even with set reference, besides SVQ3 and others do not
  1177. // mark frames as reference later "naturally".
  1178. if(s->codec_id != CODEC_ID_SVQ3)
  1179. s->current_picture_ptr->f.reference = 0;
  1180. s->current_picture_ptr->field_poc[0]=
  1181. s->current_picture_ptr->field_poc[1]= INT_MAX;
  1182. h->next_output_pic = NULL;
  1183. assert(s->current_picture_ptr->long_ref==0);
  1184. return 0;
  1185. }
  1186. /**
  1187. * Run setup operations that must be run after slice header decoding.
  1188. * This includes finding the next displayed frame.
  1189. *
  1190. * @param h h264 master context
  1191. * @param setup_finished enough NALs have been read that we can call
  1192. * ff_thread_finish_setup()
  1193. */
  1194. static void decode_postinit(H264Context *h, int setup_finished){
  1195. MpegEncContext * const s = &h->s;
  1196. Picture *out = s->current_picture_ptr;
  1197. Picture *cur = s->current_picture_ptr;
  1198. int i, pics, out_of_order, out_idx;
  1199. s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
  1200. s->current_picture_ptr->f.pict_type = s->pict_type;
  1201. if (h->next_output_pic) return;
  1202. if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
  1203. //FIXME: if we have two PAFF fields in one packet, we can't start the next thread here.
  1204. //If we have one field per packet, we can. The check in decode_nal_units() is not good enough
  1205. //to find this yet, so we assume the worst for now.
  1206. //if (setup_finished)
  1207. // ff_thread_finish_setup(s->avctx);
  1208. return;
  1209. }
  1210. cur->f.interlaced_frame = 0;
  1211. cur->f.repeat_pict = 0;
  1212. /* Signal interlacing information externally. */
  1213. /* Prioritize picture timing SEI information over used decoding process if it exists. */
  1214. if(h->sps.pic_struct_present_flag){
  1215. switch (h->sei_pic_struct)
  1216. {
  1217. case SEI_PIC_STRUCT_FRAME:
  1218. break;
  1219. case SEI_PIC_STRUCT_TOP_FIELD:
  1220. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1221. cur->f.interlaced_frame = 1;
  1222. break;
  1223. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1224. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1225. if (FIELD_OR_MBAFF_PICTURE)
  1226. cur->f.interlaced_frame = 1;
  1227. else
  1228. // try to flag soft telecine progressive
  1229. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1230. break;
  1231. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1232. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1233. // Signal the possibility of telecined film externally (pic_struct 5,6)
  1234. // From these hints, let the applications decide if they apply deinterlacing.
  1235. cur->f.repeat_pict = 1;
  1236. break;
  1237. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1238. // Force progressive here, as doubling interlaced frame is a bad idea.
  1239. cur->f.repeat_pict = 2;
  1240. break;
  1241. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1242. cur->f.repeat_pict = 4;
  1243. break;
  1244. }
  1245. if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1246. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1247. }else{
  1248. /* Derive interlacing flag from used decoding process. */
  1249. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1250. }
  1251. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1252. if (cur->field_poc[0] != cur->field_poc[1]){
  1253. /* Derive top_field_first from field pocs. */
  1254. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1255. }else{
  1256. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1257. /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
  1258. if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
  1259. || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1260. cur->f.top_field_first = 1;
  1261. else
  1262. cur->f.top_field_first = 0;
  1263. }else{
  1264. /* Most likely progressive */
  1265. cur->f.top_field_first = 0;
  1266. }
  1267. }
  1268. cur->mmco_reset = h->mmco_reset;
  1269. h->mmco_reset = 0;
  1270. //FIXME do something with unavailable reference frames
  1271. /* Sort B-frames into display order */
  1272. if(h->sps.bitstream_restriction_flag
  1273. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  1274. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  1275. s->low_delay = 0;
  1276. }
  1277. if( s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
  1278. && !h->sps.bitstream_restriction_flag){
  1279. s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1280. s->low_delay= 0;
  1281. }
  1282. for (i = 0; 1; i++) {
  1283. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1284. if(i)
  1285. h->last_pocs[i-1] = cur->poc;
  1286. break;
  1287. } else if(i) {
  1288. h->last_pocs[i-1]= h->last_pocs[i];
  1289. }
  1290. }
  1291. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1292. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1293. || (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))
  1294. out_of_order = FFMAX(out_of_order, 1);
  1295. if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1296. av_log(s->avctx, AV_LOG_WARNING, "Increasing reorder buffer to %d\n", out_of_order);
  1297. s->avctx->has_b_frames = out_of_order;
  1298. s->low_delay = 0;
  1299. }
  1300. pics = 0;
  1301. while(h->delayed_pic[pics]) pics++;
  1302. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1303. h->delayed_pic[pics++] = cur;
  1304. if (cur->f.reference == 0)
  1305. cur->f.reference = DELAYED_PIC_REF;
  1306. out = h->delayed_pic[0];
  1307. out_idx = 0;
  1308. for (i = 1; h->delayed_pic[i] && !h->delayed_pic[i]->f.key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  1309. if(h->delayed_pic[i]->poc < out->poc){
  1310. out = h->delayed_pic[i];
  1311. out_idx = i;
  1312. }
  1313. if (s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1314. h->next_outputed_poc= INT_MIN;
  1315. out_of_order = out->poc < h->next_outputed_poc;
  1316. if(out_of_order || pics > s->avctx->has_b_frames){
  1317. out->f.reference &= ~DELAYED_PIC_REF;
  1318. out->owner2 = s; // for frame threading, the owner must be the second field's thread
  1319. // or else the first thread can release the picture and reuse it unsafely
  1320. for(i=out_idx; h->delayed_pic[i]; i++)
  1321. h->delayed_pic[i] = h->delayed_pic[i+1];
  1322. }
  1323. if(!out_of_order && pics > s->avctx->has_b_frames){
  1324. h->next_output_pic = out;
  1325. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1326. h->next_outputed_poc = INT_MIN;
  1327. } else
  1328. h->next_outputed_poc = out->poc;
  1329. }else{
  1330. av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1331. }
  1332. if (h->next_output_pic && h->next_output_pic->sync) {
  1333. h->sync |= 2;
  1334. }
  1335. if (setup_finished)
  1336. ff_thread_finish_setup(s->avctx);
  1337. }
  1338. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1339. uint8_t *src_cb, uint8_t *src_cr,
  1340. int linesize, int uvlinesize, int simple)
  1341. {
  1342. MpegEncContext * const s = &h->s;
  1343. uint8_t *top_border;
  1344. int top_idx = 1;
  1345. const int pixel_shift = h->pixel_shift;
  1346. int chroma444 = CHROMA444;
  1347. int chroma422 = CHROMA422;
  1348. src_y -= linesize;
  1349. src_cb -= uvlinesize;
  1350. src_cr -= uvlinesize;
  1351. if(!simple && FRAME_MBAFF){
  1352. if(s->mb_y&1){
  1353. if(!MB_MBAFF){
  1354. top_border = h->top_borders[0][s->mb_x];
  1355. AV_COPY128(top_border, src_y + 15*linesize);
  1356. if (pixel_shift)
  1357. AV_COPY128(top_border+16, src_y+15*linesize+16);
  1358. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1359. if(chroma444){
  1360. if (pixel_shift){
  1361. AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
  1362. AV_COPY128(top_border+48, src_cb + 15*uvlinesize+16);
  1363. AV_COPY128(top_border+64, src_cr + 15*uvlinesize);
  1364. AV_COPY128(top_border+80, src_cr + 15*uvlinesize+16);
  1365. } else {
  1366. AV_COPY128(top_border+16, src_cb + 15*uvlinesize);
  1367. AV_COPY128(top_border+32, src_cr + 15*uvlinesize);
  1368. }
  1369. } else if(chroma422){
  1370. if (pixel_shift) {
  1371. AV_COPY128(top_border+32, src_cb + 15*uvlinesize);
  1372. AV_COPY128(top_border+48, src_cr + 15*uvlinesize);
  1373. } else {
  1374. AV_COPY64(top_border+16, src_cb + 15*uvlinesize);
  1375. AV_COPY64(top_border+24, src_cr + 15*uvlinesize);
  1376. }
  1377. } else {
  1378. if (pixel_shift) {
  1379. AV_COPY128(top_border+32, src_cb+7*uvlinesize);
  1380. AV_COPY128(top_border+48, src_cr+7*uvlinesize);
  1381. } else {
  1382. AV_COPY64(top_border+16, src_cb+7*uvlinesize);
  1383. AV_COPY64(top_border+24, src_cr+7*uvlinesize);
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }else if(MB_MBAFF){
  1389. top_idx = 0;
  1390. }else
  1391. return;
  1392. }
  1393. top_border = h->top_borders[top_idx][s->mb_x];
  1394. // There are two lines saved, the line above the the top macroblock of a pair,
  1395. // and the line above the bottom macroblock
  1396. AV_COPY128(top_border, src_y + 16*linesize);
  1397. if (pixel_shift)
  1398. AV_COPY128(top_border+16, src_y+16*linesize+16);
  1399. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1400. if(chroma444){
  1401. if (pixel_shift){
  1402. AV_COPY128(top_border+32, src_cb + 16*linesize);
  1403. AV_COPY128(top_border+48, src_cb + 16*linesize+16);
  1404. AV_COPY128(top_border+64, src_cr + 16*linesize);
  1405. AV_COPY128(top_border+80, src_cr + 16*linesize+16);
  1406. } else {
  1407. AV_COPY128(top_border+16, src_cb + 16*linesize);
  1408. AV_COPY128(top_border+32, src_cr + 16*linesize);
  1409. }
  1410. } else if(chroma422) {
  1411. if (pixel_shift) {
  1412. AV_COPY128(top_border+32, src_cb+16*uvlinesize);
  1413. AV_COPY128(top_border+48, src_cr+16*uvlinesize);
  1414. } else {
  1415. AV_COPY64(top_border+16, src_cb+16*uvlinesize);
  1416. AV_COPY64(top_border+24, src_cr+16*uvlinesize);
  1417. }
  1418. } else {
  1419. if (pixel_shift) {
  1420. AV_COPY128(top_border+32, src_cb+8*uvlinesize);
  1421. AV_COPY128(top_border+48, src_cr+8*uvlinesize);
  1422. } else {
  1423. AV_COPY64(top_border+16, src_cb+8*uvlinesize);
  1424. AV_COPY64(top_border+24, src_cr+8*uvlinesize);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1430. uint8_t *src_cb, uint8_t *src_cr,
  1431. int linesize, int uvlinesize,
  1432. int xchg, int chroma444,
  1433. int simple, int pixel_shift){
  1434. MpegEncContext * const s = &h->s;
  1435. int deblock_topleft;
  1436. int deblock_top;
  1437. int top_idx = 1;
  1438. uint8_t *top_border_m1;
  1439. uint8_t *top_border;
  1440. if(!simple && FRAME_MBAFF){
  1441. if(s->mb_y&1){
  1442. if(!MB_MBAFF)
  1443. return;
  1444. }else{
  1445. top_idx = MB_MBAFF ? 0 : 1;
  1446. }
  1447. }
  1448. if(h->deblocking_filter == 2) {
  1449. deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
  1450. deblock_top = h->top_type;
  1451. } else {
  1452. deblock_topleft = (s->mb_x > 0);
  1453. deblock_top = (s->mb_y > !!MB_FIELD);
  1454. }
  1455. src_y -= linesize + 1 + pixel_shift;
  1456. src_cb -= uvlinesize + 1 + pixel_shift;
  1457. src_cr -= uvlinesize + 1 + pixel_shift;
  1458. top_border_m1 = h->top_borders[top_idx][s->mb_x-1];
  1459. top_border = h->top_borders[top_idx][s->mb_x];
  1460. #define XCHG(a,b,xchg)\
  1461. if (pixel_shift) {\
  1462. if (xchg) {\
  1463. AV_SWAP64(b+0,a+0);\
  1464. AV_SWAP64(b+8,a+8);\
  1465. } else {\
  1466. AV_COPY128(b,a); \
  1467. }\
  1468. } else \
  1469. if (xchg) AV_SWAP64(b,a);\
  1470. else AV_COPY64(b,a);
  1471. if(deblock_top){
  1472. if(deblock_topleft){
  1473. XCHG(top_border_m1 + (8 << pixel_shift), src_y - (7 << pixel_shift), 1);
  1474. }
  1475. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1476. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1477. if(s->mb_x+1 < s->mb_width){
  1478. XCHG(h->top_borders[top_idx][s->mb_x+1], src_y + (17 << pixel_shift), 1);
  1479. }
  1480. }
  1481. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1482. if(chroma444){
  1483. if(deblock_topleft){
  1484. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1485. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1486. }
  1487. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  1488. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  1489. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  1490. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  1491. if(s->mb_x+1 < s->mb_width){
  1492. XCHG(h->top_borders[top_idx][s->mb_x+1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  1493. XCHG(h->top_borders[top_idx][s->mb_x+1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  1494. }
  1495. } else {
  1496. if(deblock_top){
  1497. if(deblock_topleft){
  1498. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1499. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1500. }
  1501. XCHG(top_border + (16 << pixel_shift), src_cb+1+pixel_shift, 1);
  1502. XCHG(top_border + (24 << pixel_shift), src_cr+1+pixel_shift, 1);
  1503. }
  1504. }
  1505. }
  1506. }
  1507. static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth, int index) {
  1508. if (high_bit_depth) {
  1509. return AV_RN32A(((int32_t*)mb) + index);
  1510. } else
  1511. return AV_RN16A(mb + index);
  1512. }
  1513. static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth, int index, int value) {
  1514. if (high_bit_depth) {
  1515. AV_WN32A(((int32_t*)mb) + index, value);
  1516. } else
  1517. AV_WN16A(mb + index, value);
  1518. }
  1519. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
  1520. int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
  1521. {
  1522. MpegEncContext * const s = &h->s;
  1523. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1524. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  1525. int i;
  1526. int qscale = p == 0 ? s->qscale : h->chroma_qp[p-1];
  1527. block_offset += 16*p;
  1528. if(IS_INTRA4x4(mb_type)){
  1529. if(simple || !s->encoding){
  1530. if(IS_8x8DCT(mb_type)){
  1531. if(transform_bypass){
  1532. idct_dc_add =
  1533. idct_add = s->dsp.add_pixels8;
  1534. }else{
  1535. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1536. idct_add = h->h264dsp.h264_idct8_add;
  1537. }
  1538. for(i=0; i<16; i+=4){
  1539. uint8_t * const ptr= dest_y + block_offset[i];
  1540. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  1541. if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
  1542. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1543. }else{
  1544. const int nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
  1545. h->hpc.pred8x8l[ dir ](ptr, (h->topleft_samples_available<<i)&0x8000,
  1546. (h->topright_samples_available<<i)&0x4000, linesize);
  1547. if(nnz){
  1548. if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
  1549. idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1550. else
  1551. idct_add (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1552. }
  1553. }
  1554. }
  1555. }else{
  1556. if(transform_bypass){
  1557. idct_dc_add =
  1558. idct_add = s->dsp.add_pixels4;
  1559. }else{
  1560. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1561. idct_add = h->h264dsp.h264_idct_add;
  1562. }
  1563. for(i=0; i<16; i++){
  1564. uint8_t * const ptr= dest_y + block_offset[i];
  1565. const int dir= h->intra4x4_pred_mode_cache[ scan8[i] ];
  1566. if(transform_bypass && h->sps.profile_idc==244 && dir<=1){
  1567. h->hpc.pred4x4_add[dir](ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1568. }else{
  1569. uint8_t *topright;
  1570. int nnz, tr;
  1571. uint64_t tr_high;
  1572. if(dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED){
  1573. const int topright_avail= (h->topright_samples_available<<i)&0x8000;
  1574. assert(s->mb_y || linesize <= block_offset[i]);
  1575. if(!topright_avail){
  1576. if (pixel_shift) {
  1577. tr_high= ((uint16_t*)ptr)[3 - linesize/2]*0x0001000100010001ULL;
  1578. topright= (uint8_t*) &tr_high;
  1579. } else {
  1580. tr= ptr[3 - linesize]*0x01010101u;
  1581. topright= (uint8_t*) &tr;
  1582. }
  1583. }else
  1584. topright= ptr + (4 << pixel_shift) - linesize;
  1585. }else
  1586. topright= NULL;
  1587. h->hpc.pred4x4[ dir ](ptr, topright, linesize);
  1588. nnz = h->non_zero_count_cache[ scan8[i+p*16] ];
  1589. if(nnz){
  1590. if(is_h264){
  1591. if(nnz == 1 && dctcoef_get(h->mb, pixel_shift, i*16+p*256))
  1592. idct_dc_add(ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1593. else
  1594. idct_add (ptr, h->mb + (i*16+p*256 << pixel_shift), linesize);
  1595. } else if (CONFIG_SVQ3_DECODER)
  1596. ff_svq3_add_idct_c(ptr, h->mb + i*16+p*256, linesize, qscale, 0);
  1597. }
  1598. }
  1599. }
  1600. }
  1601. }
  1602. }else{
  1603. h->hpc.pred16x16[ h->intra16x16_pred_mode ](dest_y , linesize);
  1604. if(is_h264){
  1605. if(h->non_zero_count_cache[ scan8[LUMA_DC_BLOCK_INDEX+p] ]){
  1606. if(!transform_bypass)
  1607. h->h264dsp.h264_luma_dc_dequant_idct(h->mb+(p*256 << pixel_shift), h->mb_luma_dc[p], h->dequant4_coeff[p][qscale][0]);
  1608. else{
  1609. static const uint8_t dc_mapping[16] = { 0*16, 1*16, 4*16, 5*16, 2*16, 3*16, 6*16, 7*16,
  1610. 8*16, 9*16,12*16,13*16,10*16,11*16,14*16,15*16};
  1611. for(i = 0; i < 16; i++)
  1612. dctcoef_set(h->mb+(p*256 << pixel_shift), pixel_shift, dc_mapping[i], dctcoef_get(h->mb_luma_dc[p], pixel_shift, i));
  1613. }
  1614. }
  1615. } else if (CONFIG_SVQ3_DECODER)
  1616. ff_svq3_luma_dc_dequant_idct_c(h->mb+p*256, h->mb_luma_dc[p], qscale);
  1617. }
  1618. }
  1619. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type, int is_h264, int simple, int transform_bypass,
  1620. int pixel_shift, int *block_offset, int linesize, uint8_t *dest_y, int p)
  1621. {
  1622. MpegEncContext * const s = &h->s;
  1623. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1624. int i;
  1625. block_offset += 16*p;
  1626. if(!IS_INTRA4x4(mb_type)){
  1627. if(is_h264){
  1628. if(IS_INTRA16x16(mb_type)){
  1629. if(transform_bypass){
  1630. if(h->sps.profile_idc==244 && (h->intra16x16_pred_mode==VERT_PRED8x8 || h->intra16x16_pred_mode==HOR_PRED8x8)){
  1631. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize);
  1632. }else{
  1633. for(i=0; i<16; i++){
  1634. if(h->non_zero_count_cache[ scan8[i+p*16] ] || dctcoef_get(h->mb, pixel_shift, i*16+p*256))
  1635. s->dsp.add_pixels4(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
  1636. }
  1637. }
  1638. }else{
  1639. h->h264dsp.h264_idct_add16intra(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
  1640. }
  1641. }else if(h->cbp&15){
  1642. if(transform_bypass){
  1643. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  1644. idct_add= IS_8x8DCT(mb_type) ? s->dsp.add_pixels8 : s->dsp.add_pixels4;
  1645. for(i=0; i<16; i+=di){
  1646. if(h->non_zero_count_cache[ scan8[i+p*16] ]){
  1647. idct_add(dest_y + block_offset[i], h->mb + (i*16+p*256 << pixel_shift), linesize);
  1648. }
  1649. }
  1650. }else{
  1651. if(IS_8x8DCT(mb_type)){
  1652. h->h264dsp.h264_idct8_add4(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
  1653. }else{
  1654. h->h264dsp.h264_idct_add16(dest_y, block_offset, h->mb + (p*256 << pixel_shift), linesize, h->non_zero_count_cache+p*5*8);
  1655. }
  1656. }
  1657. }
  1658. } else if (CONFIG_SVQ3_DECODER) {
  1659. for(i=0; i<16; i++){
  1660. if(h->non_zero_count_cache[ scan8[i+p*16] ] || h->mb[i*16+p*256]){ //FIXME benchmark weird rule, & below
  1661. uint8_t * const ptr= dest_y + block_offset[i];
  1662. ff_svq3_add_idct_c(ptr, h->mb + i*16 + p*256, linesize, s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  1663. }
  1664. }
  1665. }
  1666. }
  1667. }
  1668. static av_always_inline void hl_decode_mb_internal(H264Context *h, int simple, int pixel_shift)
  1669. {
  1670. MpegEncContext * const s = &h->s;
  1671. const int mb_x= s->mb_x;
  1672. const int mb_y= s->mb_y;
  1673. const int mb_xy= h->mb_xy;
  1674. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  1675. uint8_t *dest_y, *dest_cb, *dest_cr;
  1676. int linesize, uvlinesize /*dct_offset*/;
  1677. int i, j;
  1678. int *block_offset = &h->block_offset[0];
  1679. const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
  1680. /* is_h264 should always be true if SVQ3 is disabled. */
  1681. const int is_h264 = !CONFIG_SVQ3_DECODER || simple || s->codec_id == CODEC_ID_H264;
  1682. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1683. const int block_h = 16 >> s->chroma_y_shift;
  1684. const int chroma422 = CHROMA422;
  1685. dest_y = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize ) * 16;
  1686. dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift)*8 + mb_y * s->uvlinesize * block_h;
  1687. dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift)*8 + mb_y * s->uvlinesize * block_h;
  1688. s->dsp.prefetch(dest_y + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
  1689. s->dsp.prefetch(dest_cb + (s->mb_x&7)*s->uvlinesize + (64 << pixel_shift), dest_cr - dest_cb, 2);
  1690. h->list_counts[mb_xy]= h->list_count;
  1691. if (!simple && MB_FIELD) {
  1692. linesize = h->mb_linesize = s->linesize * 2;
  1693. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  1694. block_offset = &h->block_offset[48];
  1695. if(mb_y&1){ //FIXME move out of this function?
  1696. dest_y -= s->linesize*15;
  1697. dest_cb-= s->uvlinesize * (block_h - 1);
  1698. dest_cr-= s->uvlinesize * (block_h - 1);
  1699. }
  1700. if(FRAME_MBAFF) {
  1701. int list;
  1702. for(list=0; list<h->list_count; list++){
  1703. if(!USES_LIST(mb_type, list))
  1704. continue;
  1705. if(IS_16X16(mb_type)){
  1706. int8_t *ref = &h->ref_cache[list][scan8[0]];
  1707. fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
  1708. }else{
  1709. for(i=0; i<16; i+=4){
  1710. int ref = h->ref_cache[list][scan8[i]];
  1711. if(ref >= 0)
  1712. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
  1713. }
  1714. }
  1715. }
  1716. }
  1717. } else {
  1718. linesize = h->mb_linesize = s->linesize;
  1719. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  1720. // dct_offset = s->linesize * 16;
  1721. }
  1722. if (!simple && IS_INTRA_PCM(mb_type)) {
  1723. const int bit_depth = h->sps.bit_depth_luma;
  1724. if (pixel_shift) {
  1725. int j;
  1726. GetBitContext gb;
  1727. init_get_bits(&gb, (uint8_t*)h->mb, 384*bit_depth);
  1728. for (i = 0; i < 16; i++) {
  1729. uint16_t *tmp_y = (uint16_t*)(dest_y + i*linesize);
  1730. for (j = 0; j < 16; j++)
  1731. tmp_y[j] = get_bits(&gb, bit_depth);
  1732. }
  1733. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1734. if (!h->sps.chroma_format_idc) {
  1735. for (i = 0; i < block_h; i++) {
  1736. uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
  1737. uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
  1738. for (j = 0; j < 8; j++) {
  1739. tmp_cb[j] = tmp_cr[j] = 1 << (bit_depth - 1);
  1740. }
  1741. }
  1742. } else {
  1743. for (i = 0; i < block_h; i++) {
  1744. uint16_t *tmp_cb = (uint16_t*)(dest_cb + i*uvlinesize);
  1745. for (j = 0; j < 8; j++)
  1746. tmp_cb[j] = get_bits(&gb, bit_depth);
  1747. }
  1748. for (i = 0; i < block_h; i++) {
  1749. uint16_t *tmp_cr = (uint16_t*)(dest_cr + i*uvlinesize);
  1750. for (j = 0; j < 8; j++)
  1751. tmp_cr[j] = get_bits(&gb, bit_depth);
  1752. }
  1753. }
  1754. }
  1755. } else {
  1756. for (i=0; i<16; i++) {
  1757. memcpy(dest_y + i* linesize, h->mb + i*8, 16);
  1758. }
  1759. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1760. if (!h->sps.chroma_format_idc) {
  1761. for (i=0; i<8; i++) {
  1762. memset(dest_cb + i*uvlinesize, 1 << (bit_depth - 1), 8);
  1763. memset(dest_cr + i*uvlinesize, 1 << (bit_depth - 1), 8);
  1764. }
  1765. } else {
  1766. for (i=0; i<block_h; i++) {
  1767. memcpy(dest_cb + i*uvlinesize, h->mb + 128 + i*4, 8);
  1768. memcpy(dest_cr + i*uvlinesize, h->mb + 160 + i*4, 8);
  1769. }
  1770. }
  1771. }
  1772. }
  1773. } else {
  1774. if(IS_INTRA(mb_type)){
  1775. if(h->deblocking_filter)
  1776. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 1, 0, simple, pixel_shift);
  1777. if(simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){
  1778. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cb, uvlinesize);
  1779. h->hpc.pred8x8[ h->chroma_pred_mode ](dest_cr, uvlinesize);
  1780. }
  1781. hl_decode_mb_predict_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
  1782. if(h->deblocking_filter)
  1783. xchg_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0, 0, simple, pixel_shift);
  1784. }else if(is_h264){
  1785. if (chroma422) {
  1786. hl_motion_422(h, dest_y, dest_cb, dest_cr,
  1787. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  1788. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  1789. h->h264dsp.weight_h264_pixels_tab,
  1790. h->h264dsp.biweight_h264_pixels_tab,
  1791. pixel_shift);
  1792. } else {
  1793. hl_motion_420(h, dest_y, dest_cb, dest_cr,
  1794. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  1795. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  1796. h->h264dsp.weight_h264_pixels_tab,
  1797. h->h264dsp.biweight_h264_pixels_tab,
  1798. pixel_shift);
  1799. }
  1800. }
  1801. hl_decode_mb_idct_luma(h, mb_type, is_h264, simple, transform_bypass, pixel_shift, block_offset, linesize, dest_y, 0);
  1802. if((simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) && (h->cbp&0x30)){
  1803. uint8_t *dest[2] = {dest_cb, dest_cr};
  1804. if(transform_bypass){
  1805. if(IS_INTRA(mb_type) && h->sps.profile_idc==244 && (h->chroma_pred_mode==VERT_PRED8x8 || h->chroma_pred_mode==HOR_PRED8x8)){
  1806. h->hpc.pred8x8_add[h->chroma_pred_mode](dest[0], block_offset + 16, h->mb + (16*16*1 << pixel_shift), uvlinesize);
  1807. h->hpc.pred8x8_add[h->chroma_pred_mode](dest[1], block_offset + 32, h->mb + (16*16*2 << pixel_shift), uvlinesize);
  1808. }else{
  1809. idct_add = s->dsp.add_pixels4;
  1810. for(j=1; j<3; j++){
  1811. for(i=j*16; i<j*16+4; i++){
  1812. if(h->non_zero_count_cache[ scan8[i] ] || dctcoef_get(h->mb, pixel_shift, i*16))
  1813. idct_add (dest[j-1] + block_offset[i], h->mb + (i*16 << pixel_shift), uvlinesize);
  1814. }
  1815. if (chroma422) {
  1816. for(i=j*16+4; i<j*16+8; i++){
  1817. if(h->non_zero_count_cache[ scan8[i+4] ] || dctcoef_get(h->mb, pixel_shift, i*16))
  1818. idct_add (dest[j-1] + block_offset[i+4], h->mb + (i*16 << pixel_shift), uvlinesize);
  1819. }
  1820. }
  1821. }
  1822. }
  1823. }else{
  1824. if(is_h264){
  1825. int qp[2];
  1826. if (chroma422) {
  1827. qp[0] = h->chroma_qp[0] + 3;
  1828. qp[1] = h->chroma_qp[1] + 3;
  1829. } else {
  1830. qp[0] = h->chroma_qp[0];
  1831. qp[1] = h->chroma_qp[1];
  1832. }
  1833. if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+0] ])
  1834. 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]);
  1835. if(h->non_zero_count_cache[ scan8[CHROMA_DC_BLOCK_INDEX+1] ])
  1836. 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]);
  1837. h->h264dsp.h264_idct_add8(dest, block_offset,
  1838. h->mb, uvlinesize,
  1839. h->non_zero_count_cache);
  1840. } else if (CONFIG_SVQ3_DECODER) {
  1841. h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*1, h->dequant4_coeff[IS_INTRA(mb_type) ? 1:4][h->chroma_qp[0]][0]);
  1842. h->h264dsp.h264_chroma_dc_dequant_idct(h->mb + 16*16*2, h->dequant4_coeff[IS_INTRA(mb_type) ? 2:5][h->chroma_qp[1]][0]);
  1843. for(j=1; j<3; j++){
  1844. for(i=j*16; i<j*16+4; i++){
  1845. if(h->non_zero_count_cache[ scan8[i] ] || h->mb[i*16]){
  1846. uint8_t * const ptr= dest[j-1] + block_offset[i];
  1847. ff_svq3_add_idct_c(ptr, h->mb + i*16, uvlinesize, ff_h264_chroma_qp[0][s->qscale + 12] - 12, 2);
  1848. }
  1849. }
  1850. }
  1851. }
  1852. }
  1853. }
  1854. }
  1855. if(h->cbp || IS_INTRA(mb_type))
  1856. {
  1857. s->dsp.clear_blocks(h->mb);
  1858. s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
  1859. }
  1860. }
  1861. static av_always_inline void hl_decode_mb_444_internal(H264Context *h, int simple, int pixel_shift){
  1862. MpegEncContext * const s = &h->s;
  1863. const int mb_x= s->mb_x;
  1864. const int mb_y= s->mb_y;
  1865. const int mb_xy= h->mb_xy;
  1866. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  1867. uint8_t *dest[3];
  1868. int linesize;
  1869. int i, j, p;
  1870. int *block_offset = &h->block_offset[0];
  1871. const int transform_bypass = !simple && (s->qscale == 0 && h->sps.transform_bypass);
  1872. const int plane_count = (simple || !CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)) ? 3 : 1;
  1873. for (p = 0; p < plane_count; p++)
  1874. {
  1875. dest[p] = s->current_picture.f.data[p] + ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
  1876. s->dsp.prefetch(dest[p] + (s->mb_x&3)*4*s->linesize + (64 << pixel_shift), s->linesize, 4);
  1877. }
  1878. h->list_counts[mb_xy]= h->list_count;
  1879. if (!simple && MB_FIELD) {
  1880. linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize * 2;
  1881. block_offset = &h->block_offset[48];
  1882. if(mb_y&1) //FIXME move out of this function?
  1883. for (p = 0; p < 3; p++)
  1884. dest[p] -= s->linesize*15;
  1885. if(FRAME_MBAFF) {
  1886. int list;
  1887. for(list=0; list<h->list_count; list++){
  1888. if(!USES_LIST(mb_type, list))
  1889. continue;
  1890. if(IS_16X16(mb_type)){
  1891. int8_t *ref = &h->ref_cache[list][scan8[0]];
  1892. fill_rectangle(ref, 4, 4, 8, (16+*ref)^(s->mb_y&1), 1);
  1893. }else{
  1894. for(i=0; i<16; i+=4){
  1895. int ref = h->ref_cache[list][scan8[i]];
  1896. if(ref >= 0)
  1897. fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2, 8, (16+ref)^(s->mb_y&1), 1);
  1898. }
  1899. }
  1900. }
  1901. }
  1902. } else {
  1903. linesize = h->mb_linesize = h->mb_uvlinesize = s->linesize;
  1904. }
  1905. if (!simple && IS_INTRA_PCM(mb_type)) {
  1906. if (pixel_shift) {
  1907. const int bit_depth = h->sps.bit_depth_luma;
  1908. GetBitContext gb;
  1909. init_get_bits(&gb, (uint8_t*)h->mb, 768*bit_depth);
  1910. for (p = 0; p < plane_count; p++) {
  1911. for (i = 0; i < 16; i++) {
  1912. uint16_t *tmp = (uint16_t*)(dest[p] + i*linesize);
  1913. for (j = 0; j < 16; j++)
  1914. tmp[j] = get_bits(&gb, bit_depth);
  1915. }
  1916. }
  1917. } else {
  1918. for (p = 0; p < plane_count; p++) {
  1919. for (i = 0; i < 16; i++) {
  1920. memcpy(dest[p] + i*linesize, h->mb + p*128 + i*8, 16);
  1921. }
  1922. }
  1923. }
  1924. } else {
  1925. if(IS_INTRA(mb_type)){
  1926. if(h->deblocking_filter)
  1927. xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 1, 1, simple, pixel_shift);
  1928. for (p = 0; p < plane_count; p++)
  1929. hl_decode_mb_predict_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
  1930. if(h->deblocking_filter)
  1931. xchg_mb_border(h, dest[0], dest[1], dest[2], linesize, linesize, 0, 1, simple, pixel_shift);
  1932. }else{
  1933. hl_motion(h, dest[0], dest[1], dest[2],
  1934. s->me.qpel_put, s->dsp.put_h264_chroma_pixels_tab,
  1935. s->me.qpel_avg, s->dsp.avg_h264_chroma_pixels_tab,
  1936. h->h264dsp.weight_h264_pixels_tab,
  1937. h->h264dsp.biweight_h264_pixels_tab, pixel_shift, 3);
  1938. }
  1939. for (p = 0; p < plane_count; p++)
  1940. hl_decode_mb_idct_luma(h, mb_type, 1, simple, transform_bypass, pixel_shift, block_offset, linesize, dest[p], p);
  1941. }
  1942. if(h->cbp || IS_INTRA(mb_type))
  1943. {
  1944. s->dsp.clear_blocks(h->mb);
  1945. s->dsp.clear_blocks(h->mb+(24*16<<pixel_shift));
  1946. }
  1947. }
  1948. /**
  1949. * Process a macroblock; this case avoids checks for expensive uncommon cases.
  1950. */
  1951. #define hl_decode_mb_simple(sh, bits) \
  1952. static void hl_decode_mb_simple_ ## bits(H264Context *h){ \
  1953. hl_decode_mb_internal(h, 1, sh); \
  1954. }
  1955. hl_decode_mb_simple(0, 8)
  1956. hl_decode_mb_simple(1, 16)
  1957. /**
  1958. * Process a macroblock; this handles edge cases, such as interlacing.
  1959. */
  1960. static void av_noinline hl_decode_mb_complex(H264Context *h){
  1961. hl_decode_mb_internal(h, 0, h->pixel_shift);
  1962. }
  1963. static void av_noinline hl_decode_mb_444_complex(H264Context *h){
  1964. hl_decode_mb_444_internal(h, 0, h->pixel_shift);
  1965. }
  1966. static void av_noinline hl_decode_mb_444_simple(H264Context *h){
  1967. hl_decode_mb_444_internal(h, 1, 0);
  1968. }
  1969. void ff_h264_hl_decode_mb(H264Context *h){
  1970. MpegEncContext * const s = &h->s;
  1971. const int mb_xy= h->mb_xy;
  1972. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  1973. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
  1974. if (CHROMA444) {
  1975. if(is_complex || h->pixel_shift)
  1976. hl_decode_mb_444_complex(h);
  1977. else
  1978. hl_decode_mb_444_simple(h);
  1979. } else if (is_complex) {
  1980. hl_decode_mb_complex(h);
  1981. } else if (h->pixel_shift) {
  1982. hl_decode_mb_simple_16(h);
  1983. } else
  1984. hl_decode_mb_simple_8(h);
  1985. }
  1986. static int pred_weight_table(H264Context *h){
  1987. MpegEncContext * const s = &h->s;
  1988. int list, i;
  1989. int luma_def, chroma_def;
  1990. h->use_weight= 0;
  1991. h->use_weight_chroma= 0;
  1992. h->luma_log2_weight_denom= get_ue_golomb(&s->gb);
  1993. if(h->sps.chroma_format_idc)
  1994. h->chroma_log2_weight_denom= get_ue_golomb(&s->gb);
  1995. luma_def = 1<<h->luma_log2_weight_denom;
  1996. chroma_def = 1<<h->chroma_log2_weight_denom;
  1997. for(list=0; list<2; list++){
  1998. h->luma_weight_flag[list] = 0;
  1999. h->chroma_weight_flag[list] = 0;
  2000. for(i=0; i<h->ref_count[list]; i++){
  2001. int luma_weight_flag, chroma_weight_flag;
  2002. luma_weight_flag= get_bits1(&s->gb);
  2003. if(luma_weight_flag){
  2004. h->luma_weight[i][list][0]= get_se_golomb(&s->gb);
  2005. h->luma_weight[i][list][1]= get_se_golomb(&s->gb);
  2006. if( h->luma_weight[i][list][0] != luma_def
  2007. || h->luma_weight[i][list][1] != 0) {
  2008. h->use_weight= 1;
  2009. h->luma_weight_flag[list]= 1;
  2010. }
  2011. }else{
  2012. h->luma_weight[i][list][0]= luma_def;
  2013. h->luma_weight[i][list][1]= 0;
  2014. }
  2015. if(h->sps.chroma_format_idc){
  2016. chroma_weight_flag= get_bits1(&s->gb);
  2017. if(chroma_weight_flag){
  2018. int j;
  2019. for(j=0; j<2; j++){
  2020. h->chroma_weight[i][list][j][0]= get_se_golomb(&s->gb);
  2021. h->chroma_weight[i][list][j][1]= get_se_golomb(&s->gb);
  2022. if( h->chroma_weight[i][list][j][0] != chroma_def
  2023. || h->chroma_weight[i][list][j][1] != 0) {
  2024. h->use_weight_chroma= 1;
  2025. h->chroma_weight_flag[list]= 1;
  2026. }
  2027. }
  2028. }else{
  2029. int j;
  2030. for(j=0; j<2; j++){
  2031. h->chroma_weight[i][list][j][0]= chroma_def;
  2032. h->chroma_weight[i][list][j][1]= 0;
  2033. }
  2034. }
  2035. }
  2036. }
  2037. if(h->slice_type_nos != AV_PICTURE_TYPE_B) break;
  2038. }
  2039. h->use_weight= h->use_weight || h->use_weight_chroma;
  2040. return 0;
  2041. }
  2042. /**
  2043. * Initialize implicit_weight table.
  2044. * @param field 0/1 initialize the weight for interlaced MBAFF
  2045. * -1 initializes the rest
  2046. */
  2047. static void implicit_weight_table(H264Context *h, int field){
  2048. MpegEncContext * const s = &h->s;
  2049. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  2050. for (i = 0; i < 2; i++) {
  2051. h->luma_weight_flag[i] = 0;
  2052. h->chroma_weight_flag[i] = 0;
  2053. }
  2054. if(field < 0){
  2055. if (s->picture_structure == PICT_FRAME) {
  2056. cur_poc = s->current_picture_ptr->poc;
  2057. } else {
  2058. cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
  2059. }
  2060. if( h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF
  2061. && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){
  2062. h->use_weight= 0;
  2063. h->use_weight_chroma= 0;
  2064. return;
  2065. }
  2066. ref_start= 0;
  2067. ref_count0= h->ref_count[0];
  2068. ref_count1= h->ref_count[1];
  2069. }else{
  2070. cur_poc = s->current_picture_ptr->field_poc[field];
  2071. ref_start= 16;
  2072. ref_count0= 16+2*h->ref_count[0];
  2073. ref_count1= 16+2*h->ref_count[1];
  2074. }
  2075. h->use_weight= 2;
  2076. h->use_weight_chroma= 2;
  2077. h->luma_log2_weight_denom= 5;
  2078. h->chroma_log2_weight_denom= 5;
  2079. for(ref0=ref_start; ref0 < ref_count0; ref0++){
  2080. int poc0 = h->ref_list[0][ref0].poc;
  2081. for(ref1=ref_start; ref1 < ref_count1; ref1++){
  2082. int w = 32;
  2083. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  2084. int poc1 = h->ref_list[1][ref1].poc;
  2085. int td = av_clip(poc1 - poc0, -128, 127);
  2086. if(td){
  2087. int tb = av_clip(cur_poc - poc0, -128, 127);
  2088. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2089. int dist_scale_factor = (tb*tx + 32) >> 8;
  2090. if(dist_scale_factor >= -64 && dist_scale_factor <= 128)
  2091. w = 64 - dist_scale_factor;
  2092. }
  2093. }
  2094. if(field<0){
  2095. h->implicit_weight[ref0][ref1][0]=
  2096. h->implicit_weight[ref0][ref1][1]= w;
  2097. }else{
  2098. h->implicit_weight[ref0][ref1][field]=w;
  2099. }
  2100. }
  2101. }
  2102. }
  2103. /**
  2104. * instantaneous decoder refresh.
  2105. */
  2106. static void idr(H264Context *h){
  2107. int i;
  2108. ff_h264_remove_all_refs(h);
  2109. h->prev_frame_num= 0;
  2110. h->prev_frame_num_offset= 0;
  2111. h->prev_poc_msb= 1<<16;
  2112. h->prev_poc_lsb= 0;
  2113. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  2114. h->last_pocs[i] = INT_MIN;
  2115. }
  2116. /* forget old pics after a seek */
  2117. static void flush_dpb(AVCodecContext *avctx){
  2118. H264Context *h= avctx->priv_data;
  2119. int i;
  2120. for(i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
  2121. if(h->delayed_pic[i])
  2122. h->delayed_pic[i]->f.reference = 0;
  2123. h->delayed_pic[i]= NULL;
  2124. }
  2125. h->outputed_poc=h->next_outputed_poc= INT_MIN;
  2126. h->prev_interlaced_frame = 1;
  2127. idr(h);
  2128. h->prev_frame_num= -1;
  2129. if(h->s.current_picture_ptr)
  2130. h->s.current_picture_ptr->f.reference = 0;
  2131. h->s.first_field= 0;
  2132. ff_h264_reset_sei(h);
  2133. ff_mpeg_flush(avctx);
  2134. h->recovery_frame= -1;
  2135. h->sync= 0;
  2136. }
  2137. static int init_poc(H264Context *h){
  2138. MpegEncContext * const s = &h->s;
  2139. const int max_frame_num= 1<<h->sps.log2_max_frame_num;
  2140. int field_poc[2];
  2141. Picture *cur = s->current_picture_ptr;
  2142. h->frame_num_offset= h->prev_frame_num_offset;
  2143. if(h->frame_num < h->prev_frame_num)
  2144. h->frame_num_offset += max_frame_num;
  2145. if(h->sps.poc_type==0){
  2146. const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;
  2147. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)
  2148. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  2149. else 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
  2152. h->poc_msb = h->prev_poc_msb;
  2153. //printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);
  2154. field_poc[0] =
  2155. field_poc[1] = h->poc_msb + h->poc_lsb;
  2156. if(s->picture_structure == PICT_FRAME)
  2157. field_poc[1] += h->delta_poc_bottom;
  2158. }else if(h->sps.poc_type==1){
  2159. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  2160. int i;
  2161. if(h->sps.poc_cycle_length != 0)
  2162. abs_frame_num = h->frame_num_offset + h->frame_num;
  2163. else
  2164. abs_frame_num = 0;
  2165. if(h->nal_ref_idc==0 && abs_frame_num > 0)
  2166. abs_frame_num--;
  2167. expected_delta_per_poc_cycle = 0;
  2168. for(i=0; i < h->sps.poc_cycle_length; i++)
  2169. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse
  2170. if(abs_frame_num > 0){
  2171. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  2172. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  2173. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  2174. for(i = 0; i <= frame_num_in_poc_cycle; i++)
  2175. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];
  2176. } else
  2177. expectedpoc = 0;
  2178. if(h->nal_ref_idc == 0)
  2179. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  2180. field_poc[0] = expectedpoc + h->delta_poc[0];
  2181. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  2182. if(s->picture_structure == PICT_FRAME)
  2183. field_poc[1] += h->delta_poc[1];
  2184. }else{
  2185. int poc= 2*(h->frame_num_offset + h->frame_num);
  2186. if(!h->nal_ref_idc)
  2187. poc--;
  2188. field_poc[0]= poc;
  2189. field_poc[1]= poc;
  2190. }
  2191. if(s->picture_structure != PICT_BOTTOM_FIELD)
  2192. s->current_picture_ptr->field_poc[0]= field_poc[0];
  2193. if(s->picture_structure != PICT_TOP_FIELD)
  2194. s->current_picture_ptr->field_poc[1]= field_poc[1];
  2195. cur->poc= FFMIN(cur->field_poc[0], cur->field_poc[1]);
  2196. return 0;
  2197. }
  2198. /**
  2199. * initialize scan tables
  2200. */
  2201. static void init_scan_tables(H264Context *h){
  2202. int i;
  2203. for(i=0; i<16; i++){
  2204. #define T(x) (x>>2) | ((x<<2) & 0xF)
  2205. h->zigzag_scan[i] = T(zigzag_scan[i]);
  2206. h-> field_scan[i] = T( field_scan[i]);
  2207. #undef T
  2208. }
  2209. for(i=0; i<64; i++){
  2210. #define T(x) (x>>3) | ((x&7)<<3)
  2211. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  2212. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  2213. h->field_scan8x8[i] = T(field_scan8x8[i]);
  2214. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  2215. #undef T
  2216. }
  2217. if(h->sps.transform_bypass){ //FIXME same ugly
  2218. h->zigzag_scan_q0 = zigzag_scan;
  2219. h->zigzag_scan8x8_q0 = ff_zigzag_direct;
  2220. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  2221. h->field_scan_q0 = field_scan;
  2222. h->field_scan8x8_q0 = field_scan8x8;
  2223. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  2224. }else{
  2225. h->zigzag_scan_q0 = h->zigzag_scan;
  2226. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  2227. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  2228. h->field_scan_q0 = h->field_scan;
  2229. h->field_scan8x8_q0 = h->field_scan8x8;
  2230. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  2231. }
  2232. }
  2233. static int field_end(H264Context *h, int in_setup){
  2234. MpegEncContext * const s = &h->s;
  2235. AVCodecContext * const avctx= s->avctx;
  2236. int err = 0;
  2237. s->mb_y= 0;
  2238. if (!in_setup && !s->dropable)
  2239. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, (16*s->mb_height >> FIELD_PICTURE) - 1,
  2240. s->picture_structure==PICT_BOTTOM_FIELD);
  2241. if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2242. ff_vdpau_h264_set_reference_frames(s);
  2243. if(in_setup || !(avctx->active_thread_type&FF_THREAD_FRAME)){
  2244. if(!s->dropable) {
  2245. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2246. h->prev_poc_msb= h->poc_msb;
  2247. h->prev_poc_lsb= h->poc_lsb;
  2248. }
  2249. h->prev_frame_num_offset= h->frame_num_offset;
  2250. h->prev_frame_num= h->frame_num;
  2251. h->outputed_poc = h->next_outputed_poc;
  2252. }
  2253. if (avctx->hwaccel) {
  2254. if (avctx->hwaccel->end_frame(avctx) < 0)
  2255. av_log(avctx, AV_LOG_ERROR, "hardware accelerator failed to decode picture\n");
  2256. }
  2257. if (CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2258. ff_vdpau_h264_picture_complete(s);
  2259. /*
  2260. * FIXME: Error handling code does not seem to support interlaced
  2261. * when slices span multiple rows
  2262. * The ff_er_add_slice calls don't work right for bottom
  2263. * fields; they cause massive erroneous error concealing
  2264. * Error marking covers both fields (top and bottom).
  2265. * This causes a mismatched s->error_count
  2266. * and a bad error table. Further, the error count goes to
  2267. * INT_MAX when called for bottom field, because mb_y is
  2268. * past end by one (callers fault) and resync_mb_y != 0
  2269. * causes problems for the first MB line, too.
  2270. */
  2271. if (!FIELD_PICTURE)
  2272. ff_er_frame_end(s);
  2273. MPV_frame_end(s);
  2274. h->current_slice=0;
  2275. return err;
  2276. }
  2277. /**
  2278. * Replicate H264 "master" context to thread contexts.
  2279. */
  2280. static void clone_slice(H264Context *dst, H264Context *src)
  2281. {
  2282. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  2283. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  2284. dst->s.current_picture = src->s.current_picture;
  2285. dst->s.linesize = src->s.linesize;
  2286. dst->s.uvlinesize = src->s.uvlinesize;
  2287. dst->s.first_field = src->s.first_field;
  2288. dst->prev_poc_msb = src->prev_poc_msb;
  2289. dst->prev_poc_lsb = src->prev_poc_lsb;
  2290. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2291. dst->prev_frame_num = src->prev_frame_num;
  2292. dst->short_ref_count = src->short_ref_count;
  2293. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2294. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2295. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2296. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  2297. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2298. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2299. }
  2300. /**
  2301. * Compute profile from profile_idc and constraint_set?_flags.
  2302. *
  2303. * @param sps SPS
  2304. *
  2305. * @return profile as defined by FF_PROFILE_H264_*
  2306. */
  2307. int ff_h264_get_profile(SPS *sps)
  2308. {
  2309. int profile = sps->profile_idc;
  2310. switch(sps->profile_idc) {
  2311. case FF_PROFILE_H264_BASELINE:
  2312. // constraint_set1_flag set to 1
  2313. profile |= (sps->constraint_set_flags & 1<<1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2314. break;
  2315. case FF_PROFILE_H264_HIGH_10:
  2316. case FF_PROFILE_H264_HIGH_422:
  2317. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2318. // constraint_set3_flag set to 1
  2319. profile |= (sps->constraint_set_flags & 1<<3) ? FF_PROFILE_H264_INTRA : 0;
  2320. break;
  2321. }
  2322. return profile;
  2323. }
  2324. /**
  2325. * Decode a slice header.
  2326. * This will also call MPV_common_init() and frame_start() as needed.
  2327. *
  2328. * @param h h264context
  2329. * @param h0 h264 master context (differs from 'h' when doing sliced based parallel decoding)
  2330. *
  2331. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  2332. */
  2333. static int decode_slice_header(H264Context *h, H264Context *h0){
  2334. MpegEncContext * const s = &h->s;
  2335. MpegEncContext * const s0 = &h0->s;
  2336. unsigned int first_mb_in_slice;
  2337. unsigned int pps_id;
  2338. int num_ref_idx_active_override_flag;
  2339. unsigned int slice_type, tmp, i, j;
  2340. int default_ref_list_done = 0;
  2341. int last_pic_structure;
  2342. s->dropable= h->nal_ref_idc == 0;
  2343. /* FIXME: 2tap qpel isn't implemented for high bit depth. */
  2344. if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !h->nal_ref_idc && !h->pixel_shift){
  2345. s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;
  2346. s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;
  2347. }else{
  2348. s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;
  2349. s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;
  2350. }
  2351. first_mb_in_slice= get_ue_golomb_long(&s->gb);
  2352. if(first_mb_in_slice == 0){ //FIXME better field boundary detection
  2353. if(h0->current_slice && FIELD_PICTURE){
  2354. field_end(h, 1);
  2355. }
  2356. h0->current_slice = 0;
  2357. if (!s0->first_field)
  2358. s->current_picture_ptr= NULL;
  2359. }
  2360. slice_type= get_ue_golomb_31(&s->gb);
  2361. if(slice_type > 9){
  2362. 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);
  2363. return -1;
  2364. }
  2365. if(slice_type > 4){
  2366. slice_type -= 5;
  2367. h->slice_type_fixed=1;
  2368. }else
  2369. h->slice_type_fixed=0;
  2370. slice_type= golomb_to_pict_type[ slice_type ];
  2371. if (slice_type == AV_PICTURE_TYPE_I
  2372. || (h0->current_slice != 0 && slice_type == h0->last_slice_type) ) {
  2373. default_ref_list_done = 1;
  2374. }
  2375. h->slice_type= slice_type;
  2376. h->slice_type_nos= slice_type & 3;
  2377. s->pict_type= h->slice_type; // to make a few old functions happy, it's wrong though
  2378. pps_id= get_ue_golomb(&s->gb);
  2379. if(pps_id>=MAX_PPS_COUNT){
  2380. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");
  2381. return -1;
  2382. }
  2383. if(!h0->pps_buffers[pps_id]) {
  2384. av_log(h->s.avctx, AV_LOG_ERROR, "non-existing PPS %u referenced\n", pps_id);
  2385. return -1;
  2386. }
  2387. h->pps= *h0->pps_buffers[pps_id];
  2388. if(!h0->sps_buffers[h->pps.sps_id]) {
  2389. av_log(h->s.avctx, AV_LOG_ERROR, "non-existing SPS %u referenced\n", h->pps.sps_id);
  2390. return -1;
  2391. }
  2392. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2393. s->avctx->profile = ff_h264_get_profile(&h->sps);
  2394. s->avctx->level = h->sps.level_idc;
  2395. s->avctx->refs = h->sps.ref_frame_count;
  2396. if(h == h0 && h->dequant_coeff_pps != pps_id){
  2397. h->dequant_coeff_pps = pps_id;
  2398. init_dequant_tables(h);
  2399. }
  2400. s->mb_width= h->sps.mb_width;
  2401. s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2402. h->b_stride= s->mb_width*4;
  2403. s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  2404. s->width = 16*s->mb_width;
  2405. s->height= 16*s->mb_height;
  2406. if (s->context_initialized
  2407. && ( s->width != s->avctx->coded_width || s->height != s->avctx->coded_height
  2408. || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
  2409. || h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2410. || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio))) {
  2411. if(h != h0) {
  2412. av_log_missing_feature(s->avctx, "Width/height/bit depth/chroma idc changing with threads is", 0);
  2413. return -1; // width / height changed during parallelized decoding
  2414. }
  2415. free_tables(h, 0);
  2416. flush_dpb(s->avctx);
  2417. MPV_common_end(s);
  2418. h->list_count = 0;
  2419. }
  2420. if (!s->context_initialized) {
  2421. if (h != h0) {
  2422. av_log(h->s.avctx, AV_LOG_ERROR, "Cannot (re-)initialize context during parallel decoding.\n");
  2423. return -1;
  2424. }
  2425. avcodec_set_dimensions(s->avctx, s->width, s->height);
  2426. s->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
  2427. 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);
  2428. s->avctx->sample_aspect_ratio= h->sps.sar;
  2429. av_assert0(s->avctx->sample_aspect_ratio.den);
  2430. if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2431. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  2432. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10 &&
  2433. (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
  2434. s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  2435. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  2436. h->pixel_shift = h->sps.bit_depth_luma > 8;
  2437. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
  2438. ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
  2439. s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
  2440. dsputil_init(&s->dsp, s->avctx);
  2441. } else {
  2442. av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
  2443. h->sps.bit_depth_luma, h->sps.chroma_format_idc);
  2444. return -1;
  2445. }
  2446. }
  2447. if(h->sps.video_signal_type_present_flag){
  2448. s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  2449. if(h->sps.colour_description_present_flag){
  2450. s->avctx->color_primaries = h->sps.color_primaries;
  2451. s->avctx->color_trc = h->sps.color_trc;
  2452. s->avctx->colorspace = h->sps.colorspace;
  2453. }
  2454. }
  2455. if(h->sps.timing_info_present_flag){
  2456. int64_t den= h->sps.time_scale;
  2457. if(h->x264_build < 44U)
  2458. den *= 2;
  2459. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  2460. h->sps.num_units_in_tick, den, 1<<30);
  2461. }
  2462. switch (h->sps.bit_depth_luma) {
  2463. case 9 :
  2464. if (CHROMA444) {
  2465. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2466. s->avctx->pix_fmt = PIX_FMT_GBRP9;
  2467. } else
  2468. s->avctx->pix_fmt = PIX_FMT_YUV444P9;
  2469. } else if (CHROMA422)
  2470. s->avctx->pix_fmt = PIX_FMT_YUV422P9;
  2471. else
  2472. s->avctx->pix_fmt = PIX_FMT_YUV420P9;
  2473. break;
  2474. case 10 :
  2475. if (CHROMA444) {
  2476. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2477. s->avctx->pix_fmt = PIX_FMT_GBRP10;
  2478. } else
  2479. s->avctx->pix_fmt = PIX_FMT_YUV444P10;
  2480. } else if (CHROMA422)
  2481. s->avctx->pix_fmt = PIX_FMT_YUV422P10;
  2482. else
  2483. s->avctx->pix_fmt = PIX_FMT_YUV420P10;
  2484. break;
  2485. default:
  2486. if (CHROMA444){
  2487. s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ444P : PIX_FMT_YUV444P;
  2488. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2489. s->avctx->pix_fmt = PIX_FMT_GBR24P;
  2490. av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
  2491. } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
  2492. av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
  2493. }
  2494. } else if (CHROMA422) {
  2495. s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? PIX_FMT_YUVJ422P : PIX_FMT_YUV422P;
  2496. }else{
  2497. s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
  2498. s->avctx->codec->pix_fmts ?
  2499. s->avctx->codec->pix_fmts :
  2500. s->avctx->color_range == AVCOL_RANGE_JPEG ?
  2501. hwaccel_pixfmt_list_h264_jpeg_420 :
  2502. ff_hwaccel_pixfmt_list_420);
  2503. }
  2504. }
  2505. s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
  2506. if (MPV_common_init(s) < 0) {
  2507. av_log(h->s.avctx, AV_LOG_ERROR, "MPV_common_init() failed.\n");
  2508. return -1;
  2509. }
  2510. s->first_field = 0;
  2511. h->prev_interlaced_frame = 1;
  2512. init_scan_tables(h);
  2513. if (ff_h264_alloc_tables(h) < 0) {
  2514. av_log(h->s.avctx, AV_LOG_ERROR, "Could not allocate memory for h264\n");
  2515. return AVERROR(ENOMEM);
  2516. }
  2517. if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_SLICE)) {
  2518. if (context_init(h) < 0) {
  2519. av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2520. return -1;
  2521. }
  2522. } else {
  2523. for(i = 1; i < s->slice_context_count; i++) {
  2524. H264Context *c;
  2525. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  2526. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  2527. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  2528. c->h264dsp = h->h264dsp;
  2529. c->sps = h->sps;
  2530. c->pps = h->pps;
  2531. c->pixel_shift = h->pixel_shift;
  2532. c->cur_chroma_format_idc = h->cur_chroma_format_idc;
  2533. init_scan_tables(c);
  2534. clone_tables(c, h, i);
  2535. }
  2536. for(i = 0; i < s->slice_context_count; i++)
  2537. if (context_init(h->thread_context[i]) < 0) {
  2538. av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2539. return -1;
  2540. }
  2541. }
  2542. }
  2543. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  2544. h->mb_mbaff = 0;
  2545. h->mb_aff_frame = 0;
  2546. last_pic_structure = s0->picture_structure;
  2547. if(h->sps.frame_mbs_only_flag){
  2548. s->picture_structure= PICT_FRAME;
  2549. }else{
  2550. if(!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B){
  2551. av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  2552. return -1;
  2553. }
  2554. if(get_bits1(&s->gb)) { //field_pic_flag
  2555. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  2556. } else {
  2557. s->picture_structure= PICT_FRAME;
  2558. h->mb_aff_frame = h->sps.mb_aff;
  2559. }
  2560. }
  2561. h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
  2562. if(h0->current_slice == 0){
  2563. // Shorten frame num gaps so we don't have to allocate reference frames just to throw them away
  2564. if(h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
  2565. int unwrap_prev_frame_num = h->prev_frame_num, max_frame_num = 1<<h->sps.log2_max_frame_num;
  2566. if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num;
  2567. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  2568. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  2569. if (unwrap_prev_frame_num < 0)
  2570. unwrap_prev_frame_num += max_frame_num;
  2571. h->prev_frame_num = unwrap_prev_frame_num;
  2572. }
  2573. }
  2574. while(h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 &&
  2575. h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
  2576. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2577. av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
  2578. if (ff_h264_frame_start(h) < 0)
  2579. return -1;
  2580. h->prev_frame_num++;
  2581. h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
  2582. s->current_picture_ptr->frame_num= h->prev_frame_num;
  2583. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 0);
  2584. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, INT_MAX, 1);
  2585. ff_generate_sliding_window_mmcos(h);
  2586. if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
  2587. (s->avctx->err_recognition & AV_EF_EXPLODE))
  2588. return AVERROR_INVALIDDATA;
  2589. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2590. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  2591. * about there being no actual duplicates.
  2592. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  2593. * concealing a lost frame, this probably isn't noticeable by comparison, but it should
  2594. * be fixed. */
  2595. if (h->short_ref_count) {
  2596. if (prev) {
  2597. av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
  2598. (const uint8_t**)prev->f.data, prev->f.linesize,
  2599. s->avctx->pix_fmt, s->mb_width*16, s->mb_height*16);
  2600. h->short_ref[0]->poc = prev->poc+2;
  2601. }
  2602. h->short_ref[0]->frame_num = h->prev_frame_num;
  2603. }
  2604. }
  2605. /* See if we have a decoded first field looking for a pair... */
  2606. if (s0->first_field) {
  2607. assert(s0->current_picture_ptr);
  2608. assert(s0->current_picture_ptr->f.data[0]);
  2609. assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
  2610. /* figure out if we have a complementary field pair */
  2611. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2612. /*
  2613. * Previous field is unmatched. Don't display it, but let it
  2614. * remain for reference if marked as such.
  2615. */
  2616. s0->current_picture_ptr = NULL;
  2617. s0->first_field = FIELD_PICTURE;
  2618. } else {
  2619. if (s0->current_picture_ptr->frame_num != h->frame_num) {
  2620. /*
  2621. * This and previous field had
  2622. * different frame_nums. Consider this field first in
  2623. * pair. Throw away previous field except for reference
  2624. * purposes.
  2625. */
  2626. s0->first_field = 1;
  2627. s0->current_picture_ptr = NULL;
  2628. } else {
  2629. /* Second field in complementary pair */
  2630. s0->first_field = 0;
  2631. }
  2632. }
  2633. } else {
  2634. /* Frame or first field in a potentially complementary pair */
  2635. assert(!s0->current_picture_ptr);
  2636. s0->first_field = FIELD_PICTURE;
  2637. }
  2638. if(!FIELD_PICTURE || s0->first_field) {
  2639. if (ff_h264_frame_start(h) < 0) {
  2640. s0->first_field = 0;
  2641. return -1;
  2642. }
  2643. } else {
  2644. ff_release_unused_pictures(s, 0);
  2645. }
  2646. }
  2647. if(h != h0)
  2648. clone_slice(h, h0);
  2649. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  2650. assert(s->mb_num == s->mb_width * s->mb_height);
  2651. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  2652. first_mb_in_slice >= s->mb_num){
  2653. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2654. return -1;
  2655. }
  2656. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  2657. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  2658. if (s->picture_structure == PICT_BOTTOM_FIELD)
  2659. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  2660. assert(s->mb_y < s->mb_height);
  2661. if(s->picture_structure==PICT_FRAME){
  2662. h->curr_pic_num= h->frame_num;
  2663. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  2664. }else{
  2665. h->curr_pic_num= 2*h->frame_num + 1;
  2666. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  2667. }
  2668. if(h->nal_unit_type == NAL_IDR_SLICE){
  2669. get_ue_golomb(&s->gb); /* idr_pic_id */
  2670. }
  2671. if(h->sps.poc_type==0){
  2672. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  2673. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  2674. h->delta_poc_bottom= get_se_golomb(&s->gb);
  2675. }
  2676. }
  2677. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  2678. h->delta_poc[0]= get_se_golomb(&s->gb);
  2679. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  2680. h->delta_poc[1]= get_se_golomb(&s->gb);
  2681. }
  2682. init_poc(h);
  2683. if(h->pps.redundant_pic_cnt_present){
  2684. h->redundant_pic_count= get_ue_golomb(&s->gb);
  2685. }
  2686. //set defaults, might be overridden a few lines later
  2687. h->ref_count[0]= h->pps.ref_count[0];
  2688. h->ref_count[1]= h->pps.ref_count[1];
  2689. if(h->slice_type_nos != AV_PICTURE_TYPE_I){
  2690. unsigned max= (16<<(s->picture_structure != PICT_FRAME))-1;
  2691. if(h->slice_type_nos == AV_PICTURE_TYPE_B){
  2692. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  2693. }
  2694. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  2695. if(num_ref_idx_active_override_flag){
  2696. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  2697. if(h->slice_type_nos==AV_PICTURE_TYPE_B)
  2698. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  2699. }
  2700. if(h->ref_count[0]-1 > max || h->ref_count[1]-1 > max){
  2701. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  2702. h->ref_count[0]= h->ref_count[1]= 1;
  2703. return -1;
  2704. }
  2705. if(h->slice_type_nos == AV_PICTURE_TYPE_B)
  2706. h->list_count= 2;
  2707. else
  2708. h->list_count= 1;
  2709. }else
  2710. h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
  2711. if(!default_ref_list_done){
  2712. ff_h264_fill_default_ref_list(h);
  2713. }
  2714. if(h->slice_type_nos!=AV_PICTURE_TYPE_I && ff_h264_decode_ref_pic_list_reordering(h) < 0) {
  2715. h->ref_count[1]= h->ref_count[0]= 0;
  2716. return -1;
  2717. }
  2718. if(h->slice_type_nos!=AV_PICTURE_TYPE_I){
  2719. s->last_picture_ptr= &h->ref_list[0][0];
  2720. ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  2721. }
  2722. if(h->slice_type_nos==AV_PICTURE_TYPE_B){
  2723. s->next_picture_ptr= &h->ref_list[1][0];
  2724. ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  2725. }
  2726. if( (h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P )
  2727. || (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== AV_PICTURE_TYPE_B ) )
  2728. pred_weight_table(h);
  2729. else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
  2730. implicit_weight_table(h, -1);
  2731. }else {
  2732. h->use_weight = 0;
  2733. for (i = 0; i < 2; i++) {
  2734. h->luma_weight_flag[i] = 0;
  2735. h->chroma_weight_flag[i] = 0;
  2736. }
  2737. }
  2738. if(h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
  2739. (s->avctx->err_recognition & AV_EF_EXPLODE))
  2740. return AVERROR_INVALIDDATA;
  2741. if(FRAME_MBAFF){
  2742. ff_h264_fill_mbaff_ref_list(h);
  2743. if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== AV_PICTURE_TYPE_B){
  2744. implicit_weight_table(h, 0);
  2745. implicit_weight_table(h, 1);
  2746. }
  2747. }
  2748. if(h->slice_type_nos==AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  2749. ff_h264_direct_dist_scale_factor(h);
  2750. ff_h264_direct_ref_list_init(h);
  2751. if( h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac ){
  2752. tmp = get_ue_golomb_31(&s->gb);
  2753. if(tmp > 2){
  2754. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  2755. return -1;
  2756. }
  2757. h->cabac_init_idc= tmp;
  2758. }
  2759. h->last_qscale_diff = 0;
  2760. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  2761. if(tmp>51+6*(h->sps.bit_depth_luma-8)){
  2762. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  2763. return -1;
  2764. }
  2765. s->qscale= tmp;
  2766. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2767. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2768. //FIXME qscale / qp ... stuff
  2769. if(h->slice_type == AV_PICTURE_TYPE_SP){
  2770. get_bits1(&s->gb); /* sp_for_switch_flag */
  2771. }
  2772. if(h->slice_type==AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI){
  2773. get_se_golomb(&s->gb); /* slice_qs_delta */
  2774. }
  2775. h->deblocking_filter = 1;
  2776. h->slice_alpha_c0_offset = 52;
  2777. h->slice_beta_offset = 52;
  2778. if( h->pps.deblocking_filter_parameters_present ) {
  2779. tmp= get_ue_golomb_31(&s->gb);
  2780. if(tmp > 2){
  2781. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  2782. return -1;
  2783. }
  2784. h->deblocking_filter= tmp;
  2785. if(h->deblocking_filter < 2)
  2786. h->deblocking_filter^= 1; // 1<->0
  2787. if( h->deblocking_filter ) {
  2788. h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
  2789. h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
  2790. if( h->slice_alpha_c0_offset > 104U
  2791. || h->slice_beta_offset > 104U){
  2792. 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);
  2793. return -1;
  2794. }
  2795. }
  2796. }
  2797. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  2798. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I)
  2799. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B)
  2800. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  2801. h->deblocking_filter= 0;
  2802. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  2803. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  2804. /* Cheat slightly for speed:
  2805. Do not bother to deblock across slices. */
  2806. h->deblocking_filter = 2;
  2807. } else {
  2808. h0->max_contexts = 1;
  2809. if(!h0->single_decode_warning) {
  2810. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  2811. h0->single_decode_warning = 1;
  2812. }
  2813. if (h != h0) {
  2814. av_log(h->s.avctx, AV_LOG_ERROR, "Deblocking switched inside frame.\n");
  2815. return 1;
  2816. }
  2817. }
  2818. }
  2819. h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset)
  2820. - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1])
  2821. + 6 * (h->sps.bit_depth_luma - 8);
  2822. #if 0 //FMO
  2823. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  2824. slice_group_change_cycle= get_bits(&s->gb, ?);
  2825. #endif
  2826. h0->last_slice_type = slice_type;
  2827. h->slice_num = ++h0->current_slice;
  2828. if(h->slice_num)
  2829. h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
  2830. if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
  2831. && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
  2832. && h->slice_num >= MAX_SLICES) {
  2833. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  2834. 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);
  2835. }
  2836. for(j=0; j<2; j++){
  2837. int id_list[16];
  2838. int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
  2839. for(i=0; i<16; i++){
  2840. id_list[i]= 60;
  2841. if (h->ref_list[j][i].f.data[0]) {
  2842. int k;
  2843. uint8_t *base = h->ref_list[j][i].f.base[0];
  2844. for(k=0; k<h->short_ref_count; k++)
  2845. if (h->short_ref[k]->f.base[0] == base) {
  2846. id_list[i]= k;
  2847. break;
  2848. }
  2849. for(k=0; k<h->long_ref_count; k++)
  2850. if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
  2851. id_list[i]= h->short_ref_count + k;
  2852. break;
  2853. }
  2854. }
  2855. }
  2856. ref2frm[0]=
  2857. ref2frm[1]= -1;
  2858. for(i=0; i<16; i++)
  2859. ref2frm[i+2]= 4*id_list[i]
  2860. + (h->ref_list[j][i].f.reference & 3);
  2861. ref2frm[18+0]=
  2862. ref2frm[18+1]= -1;
  2863. for(i=16; i<48; i++)
  2864. ref2frm[i+4]= 4*id_list[(i-16)>>1]
  2865. + (h->ref_list[j][i].f.reference & 3);
  2866. }
  2867. //FIXME: fix draw_edges+PAFF+frame threads
  2868. h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE || (!h->sps.frame_mbs_only_flag && s->avctx->active_thread_type)) ? 0 : 16;
  2869. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  2870. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  2871. 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",
  2872. h->slice_num,
  2873. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  2874. first_mb_in_slice,
  2875. av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  2876. pps_id, h->frame_num,
  2877. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  2878. h->ref_count[0], h->ref_count[1],
  2879. s->qscale,
  2880. h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
  2881. h->use_weight,
  2882. h->use_weight==1 && h->use_weight_chroma ? "c" : "",
  2883. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
  2884. );
  2885. }
  2886. return 0;
  2887. }
  2888. int ff_h264_get_slice_type(const H264Context *h)
  2889. {
  2890. switch (h->slice_type) {
  2891. case AV_PICTURE_TYPE_P: return 0;
  2892. case AV_PICTURE_TYPE_B: return 1;
  2893. case AV_PICTURE_TYPE_I: return 2;
  2894. case AV_PICTURE_TYPE_SP: return 3;
  2895. case AV_PICTURE_TYPE_SI: return 4;
  2896. default: return -1;
  2897. }
  2898. }
  2899. static av_always_inline void fill_filter_caches_inter(H264Context *h, MpegEncContext * const s, int mb_type, int top_xy,
  2900. int left_xy[LEFT_MBS], int top_type, int left_type[LEFT_MBS], int mb_xy, int list)
  2901. {
  2902. int b_stride = h->b_stride;
  2903. int16_t (*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  2904. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  2905. if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
  2906. if(USES_LIST(top_type, list)){
  2907. const int b_xy= h->mb2b_xy[top_xy] + 3*b_stride;
  2908. const int b8_xy= 4*top_xy + 2;
  2909. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2910. AV_COPY128(mv_dst - 1*8, s->current_picture.f.motion_val[list][b_xy + 0]);
  2911. ref_cache[0 - 1*8]=
  2912. ref_cache[1 - 1*8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
  2913. ref_cache[2 - 1*8]=
  2914. ref_cache[3 - 1*8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
  2915. }else{
  2916. AV_ZERO128(mv_dst - 1*8);
  2917. AV_WN32A(&ref_cache[0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2918. }
  2919. if(!IS_INTERLACED(mb_type^left_type[LTOP])){
  2920. if(USES_LIST(left_type[LTOP], list)){
  2921. const int b_xy= h->mb2b_xy[left_xy[LTOP]] + 3;
  2922. const int b8_xy= 4*left_xy[LTOP] + 1;
  2923. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[LTOP]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2924. AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride*0]);
  2925. AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride*1]);
  2926. AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride*2]);
  2927. AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride*3]);
  2928. ref_cache[-1 + 0]=
  2929. ref_cache[-1 + 8]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2*0]];
  2930. ref_cache[-1 + 16]=
  2931. ref_cache[-1 + 24]= ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2*1]];
  2932. }else{
  2933. AV_ZERO32(mv_dst - 1 + 0);
  2934. AV_ZERO32(mv_dst - 1 + 8);
  2935. AV_ZERO32(mv_dst - 1 +16);
  2936. AV_ZERO32(mv_dst - 1 +24);
  2937. ref_cache[-1 + 0]=
  2938. ref_cache[-1 + 8]=
  2939. ref_cache[-1 + 16]=
  2940. ref_cache[-1 + 24]= LIST_NOT_USED;
  2941. }
  2942. }
  2943. }
  2944. if(!USES_LIST(mb_type, list)){
  2945. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0,0), 4);
  2946. AV_WN32A(&ref_cache[0*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2947. AV_WN32A(&ref_cache[1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2948. AV_WN32A(&ref_cache[2*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2949. AV_WN32A(&ref_cache[3*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2950. return;
  2951. }
  2952. {
  2953. int8_t *ref = &s->current_picture.f.ref_index[list][4*mb_xy];
  2954. int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2955. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101;
  2956. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]],ref2frm[list][ref[3]])&0x00FF00FF)*0x0101;
  2957. AV_WN32A(&ref_cache[0*8], ref01);
  2958. AV_WN32A(&ref_cache[1*8], ref01);
  2959. AV_WN32A(&ref_cache[2*8], ref23);
  2960. AV_WN32A(&ref_cache[3*8], ref23);
  2961. }
  2962. {
  2963. int16_t (*mv_src)[2] = &s->current_picture.f.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
  2964. AV_COPY128(mv_dst + 8*0, mv_src + 0*b_stride);
  2965. AV_COPY128(mv_dst + 8*1, mv_src + 1*b_stride);
  2966. AV_COPY128(mv_dst + 8*2, mv_src + 2*b_stride);
  2967. AV_COPY128(mv_dst + 8*3, mv_src + 3*b_stride);
  2968. }
  2969. }
  2970. /**
  2971. *
  2972. * @return non zero if the loop filter can be skipped
  2973. */
  2974. static int fill_filter_caches(H264Context *h, int mb_type){
  2975. MpegEncContext * const s = &h->s;
  2976. const int mb_xy= h->mb_xy;
  2977. int top_xy, left_xy[LEFT_MBS];
  2978. int top_type, left_type[LEFT_MBS];
  2979. uint8_t *nnz;
  2980. uint8_t *nnz_cache;
  2981. top_xy = mb_xy - (s->mb_stride << MB_FIELD);
  2982. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  2983. * stuff, I can't imagine that these complex rules are worth it. */
  2984. left_xy[LBOT] = left_xy[LTOP] = mb_xy-1;
  2985. if(FRAME_MBAFF){
  2986. const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
  2987. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  2988. if(s->mb_y&1){
  2989. if (left_mb_field_flag != curr_mb_field_flag) {
  2990. left_xy[LTOP] -= s->mb_stride;
  2991. }
  2992. }else{
  2993. if(curr_mb_field_flag){
  2994. top_xy += s->mb_stride & (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
  2995. }
  2996. if (left_mb_field_flag != curr_mb_field_flag) {
  2997. left_xy[LBOT] += s->mb_stride;
  2998. }
  2999. }
  3000. }
  3001. h->top_mb_xy = top_xy;
  3002. h->left_mb_xy[LTOP] = left_xy[LTOP];
  3003. h->left_mb_xy[LBOT] = left_xy[LBOT];
  3004. {
  3005. //for sufficiently low qp, filtering wouldn't do anything
  3006. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  3007. int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
  3008. int qp = s->current_picture.f.qscale_table[mb_xy];
  3009. if(qp <= qp_thresh
  3010. && (left_xy[LTOP] < 0 || ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh)
  3011. && (top_xy < 0 || ((qp + s->current_picture.f.qscale_table[top_xy ] + 1) >> 1) <= qp_thresh)) {
  3012. if(!FRAME_MBAFF)
  3013. return 1;
  3014. if ((left_xy[LTOP] < 0 || ((qp + s->current_picture.f.qscale_table[left_xy[LBOT] ] + 1) >> 1) <= qp_thresh) &&
  3015. (top_xy < s->mb_stride || ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
  3016. return 1;
  3017. }
  3018. }
  3019. top_type = s->current_picture.f.mb_type[top_xy];
  3020. left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
  3021. left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
  3022. if(h->deblocking_filter == 2){
  3023. if(h->slice_table[top_xy ] != h->slice_num) top_type= 0;
  3024. if(h->slice_table[left_xy[LBOT]] != h->slice_num) left_type[LTOP]= left_type[LBOT]= 0;
  3025. }else{
  3026. if(h->slice_table[top_xy ] == 0xFFFF) top_type= 0;
  3027. if(h->slice_table[left_xy[LBOT]] == 0xFFFF) left_type[LTOP]= left_type[LBOT] =0;
  3028. }
  3029. h->top_type = top_type;
  3030. h->left_type[LTOP]= left_type[LTOP];
  3031. h->left_type[LBOT]= left_type[LBOT];
  3032. if(IS_INTRA(mb_type))
  3033. return 0;
  3034. fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 0);
  3035. if(h->list_count == 2)
  3036. fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy, top_type, left_type, mb_xy, 1);
  3037. nnz = h->non_zero_count[mb_xy];
  3038. nnz_cache = h->non_zero_count_cache;
  3039. AV_COPY32(&nnz_cache[4+8*1], &nnz[ 0]);
  3040. AV_COPY32(&nnz_cache[4+8*2], &nnz[ 4]);
  3041. AV_COPY32(&nnz_cache[4+8*3], &nnz[ 8]);
  3042. AV_COPY32(&nnz_cache[4+8*4], &nnz[12]);
  3043. h->cbp= h->cbp_table[mb_xy];
  3044. if(top_type){
  3045. nnz = h->non_zero_count[top_xy];
  3046. AV_COPY32(&nnz_cache[4+8*0], &nnz[3*4]);
  3047. }
  3048. if(left_type[LTOP]){
  3049. nnz = h->non_zero_count[left_xy[LTOP]];
  3050. nnz_cache[3+8*1]= nnz[3+0*4];
  3051. nnz_cache[3+8*2]= nnz[3+1*4];
  3052. nnz_cache[3+8*3]= nnz[3+2*4];
  3053. nnz_cache[3+8*4]= nnz[3+3*4];
  3054. }
  3055. // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
  3056. if(!CABAC && h->pps.transform_8x8_mode){
  3057. if(IS_8x8DCT(top_type)){
  3058. nnz_cache[4+8*0]=
  3059. nnz_cache[5+8*0]= (h->cbp_table[top_xy] & 0x4000) >> 12;
  3060. nnz_cache[6+8*0]=
  3061. nnz_cache[7+8*0]= (h->cbp_table[top_xy] & 0x8000) >> 12;
  3062. }
  3063. if(IS_8x8DCT(left_type[LTOP])){
  3064. nnz_cache[3+8*1]=
  3065. nnz_cache[3+8*2]= (h->cbp_table[left_xy[LTOP]]&0x2000) >> 12; //FIXME check MBAFF
  3066. }
  3067. if(IS_8x8DCT(left_type[LBOT])){
  3068. nnz_cache[3+8*3]=
  3069. nnz_cache[3+8*4]= (h->cbp_table[left_xy[LBOT]]&0x8000) >> 12; //FIXME check MBAFF
  3070. }
  3071. if(IS_8x8DCT(mb_type)){
  3072. nnz_cache[scan8[0 ]]= nnz_cache[scan8[1 ]]=
  3073. nnz_cache[scan8[2 ]]= nnz_cache[scan8[3 ]]= (h->cbp & 0x1000) >> 12;
  3074. nnz_cache[scan8[0+ 4]]= nnz_cache[scan8[1+ 4]]=
  3075. nnz_cache[scan8[2+ 4]]= nnz_cache[scan8[3+ 4]]= (h->cbp & 0x2000) >> 12;
  3076. nnz_cache[scan8[0+ 8]]= nnz_cache[scan8[1+ 8]]=
  3077. nnz_cache[scan8[2+ 8]]= nnz_cache[scan8[3+ 8]]= (h->cbp & 0x4000) >> 12;
  3078. nnz_cache[scan8[0+12]]= nnz_cache[scan8[1+12]]=
  3079. nnz_cache[scan8[2+12]]= nnz_cache[scan8[3+12]]= (h->cbp & 0x8000) >> 12;
  3080. }
  3081. }
  3082. return 0;
  3083. }
  3084. static void loop_filter(H264Context *h, int start_x, int end_x){
  3085. MpegEncContext * const s = &h->s;
  3086. uint8_t *dest_y, *dest_cb, *dest_cr;
  3087. int linesize, uvlinesize, mb_x, mb_y;
  3088. const int end_mb_y= s->mb_y + FRAME_MBAFF;
  3089. const int old_slice_type= h->slice_type;
  3090. const int pixel_shift = h->pixel_shift;
  3091. const int block_h = 16 >> s->chroma_y_shift;
  3092. if(h->deblocking_filter) {
  3093. for(mb_x= start_x; mb_x<end_x; mb_x++){
  3094. for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
  3095. int mb_xy, mb_type;
  3096. mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
  3097. h->slice_num= h->slice_table[mb_xy];
  3098. mb_type = s->current_picture.f.mb_type[mb_xy];
  3099. h->list_count= h->list_counts[mb_xy];
  3100. if(FRAME_MBAFF)
  3101. h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3102. s->mb_x= mb_x;
  3103. s->mb_y= mb_y;
  3104. dest_y = s->current_picture.f.data[0] + ((mb_x << pixel_shift) + mb_y * s->linesize ) * 16;
  3105. dest_cb = s->current_picture.f.data[1] + (mb_x << pixel_shift) * (8 << CHROMA444) + mb_y * s->uvlinesize * block_h;
  3106. dest_cr = s->current_picture.f.data[2] + (mb_x << pixel_shift) * (8 << CHROMA444) + mb_y * s->uvlinesize * block_h;
  3107. //FIXME simplify above
  3108. if (MB_FIELD) {
  3109. linesize = h->mb_linesize = s->linesize * 2;
  3110. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  3111. if(mb_y&1){ //FIXME move out of this function?
  3112. dest_y -= s->linesize*15;
  3113. dest_cb-= s->uvlinesize * (block_h - 1);
  3114. dest_cr-= s->uvlinesize * (block_h - 1);
  3115. }
  3116. } else {
  3117. linesize = h->mb_linesize = s->linesize;
  3118. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  3119. }
  3120. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
  3121. if(fill_filter_caches(h, mb_type))
  3122. continue;
  3123. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
  3124. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
  3125. if (FRAME_MBAFF) {
  3126. ff_h264_filter_mb (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  3127. } else {
  3128. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  3129. }
  3130. }
  3131. }
  3132. }
  3133. h->slice_type= old_slice_type;
  3134. s->mb_x= end_x;
  3135. s->mb_y= end_mb_y - FRAME_MBAFF;
  3136. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  3137. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  3138. }
  3139. static void predict_field_decoding_flag(H264Context *h){
  3140. MpegEncContext * const s = &h->s;
  3141. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3142. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  3143. ? s->current_picture.f.mb_type[mb_xy - 1]
  3144. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  3145. ? s->current_picture.f.mb_type[mb_xy - s->mb_stride]
  3146. : 0;
  3147. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3148. }
  3149. /**
  3150. * Draw edges and report progress for the last MB row.
  3151. */
  3152. static void decode_finish_row(H264Context *h){
  3153. MpegEncContext * const s = &h->s;
  3154. int top = 16*(s->mb_y >> FIELD_PICTURE);
  3155. int height = 16 << FRAME_MBAFF;
  3156. int deblock_border = (16 + 4) << FRAME_MBAFF;
  3157. int pic_height = 16*s->mb_height >> FIELD_PICTURE;
  3158. if (h->deblocking_filter) {
  3159. if((top + height) >= pic_height)
  3160. height += deblock_border;
  3161. top -= deblock_border;
  3162. }
  3163. if (top >= pic_height || (top + height) < h->emu_edge_height)
  3164. return;
  3165. height = FFMIN(height, pic_height - top);
  3166. if (top < h->emu_edge_height) {
  3167. height = top+height;
  3168. top = 0;
  3169. }
  3170. ff_draw_horiz_band(s, top, height);
  3171. if (s->dropable) return;
  3172. ff_thread_report_progress((AVFrame*)s->current_picture_ptr, top + height - 1,
  3173. s->picture_structure==PICT_BOTTOM_FIELD);
  3174. }
  3175. static int decode_slice(struct AVCodecContext *avctx, void *arg){
  3176. H264Context *h = *(void**)arg;
  3177. MpegEncContext * const s = &h->s;
  3178. const int part_mask= s->partitioned_frame ? (ER_AC_END|ER_AC_ERROR) : 0x7F;
  3179. int lf_x_start = s->mb_x;
  3180. s->mb_skip_run= -1;
  3181. h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
  3182. (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
  3183. if( h->pps.cabac ) {
  3184. /* realign */
  3185. align_get_bits( &s->gb );
  3186. /* init cabac */
  3187. ff_init_cabac_states( &h->cabac);
  3188. ff_init_cabac_decoder( &h->cabac,
  3189. s->gb.buffer + get_bits_count(&s->gb)/8,
  3190. (get_bits_left(&s->gb) + 7)/8);
  3191. ff_h264_init_cabac_states(h);
  3192. for(;;){
  3193. //START_TIMER
  3194. int ret = ff_h264_decode_mb_cabac(h);
  3195. int eos;
  3196. //STOP_TIMER("decode_mb_cabac")
  3197. if(ret>=0) ff_h264_hl_decode_mb(h);
  3198. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  3199. s->mb_y++;
  3200. ret = ff_h264_decode_mb_cabac(h);
  3201. if(ret>=0) ff_h264_hl_decode_mb(h);
  3202. s->mb_y--;
  3203. }
  3204. eos = get_cabac_terminate( &h->cabac );
  3205. if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
  3206. 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);
  3207. if (s->mb_x >= lf_x_start) loop_filter(h, lf_x_start, s->mb_x + 1);
  3208. return 0;
  3209. }
  3210. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3211. 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);
  3212. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
  3213. return -1;
  3214. }
  3215. if( ++s->mb_x >= s->mb_width ) {
  3216. loop_filter(h, lf_x_start, s->mb_x);
  3217. s->mb_x = lf_x_start = 0;
  3218. decode_finish_row(h);
  3219. ++s->mb_y;
  3220. if(FIELD_OR_MBAFF_PICTURE) {
  3221. ++s->mb_y;
  3222. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  3223. predict_field_decoding_flag(h);
  3224. }
  3225. }
  3226. if( eos || s->mb_y >= s->mb_height ) {
  3227. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  3228. 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);
  3229. if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);
  3230. return 0;
  3231. }
  3232. }
  3233. } else {
  3234. for(;;){
  3235. int ret = ff_h264_decode_mb_cavlc(h);
  3236. if(ret>=0) ff_h264_hl_decode_mb(h);
  3237. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  3238. s->mb_y++;
  3239. ret = ff_h264_decode_mb_cavlc(h);
  3240. if(ret>=0) ff_h264_hl_decode_mb(h);
  3241. s->mb_y--;
  3242. }
  3243. if(ret<0){
  3244. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  3245. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
  3246. return -1;
  3247. }
  3248. if(++s->mb_x >= s->mb_width){
  3249. loop_filter(h, lf_x_start, s->mb_x);
  3250. s->mb_x = lf_x_start = 0;
  3251. decode_finish_row(h);
  3252. ++s->mb_y;
  3253. if(FIELD_OR_MBAFF_PICTURE) {
  3254. ++s->mb_y;
  3255. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  3256. predict_field_decoding_flag(h);
  3257. }
  3258. if(s->mb_y >= s->mb_height){
  3259. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  3260. if( get_bits_count(&s->gb) == s->gb.size_in_bits
  3261. || get_bits_count(&s->gb) < s->gb.size_in_bits && s->avctx->error_recognition < FF_ER_AGGRESSIVE) {
  3262. 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);
  3263. return 0;
  3264. }else{
  3265. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_END&part_mask);
  3266. return -1;
  3267. }
  3268. }
  3269. }
  3270. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  3271. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  3272. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  3273. 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);
  3274. if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);
  3275. return 0;
  3276. }else{
  3277. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, ER_MB_ERROR&part_mask);
  3278. return -1;
  3279. }
  3280. }
  3281. }
  3282. }
  3283. }
  3284. /**
  3285. * Call decode_slice() for each context.
  3286. *
  3287. * @param h h264 master context
  3288. * @param context_count number of contexts to execute
  3289. */
  3290. static int execute_decode_slices(H264Context *h, int context_count){
  3291. MpegEncContext * const s = &h->s;
  3292. AVCodecContext * const avctx= s->avctx;
  3293. H264Context *hx;
  3294. int i;
  3295. if (s->avctx->hwaccel || s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  3296. return 0;
  3297. if(context_count == 1) {
  3298. return decode_slice(avctx, &h);
  3299. } else {
  3300. for(i = 1; i < context_count; i++) {
  3301. hx = h->thread_context[i];
  3302. hx->s.err_recognition = avctx->err_recognition;
  3303. hx->s.error_count = 0;
  3304. hx->x264_build= h->x264_build;
  3305. }
  3306. avctx->execute(avctx, decode_slice,
  3307. h->thread_context, NULL, context_count, sizeof(void*));
  3308. /* pull back stuff from slices to master context */
  3309. hx = h->thread_context[context_count - 1];
  3310. s->mb_x = hx->s.mb_x;
  3311. s->mb_y = hx->s.mb_y;
  3312. s->dropable = hx->s.dropable;
  3313. s->picture_structure = hx->s.picture_structure;
  3314. for(i = 1; i < context_count; i++)
  3315. h->s.error_count += h->thread_context[i]->s.error_count;
  3316. }
  3317. return 0;
  3318. }
  3319. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
  3320. MpegEncContext * const s = &h->s;
  3321. AVCodecContext * const avctx= s->avctx;
  3322. H264Context *hx; ///< thread context
  3323. int buf_index;
  3324. int context_count;
  3325. int next_avc;
  3326. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3327. int nals_needed=0; ///< number of NALs that need decoding before the next frame thread starts
  3328. int nal_index;
  3329. h->nal_unit_type= 0;
  3330. if(!s->slice_context_count)
  3331. s->slice_context_count= 1;
  3332. h->max_contexts = s->slice_context_count;
  3333. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  3334. h->current_slice = 0;
  3335. if (!s->first_field)
  3336. s->current_picture_ptr= NULL;
  3337. ff_h264_reset_sei(h);
  3338. }
  3339. for(;pass <= 1;pass++){
  3340. buf_index = 0;
  3341. context_count = 0;
  3342. next_avc = h->is_avc ? 0 : buf_size;
  3343. nal_index = 0;
  3344. for(;;){
  3345. int consumed;
  3346. int dst_length;
  3347. int bit_length;
  3348. uint8_t *ptr;
  3349. int i, nalsize = 0;
  3350. int err;
  3351. if(buf_index >= next_avc) {
  3352. if (buf_index >= buf_size - h->nal_length_size) break;
  3353. nalsize = 0;
  3354. for(i = 0; i < h->nal_length_size; i++)
  3355. nalsize = (nalsize << 8) | buf[buf_index++];
  3356. if(nalsize <= 0 || nalsize > buf_size - buf_index){
  3357. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  3358. break;
  3359. }
  3360. next_avc= buf_index + nalsize;
  3361. } else {
  3362. // start code prefix search
  3363. for(; buf_index + 3 < next_avc; buf_index++){
  3364. // This should always succeed in the first iteration.
  3365. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  3366. break;
  3367. }
  3368. if(buf_index+3 >= buf_size) break;
  3369. buf_index+=3;
  3370. if(buf_index >= next_avc) continue;
  3371. }
  3372. hx = h->thread_context[context_count];
  3373. ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
  3374. if (ptr==NULL || dst_length < 0){
  3375. return -1;
  3376. }
  3377. i= buf_index + consumed;
  3378. if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
  3379. buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
  3380. s->workaround_bugs |= FF_BUG_TRUNCATED;
  3381. if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
  3382. while(dst_length > 0 && ptr[dst_length - 1] == 0)
  3383. dst_length--;
  3384. }
  3385. bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
  3386. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  3387. 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);
  3388. }
  3389. if (h->is_avc && (nalsize != consumed) && nalsize){
  3390. av_log(h->s.avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  3391. }
  3392. buf_index += consumed;
  3393. nal_index++;
  3394. if(pass == 0) {
  3395. // packets can sometimes contain multiple PPS/SPS
  3396. // e.g. two PAFF field pictures in one packet, or a demuxer which splits NALs strangely
  3397. // if so, when frame threading we can't start the next thread until we've read all of them
  3398. switch (hx->nal_unit_type) {
  3399. case NAL_SPS:
  3400. case NAL_PPS:
  3401. nals_needed = nal_index;
  3402. break;
  3403. case NAL_IDR_SLICE:
  3404. case NAL_SLICE:
  3405. init_get_bits(&hx->s.gb, ptr, bit_length);
  3406. if (!get_ue_golomb(&hx->s.gb))
  3407. nals_needed = nal_index;
  3408. }
  3409. continue;
  3410. }
  3411. //FIXME do not discard SEI id
  3412. if(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  3413. continue;
  3414. again:
  3415. err = 0;
  3416. switch(hx->nal_unit_type){
  3417. case NAL_IDR_SLICE:
  3418. if (h->nal_unit_type != NAL_IDR_SLICE) {
  3419. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices\n");
  3420. return -1;
  3421. }
  3422. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3423. case NAL_SLICE:
  3424. init_get_bits(&hx->s.gb, ptr, bit_length);
  3425. hx->intra_gb_ptr=
  3426. hx->inter_gb_ptr= &hx->s.gb;
  3427. hx->s.data_partitioning = 0;
  3428. if((err = decode_slice_header(hx, h)))
  3429. break;
  3430. if ( h->sei_recovery_frame_cnt >= 0
  3431. && ( h->recovery_frame<0
  3432. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
  3433. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
  3434. (1 << h->sps.log2_max_frame_num);
  3435. }
  3436. s->current_picture_ptr->f.key_frame |=
  3437. (hx->nal_unit_type == NAL_IDR_SLICE);
  3438. if (h->recovery_frame == h->frame_num) {
  3439. s->current_picture_ptr->sync |= 1;
  3440. h->recovery_frame = -1;
  3441. }
  3442. h->sync |= !!s->current_picture_ptr->f.key_frame;
  3443. h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);
  3444. s->current_picture_ptr->sync |= h->sync;
  3445. if (h->current_slice == 1) {
  3446. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
  3447. decode_postinit(h, nal_index >= nals_needed);
  3448. }
  3449. if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
  3450. return -1;
  3451. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  3452. ff_vdpau_h264_picture_start(s);
  3453. }
  3454. if(hx->redundant_pic_count==0
  3455. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  3456. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=AV_PICTURE_TYPE_B)
  3457. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)
  3458. && avctx->skip_frame < AVDISCARD_ALL){
  3459. if(avctx->hwaccel) {
  3460. if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
  3461. return -1;
  3462. }else
  3463. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
  3464. static const uint8_t start_code[] = {0x00, 0x00, 0x01};
  3465. ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
  3466. ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
  3467. }else
  3468. context_count++;
  3469. }
  3470. break;
  3471. case NAL_DPA:
  3472. init_get_bits(&hx->s.gb, ptr, bit_length);
  3473. hx->intra_gb_ptr=
  3474. hx->inter_gb_ptr= NULL;
  3475. if ((err = decode_slice_header(hx, h)) < 0)
  3476. break;
  3477. hx->s.data_partitioning = 1;
  3478. break;
  3479. case NAL_DPB:
  3480. init_get_bits(&hx->intra_gb, ptr, bit_length);
  3481. hx->intra_gb_ptr= &hx->intra_gb;
  3482. break;
  3483. case NAL_DPC:
  3484. init_get_bits(&hx->inter_gb, ptr, bit_length);
  3485. hx->inter_gb_ptr= &hx->inter_gb;
  3486. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  3487. && s->context_initialized
  3488. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  3489. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=AV_PICTURE_TYPE_B)
  3490. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==AV_PICTURE_TYPE_I)
  3491. && avctx->skip_frame < AVDISCARD_ALL)
  3492. context_count++;
  3493. break;
  3494. case NAL_SEI:
  3495. init_get_bits(&s->gb, ptr, bit_length);
  3496. ff_h264_decode_sei(h);
  3497. break;
  3498. case NAL_SPS:
  3499. init_get_bits(&s->gb, ptr, bit_length);
  3500. if(ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)){
  3501. av_log(h->s.avctx, AV_LOG_DEBUG, "SPS decoding failure, trying alternative mode\n");
  3502. if(h->is_avc) av_assert0(next_avc - buf_index + consumed == nalsize);
  3503. init_get_bits(&s->gb, &buf[buf_index + 1 - consumed], 8*(next_avc - buf_index + consumed));
  3504. ff_h264_decode_seq_parameter_set(h);
  3505. }
  3506. if (s->flags& CODEC_FLAG_LOW_DELAY ||
  3507. (h->sps.bitstream_restriction_flag && !h->sps.num_reorder_frames))
  3508. s->low_delay=1;
  3509. if(avctx->has_b_frames < 2)
  3510. avctx->has_b_frames= !s->low_delay;
  3511. break;
  3512. case NAL_PPS:
  3513. init_get_bits(&s->gb, ptr, bit_length);
  3514. ff_h264_decode_picture_parameter_set(h, bit_length);
  3515. break;
  3516. case NAL_AUD:
  3517. case NAL_END_SEQUENCE:
  3518. case NAL_END_STREAM:
  3519. case NAL_FILLER_DATA:
  3520. case NAL_SPS_EXT:
  3521. case NAL_AUXILIARY_SLICE:
  3522. break;
  3523. default:
  3524. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
  3525. }
  3526. if(context_count == h->max_contexts) {
  3527. execute_decode_slices(h, context_count);
  3528. context_count = 0;
  3529. }
  3530. if (err < 0)
  3531. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  3532. else if(err == 1) {
  3533. /* Slice could not be decoded in parallel mode, copy down
  3534. * NAL unit stuff to context 0 and restart. Note that
  3535. * rbsp_buffer is not transferred, but since we no longer
  3536. * run in parallel mode this should not be an issue. */
  3537. h->nal_unit_type = hx->nal_unit_type;
  3538. h->nal_ref_idc = hx->nal_ref_idc;
  3539. hx = h;
  3540. goto again;
  3541. }
  3542. }
  3543. }
  3544. if(context_count)
  3545. execute_decode_slices(h, context_count);
  3546. return buf_index;
  3547. }
  3548. /**
  3549. * Return the number of bytes consumed for building the current frame.
  3550. */
  3551. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  3552. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  3553. if(pos+10>buf_size) pos=buf_size; // oops ;)
  3554. return pos;
  3555. }
  3556. static int decode_frame(AVCodecContext *avctx,
  3557. void *data, int *data_size,
  3558. AVPacket *avpkt)
  3559. {
  3560. const uint8_t *buf = avpkt->data;
  3561. int buf_size = avpkt->size;
  3562. H264Context *h = avctx->priv_data;
  3563. MpegEncContext *s = &h->s;
  3564. AVFrame *pict = data;
  3565. int buf_index = 0;
  3566. Picture *out;
  3567. int i, out_idx;
  3568. s->flags= avctx->flags;
  3569. s->flags2= avctx->flags2;
  3570. /* end of stream, output what is still in the buffers */
  3571. if (buf_size == 0) {
  3572. out:
  3573. s->current_picture_ptr = NULL;
  3574. //FIXME factorize this with the output code below
  3575. out = h->delayed_pic[0];
  3576. out_idx = 0;
  3577. for (i = 1; h->delayed_pic[i] && !h->delayed_pic[i]->f.key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  3578. if(h->delayed_pic[i]->poc < out->poc){
  3579. out = h->delayed_pic[i];
  3580. out_idx = i;
  3581. }
  3582. for(i=out_idx; h->delayed_pic[i]; i++)
  3583. h->delayed_pic[i] = h->delayed_pic[i+1];
  3584. if(out){
  3585. *data_size = sizeof(AVFrame);
  3586. *pict= *(AVFrame*)out;
  3587. }
  3588. return buf_index;
  3589. }
  3590. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  3591. int cnt= buf[5]&0x1f;
  3592. uint8_t *p= buf+6;
  3593. while(cnt--){
  3594. int nalsize= AV_RB16(p) + 2;
  3595. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  3596. goto not_extra;
  3597. p += nalsize;
  3598. }
  3599. cnt = *(p++);
  3600. if(!cnt)
  3601. goto not_extra;
  3602. while(cnt--){
  3603. int nalsize= AV_RB16(p) + 2;
  3604. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  3605. goto not_extra;
  3606. p += nalsize;
  3607. }
  3608. return ff_h264_decode_extradata(h, buf, buf_size);
  3609. }
  3610. not_extra:
  3611. buf_index=decode_nal_units(h, buf, buf_size);
  3612. if(buf_index < 0)
  3613. return -1;
  3614. if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  3615. av_assert0(buf_index <= buf_size);
  3616. goto out;
  3617. }
  3618. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  3619. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  3620. buf_size >= 4 && !memcmp("Q264", buf, 4))
  3621. return buf_size;
  3622. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3623. return -1;
  3624. }
  3625. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  3626. if(s->flags2 & CODEC_FLAG2_CHUNKS) decode_postinit(h, 1);
  3627. field_end(h, 0);
  3628. *data_size = 0; /* Wait for second field. */
  3629. if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
  3630. *data_size = sizeof(AVFrame);
  3631. *pict = *(AVFrame*)h->next_output_pic;
  3632. }
  3633. }
  3634. assert(pict->data[0] || !*data_size);
  3635. ff_print_debug_info(s, pict);
  3636. //printf("out %d\n", (int)pict->data[0]);
  3637. return get_consumed_bytes(s, buf_index, buf_size);
  3638. }
  3639. #if 0
  3640. static inline void fill_mb_avail(H264Context *h){
  3641. MpegEncContext * const s = &h->s;
  3642. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  3643. if(s->mb_y){
  3644. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  3645. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  3646. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  3647. }else{
  3648. h->mb_avail[0]=
  3649. h->mb_avail[1]=
  3650. h->mb_avail[2]= 0;
  3651. }
  3652. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  3653. h->mb_avail[4]= 1; //FIXME move out
  3654. h->mb_avail[5]= 0; //FIXME move out
  3655. }
  3656. #endif
  3657. #ifdef TEST
  3658. #undef printf
  3659. #undef random
  3660. #define COUNT 8000
  3661. #define SIZE (COUNT*40)
  3662. extern AVCodec ff_h264_decoder;
  3663. int main(void){
  3664. int i;
  3665. uint8_t temp[SIZE];
  3666. PutBitContext pb;
  3667. GetBitContext gb;
  3668. DSPContext dsp;
  3669. AVCodecContext avctx;
  3670. avcodec_get_context_defaults3(&avctx, &ff_h264_decoder);
  3671. dsputil_init(&dsp, &avctx);
  3672. init_put_bits(&pb, temp, SIZE);
  3673. printf("testing unsigned exp golomb\n");
  3674. for(i=0; i<COUNT; i++){
  3675. START_TIMER
  3676. set_ue_golomb(&pb, i);
  3677. STOP_TIMER("set_ue_golomb");
  3678. }
  3679. flush_put_bits(&pb);
  3680. init_get_bits(&gb, temp, 8*SIZE);
  3681. for(i=0; i<COUNT; i++){
  3682. int j, s = show_bits(&gb, 24);
  3683. {START_TIMER
  3684. j= get_ue_golomb(&gb);
  3685. if(j != i){
  3686. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  3687. // return -1;
  3688. }
  3689. STOP_TIMER("get_ue_golomb");}
  3690. }
  3691. init_put_bits(&pb, temp, SIZE);
  3692. printf("testing signed exp golomb\n");
  3693. for(i=0; i<COUNT; i++){
  3694. START_TIMER
  3695. set_se_golomb(&pb, i - COUNT/2);
  3696. STOP_TIMER("set_se_golomb");
  3697. }
  3698. flush_put_bits(&pb);
  3699. init_get_bits(&gb, temp, 8*SIZE);
  3700. for(i=0; i<COUNT; i++){
  3701. int j, s = show_bits(&gb, 24);
  3702. {START_TIMER
  3703. j= get_se_golomb(&gb);
  3704. if(j != i - COUNT/2){
  3705. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  3706. // return -1;
  3707. }
  3708. STOP_TIMER("get_se_golomb");}
  3709. }
  3710. printf("Testing RBSP\n");
  3711. return 0;
  3712. }
  3713. #endif /* TEST */
  3714. av_cold void ff_h264_free_context(H264Context *h)
  3715. {
  3716. int i;
  3717. free_tables(h, 1); //FIXME cleanup init stuff perhaps
  3718. for(i = 0; i < MAX_SPS_COUNT; i++)
  3719. av_freep(h->sps_buffers + i);
  3720. for(i = 0; i < MAX_PPS_COUNT; i++)
  3721. av_freep(h->pps_buffers + i);
  3722. }
  3723. av_cold int ff_h264_decode_end(AVCodecContext *avctx)
  3724. {
  3725. H264Context *h = avctx->priv_data;
  3726. MpegEncContext *s = &h->s;
  3727. ff_h264_remove_all_refs(h);
  3728. ff_h264_free_context(h);
  3729. MPV_common_end(s);
  3730. // memset(h, 0, sizeof(H264Context));
  3731. return 0;
  3732. }
  3733. static const AVProfile profiles[] = {
  3734. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3735. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3736. { FF_PROFILE_H264_MAIN, "Main" },
  3737. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3738. { FF_PROFILE_H264_HIGH, "High" },
  3739. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3740. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3741. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3742. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3743. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3744. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3745. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3746. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3747. { FF_PROFILE_UNKNOWN },
  3748. };
  3749. static const AVOption h264_options[] = {
  3750. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 1, 0},
  3751. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.dbl = 0}, 0, 4, 0},
  3752. {NULL}
  3753. };
  3754. static const AVClass h264_class = {
  3755. "H264 Decoder",
  3756. av_default_item_name,
  3757. h264_options,
  3758. LIBAVUTIL_VERSION_INT,
  3759. };
  3760. static const AVClass h264_vdpau_class = {
  3761. "H264 VDPAU Decoder",
  3762. av_default_item_name,
  3763. h264_options,
  3764. LIBAVUTIL_VERSION_INT,
  3765. };
  3766. AVCodec ff_h264_decoder = {
  3767. .name = "h264",
  3768. .type = AVMEDIA_TYPE_VIDEO,
  3769. .id = CODEC_ID_H264,
  3770. .priv_data_size = sizeof(H264Context),
  3771. .init = ff_h264_decode_init,
  3772. .close = ff_h264_decode_end,
  3773. .decode = decode_frame,
  3774. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY |
  3775. CODEC_CAP_SLICE_THREADS | CODEC_CAP_FRAME_THREADS,
  3776. .flush= flush_dpb,
  3777. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  3778. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  3779. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  3780. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3781. .priv_class = &h264_class,
  3782. };
  3783. #if CONFIG_H264_VDPAU_DECODER
  3784. AVCodec ff_h264_vdpau_decoder = {
  3785. .name = "h264_vdpau",
  3786. .type = AVMEDIA_TYPE_VIDEO,
  3787. .id = CODEC_ID_H264,
  3788. .priv_data_size = sizeof(H264Context),
  3789. .init = ff_h264_decode_init,
  3790. .close = ff_h264_decode_end,
  3791. .decode = decode_frame,
  3792. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  3793. .flush= flush_dpb,
  3794. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  3795. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
  3796. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3797. .priv_class = &h264_vdpau_class,
  3798. };
  3799. #endif