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.

3416 lines
126KB

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