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.

3413 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. * Replicates 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->color_range == AVCOL_RANGE_JPEG ?
  1623. hwaccel_pixfmt_list_h264_jpeg_420 :
  1624. ff_hwaccel_pixfmt_list_420);
  1625. s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
  1626. if (MPV_common_init(s) < 0)
  1627. return -1;
  1628. s->first_field = 0;
  1629. h->prev_interlaced_frame = 1;
  1630. init_scan_tables(h);
  1631. ff_h264_alloc_tables(h);
  1632. for(i = 1; i < s->avctx->thread_count; i++) {
  1633. H264Context *c;
  1634. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  1635. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  1636. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  1637. c->h264dsp = h->h264dsp;
  1638. c->sps = h->sps;
  1639. c->pps = h->pps;
  1640. init_scan_tables(c);
  1641. clone_tables(c, h, i);
  1642. }
  1643. for(i = 0; i < s->avctx->thread_count; i++)
  1644. if(context_init(h->thread_context[i]) < 0)
  1645. return -1;
  1646. }
  1647. h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);
  1648. h->mb_mbaff = 0;
  1649. h->mb_aff_frame = 0;
  1650. last_pic_structure = s0->picture_structure;
  1651. if(h->sps.frame_mbs_only_flag){
  1652. s->picture_structure= PICT_FRAME;
  1653. }else{
  1654. if(get_bits1(&s->gb)) { //field_pic_flag
  1655. s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag
  1656. } else {
  1657. s->picture_structure= PICT_FRAME;
  1658. h->mb_aff_frame = h->sps.mb_aff;
  1659. }
  1660. }
  1661. h->mb_field_decoding_flag= s->picture_structure != PICT_FRAME;
  1662. if(h0->current_slice == 0){
  1663. while(h->frame_num != h->prev_frame_num &&
  1664. h->frame_num != (h->prev_frame_num+1)%(1<<h->sps.log2_max_frame_num)){
  1665. av_log(NULL, AV_LOG_DEBUG, "Frame num gap %d %d\n", h->frame_num, h->prev_frame_num);
  1666. if (ff_h264_frame_start(h) < 0)
  1667. return -1;
  1668. h->prev_frame_num++;
  1669. h->prev_frame_num %= 1<<h->sps.log2_max_frame_num;
  1670. s->current_picture_ptr->frame_num= h->prev_frame_num;
  1671. ff_h264_execute_ref_pic_marking(h, NULL, 0);
  1672. }
  1673. /* See if we have a decoded first field looking for a pair... */
  1674. if (s0->first_field) {
  1675. assert(s0->current_picture_ptr);
  1676. assert(s0->current_picture_ptr->data[0]);
  1677. assert(s0->current_picture_ptr->reference != DELAYED_PIC_REF);
  1678. /* figure out if we have a complementary field pair */
  1679. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  1680. /*
  1681. * Previous field is unmatched. Don't display it, but let it
  1682. * remain for reference if marked as such.
  1683. */
  1684. s0->current_picture_ptr = NULL;
  1685. s0->first_field = FIELD_PICTURE;
  1686. } else {
  1687. if (h->nal_ref_idc &&
  1688. s0->current_picture_ptr->reference &&
  1689. s0->current_picture_ptr->frame_num != h->frame_num) {
  1690. /*
  1691. * This and previous field were reference, but had
  1692. * different frame_nums. Consider this field first in
  1693. * pair. Throw away previous field except for reference
  1694. * purposes.
  1695. */
  1696. s0->first_field = 1;
  1697. s0->current_picture_ptr = NULL;
  1698. } else {
  1699. /* Second field in complementary pair */
  1700. s0->first_field = 0;
  1701. }
  1702. }
  1703. } else {
  1704. /* Frame or first field in a potentially complementary pair */
  1705. assert(!s0->current_picture_ptr);
  1706. s0->first_field = FIELD_PICTURE;
  1707. }
  1708. if((!FIELD_PICTURE || s0->first_field) && ff_h264_frame_start(h) < 0) {
  1709. s0->first_field = 0;
  1710. return -1;
  1711. }
  1712. }
  1713. if(h != h0)
  1714. clone_slice(h, h0);
  1715. s->current_picture_ptr->frame_num= h->frame_num; //FIXME frame_num cleanup
  1716. assert(s->mb_num == s->mb_width * s->mb_height);
  1717. if(first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  1718. first_mb_in_slice >= s->mb_num){
  1719. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  1720. return -1;
  1721. }
  1722. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  1723. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  1724. if (s->picture_structure == PICT_BOTTOM_FIELD)
  1725. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  1726. assert(s->mb_y < s->mb_height);
  1727. if(s->picture_structure==PICT_FRAME){
  1728. h->curr_pic_num= h->frame_num;
  1729. h->max_pic_num= 1<< h->sps.log2_max_frame_num;
  1730. }else{
  1731. h->curr_pic_num= 2*h->frame_num + 1;
  1732. h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);
  1733. }
  1734. if(h->nal_unit_type == NAL_IDR_SLICE){
  1735. get_ue_golomb(&s->gb); /* idr_pic_id */
  1736. }
  1737. if(h->sps.poc_type==0){
  1738. h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  1739. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){
  1740. h->delta_poc_bottom= get_se_golomb(&s->gb);
  1741. }
  1742. }
  1743. if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){
  1744. h->delta_poc[0]= get_se_golomb(&s->gb);
  1745. if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)
  1746. h->delta_poc[1]= get_se_golomb(&s->gb);
  1747. }
  1748. init_poc(h);
  1749. if(h->pps.redundant_pic_cnt_present){
  1750. h->redundant_pic_count= get_ue_golomb(&s->gb);
  1751. }
  1752. //set defaults, might be overridden a few lines later
  1753. h->ref_count[0]= h->pps.ref_count[0];
  1754. h->ref_count[1]= h->pps.ref_count[1];
  1755. if(h->slice_type_nos != FF_I_TYPE){
  1756. if(h->slice_type_nos == FF_B_TYPE){
  1757. h->direct_spatial_mv_pred= get_bits1(&s->gb);
  1758. }
  1759. num_ref_idx_active_override_flag= get_bits1(&s->gb);
  1760. if(num_ref_idx_active_override_flag){
  1761. h->ref_count[0]= get_ue_golomb(&s->gb) + 1;
  1762. if(h->slice_type_nos==FF_B_TYPE)
  1763. h->ref_count[1]= get_ue_golomb(&s->gb) + 1;
  1764. if(h->ref_count[0]-1 > 32-1 || h->ref_count[1]-1 > 32-1){
  1765. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");
  1766. h->ref_count[0]= h->ref_count[1]= 1;
  1767. return -1;
  1768. }
  1769. }
  1770. if(h->slice_type_nos == FF_B_TYPE)
  1771. h->list_count= 2;
  1772. else
  1773. h->list_count= 1;
  1774. }else
  1775. h->list_count= 0;
  1776. if(!default_ref_list_done){
  1777. ff_h264_fill_default_ref_list(h);
  1778. }
  1779. if(h->slice_type_nos!=FF_I_TYPE && ff_h264_decode_ref_pic_list_reordering(h) < 0)
  1780. return -1;
  1781. if(h->slice_type_nos!=FF_I_TYPE){
  1782. s->last_picture_ptr= &h->ref_list[0][0];
  1783. ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  1784. }
  1785. if(h->slice_type_nos==FF_B_TYPE){
  1786. s->next_picture_ptr= &h->ref_list[1][0];
  1787. ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  1788. }
  1789. if( (h->pps.weighted_pred && h->slice_type_nos == FF_P_TYPE )
  1790. || (h->pps.weighted_bipred_idc==1 && h->slice_type_nos== FF_B_TYPE ) )
  1791. pred_weight_table(h);
  1792. else if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
  1793. implicit_weight_table(h, -1);
  1794. }else {
  1795. h->use_weight = 0;
  1796. for (i = 0; i < 2; i++) {
  1797. h->luma_weight_flag[i] = 0;
  1798. h->chroma_weight_flag[i] = 0;
  1799. }
  1800. }
  1801. if(h->nal_ref_idc)
  1802. ff_h264_decode_ref_pic_marking(h0, &s->gb);
  1803. if(FRAME_MBAFF){
  1804. ff_h264_fill_mbaff_ref_list(h);
  1805. if(h->pps.weighted_bipred_idc==2 && h->slice_type_nos== FF_B_TYPE){
  1806. implicit_weight_table(h, 0);
  1807. implicit_weight_table(h, 1);
  1808. }
  1809. }
  1810. if(h->slice_type_nos==FF_B_TYPE && !h->direct_spatial_mv_pred)
  1811. ff_h264_direct_dist_scale_factor(h);
  1812. ff_h264_direct_ref_list_init(h);
  1813. if( h->slice_type_nos != FF_I_TYPE && h->pps.cabac ){
  1814. tmp = get_ue_golomb_31(&s->gb);
  1815. if(tmp > 2){
  1816. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  1817. return -1;
  1818. }
  1819. h->cabac_init_idc= tmp;
  1820. }
  1821. h->last_qscale_diff = 0;
  1822. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  1823. if(tmp>51){
  1824. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  1825. return -1;
  1826. }
  1827. s->qscale= tmp;
  1828. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  1829. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  1830. //FIXME qscale / qp ... stuff
  1831. if(h->slice_type == FF_SP_TYPE){
  1832. get_bits1(&s->gb); /* sp_for_switch_flag */
  1833. }
  1834. if(h->slice_type==FF_SP_TYPE || h->slice_type == FF_SI_TYPE){
  1835. get_se_golomb(&s->gb); /* slice_qs_delta */
  1836. }
  1837. h->deblocking_filter = 1;
  1838. h->slice_alpha_c0_offset = 52;
  1839. h->slice_beta_offset = 52;
  1840. if( h->pps.deblocking_filter_parameters_present ) {
  1841. tmp= get_ue_golomb_31(&s->gb);
  1842. if(tmp > 2){
  1843. av_log(s->avctx, AV_LOG_ERROR, "deblocking_filter_idc %u out of range\n", tmp);
  1844. return -1;
  1845. }
  1846. h->deblocking_filter= tmp;
  1847. if(h->deblocking_filter < 2)
  1848. h->deblocking_filter^= 1; // 1<->0
  1849. if( h->deblocking_filter ) {
  1850. h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
  1851. h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
  1852. if( h->slice_alpha_c0_offset > 104U
  1853. || h->slice_beta_offset > 104U){
  1854. 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);
  1855. return -1;
  1856. }
  1857. }
  1858. }
  1859. if( s->avctx->skip_loop_filter >= AVDISCARD_ALL
  1860. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != FF_I_TYPE)
  1861. ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == FF_B_TYPE)
  1862. ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  1863. h->deblocking_filter= 0;
  1864. if(h->deblocking_filter == 1 && h0->max_contexts > 1) {
  1865. if(s->avctx->flags2 & CODEC_FLAG2_FAST) {
  1866. /* Cheat slightly for speed:
  1867. Do not bother to deblock across slices. */
  1868. h->deblocking_filter = 2;
  1869. } else {
  1870. h0->max_contexts = 1;
  1871. if(!h0->single_decode_warning) {
  1872. av_log(s->avctx, AV_LOG_INFO, "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  1873. h0->single_decode_warning = 1;
  1874. }
  1875. if(h != h0)
  1876. return 1; // deblocking switched inside frame
  1877. }
  1878. }
  1879. 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]);
  1880. #if 0 //FMO
  1881. if( h->pps.num_slice_groups > 1 && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)
  1882. slice_group_change_cycle= get_bits(&s->gb, ?);
  1883. #endif
  1884. h0->last_slice_type = slice_type;
  1885. h->slice_num = ++h0->current_slice;
  1886. if(h->slice_num >= MAX_SLICES){
  1887. av_log(s->avctx, AV_LOG_ERROR, "Too many slices, increase MAX_SLICES and recompile\n");
  1888. }
  1889. for(j=0; j<2; j++){
  1890. int id_list[16];
  1891. int *ref2frm= h->ref2frm[h->slice_num&(MAX_SLICES-1)][j];
  1892. for(i=0; i<16; i++){
  1893. id_list[i]= 60;
  1894. if(h->ref_list[j][i].data[0]){
  1895. int k;
  1896. uint8_t *base= h->ref_list[j][i].base[0];
  1897. for(k=0; k<h->short_ref_count; k++)
  1898. if(h->short_ref[k]->base[0] == base){
  1899. id_list[i]= k;
  1900. break;
  1901. }
  1902. for(k=0; k<h->long_ref_count; k++)
  1903. if(h->long_ref[k] && h->long_ref[k]->base[0] == base){
  1904. id_list[i]= h->short_ref_count + k;
  1905. break;
  1906. }
  1907. }
  1908. }
  1909. ref2frm[0]=
  1910. ref2frm[1]= -1;
  1911. for(i=0; i<16; i++)
  1912. ref2frm[i+2]= 4*id_list[i]
  1913. +(h->ref_list[j][i].reference&3);
  1914. ref2frm[18+0]=
  1915. ref2frm[18+1]= -1;
  1916. for(i=16; i<48; i++)
  1917. ref2frm[i+4]= 4*id_list[(i-16)>>1]
  1918. +(h->ref_list[j][i].reference&3);
  1919. }
  1920. h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;
  1921. h->emu_edge_height= (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  1922. if(s->avctx->debug&FF_DEBUG_PICT_INFO){
  1923. 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",
  1924. h->slice_num,
  1925. (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),
  1926. first_mb_in_slice,
  1927. av_get_pict_type_char(h->slice_type), h->slice_type_fixed ? " fix" : "", h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  1928. pps_id, h->frame_num,
  1929. s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],
  1930. h->ref_count[0], h->ref_count[1],
  1931. s->qscale,
  1932. h->deblocking_filter, h->slice_alpha_c0_offset/2-26, h->slice_beta_offset/2-26,
  1933. h->use_weight,
  1934. h->use_weight==1 && h->use_weight_chroma ? "c" : "",
  1935. h->slice_type == FF_B_TYPE ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : ""
  1936. );
  1937. }
  1938. return 0;
  1939. }
  1940. int ff_h264_get_slice_type(const H264Context *h)
  1941. {
  1942. switch (h->slice_type) {
  1943. case FF_P_TYPE: return 0;
  1944. case FF_B_TYPE: return 1;
  1945. case FF_I_TYPE: return 2;
  1946. case FF_SP_TYPE: return 3;
  1947. case FF_SI_TYPE: return 4;
  1948. default: return -1;
  1949. }
  1950. }
  1951. /**
  1952. *
  1953. * @return non zero if the loop filter can be skiped
  1954. */
  1955. static int fill_filter_caches(H264Context *h, int mb_type){
  1956. MpegEncContext * const s = &h->s;
  1957. const int mb_xy= h->mb_xy;
  1958. int top_xy, left_xy[2];
  1959. int top_type, left_type[2];
  1960. top_xy = mb_xy - (s->mb_stride << MB_FIELD);
  1961. //FIXME deblocking could skip the intra and nnz parts.
  1962. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  1963. * stuff, I can't imagine that these complex rules are worth it. */
  1964. left_xy[1] = left_xy[0] = mb_xy-1;
  1965. if(FRAME_MBAFF){
  1966. const int left_mb_field_flag = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);
  1967. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  1968. if(s->mb_y&1){
  1969. if (left_mb_field_flag != curr_mb_field_flag) {
  1970. left_xy[0] -= s->mb_stride;
  1971. }
  1972. }else{
  1973. if(curr_mb_field_flag){
  1974. top_xy += s->mb_stride & (((s->current_picture.mb_type[top_xy ]>>7)&1)-1);
  1975. }
  1976. if (left_mb_field_flag != curr_mb_field_flag) {
  1977. left_xy[1] += s->mb_stride;
  1978. }
  1979. }
  1980. }
  1981. h->top_mb_xy = top_xy;
  1982. h->left_mb_xy[0] = left_xy[0];
  1983. h->left_mb_xy[1] = left_xy[1];
  1984. {
  1985. //for sufficiently low qp, filtering wouldn't do anything
  1986. //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp
  1987. int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice
  1988. int qp = s->current_picture.qscale_table[mb_xy];
  1989. if(qp <= qp_thresh
  1990. && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)
  1991. && (top_xy < 0 || ((qp + s->current_picture.qscale_table[top_xy ] + 1)>>1) <= qp_thresh)){
  1992. if(!FRAME_MBAFF)
  1993. return 1;
  1994. if( (left_xy[0]< 0 || ((qp + s->current_picture.qscale_table[left_xy[1] ] + 1)>>1) <= qp_thresh)
  1995. && (top_xy < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy -s->mb_stride] + 1)>>1) <= qp_thresh))
  1996. return 1;
  1997. }
  1998. }
  1999. top_type = s->current_picture.mb_type[top_xy] ;
  2000. left_type[0] = s->current_picture.mb_type[left_xy[0]];
  2001. left_type[1] = s->current_picture.mb_type[left_xy[1]];
  2002. if(h->deblocking_filter == 2){
  2003. if(h->slice_table[top_xy ] != h->slice_num) top_type= 0;
  2004. if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;
  2005. }else{
  2006. if(h->slice_table[top_xy ] == 0xFFFF) top_type= 0;
  2007. if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;
  2008. }
  2009. h->top_type = top_type ;
  2010. h->left_type[0]= left_type[0];
  2011. h->left_type[1]= left_type[1];
  2012. if(IS_INTRA(mb_type))
  2013. return 0;
  2014. AV_COPY64(&h->non_zero_count_cache[0+8*1], &h->non_zero_count[mb_xy][ 0]);
  2015. AV_COPY64(&h->non_zero_count_cache[0+8*2], &h->non_zero_count[mb_xy][ 8]);
  2016. AV_COPY32(&h->non_zero_count_cache[0+8*5], &h->non_zero_count[mb_xy][16]);
  2017. AV_COPY32(&h->non_zero_count_cache[4+8*3], &h->non_zero_count[mb_xy][20]);
  2018. AV_COPY64(&h->non_zero_count_cache[0+8*4], &h->non_zero_count[mb_xy][24]);
  2019. h->cbp= h->cbp_table[mb_xy];
  2020. {
  2021. int list;
  2022. for(list=0; list<h->list_count; list++){
  2023. int8_t *ref;
  2024. int y, b_stride;
  2025. int16_t (*mv_dst)[2];
  2026. int16_t (*mv_src)[2];
  2027. if(!USES_LIST(mb_type, list)){
  2028. fill_rectangle( h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);
  2029. AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2030. AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2031. AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2032. AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2033. continue;
  2034. }
  2035. ref = &s->current_picture.ref_index[list][4*mb_xy];
  2036. {
  2037. int (*ref2frm)[64] = h->ref2frm[ h->slice_num&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2038. AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2039. AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2040. ref += 2;
  2041. AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2042. AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);
  2043. }
  2044. b_stride = h->b_stride;
  2045. mv_dst = &h->mv_cache[list][scan8[0]];
  2046. mv_src = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];
  2047. for(y=0; y<4; y++){
  2048. AV_COPY128(mv_dst + 8*y, mv_src + y*b_stride);
  2049. }
  2050. }
  2051. }
  2052. /*
  2053. 0 . T T. T T T T
  2054. 1 L . .L . . . .
  2055. 2 L . .L . . . .
  2056. 3 . T TL . . . .
  2057. 4 L . .L . . . .
  2058. 5 L . .. . . . .
  2059. */
  2060. //FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)
  2061. if(top_type){
  2062. AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][4+3*8]);
  2063. }
  2064. if(left_type[0]){
  2065. h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][7+0*8];
  2066. h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][7+1*8];
  2067. h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][7+2*8];
  2068. h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][7+3*8];
  2069. }
  2070. // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs
  2071. if(!CABAC && h->pps.transform_8x8_mode){
  2072. if(IS_8x8DCT(top_type)){
  2073. h->non_zero_count_cache[4+8*0]=
  2074. h->non_zero_count_cache[5+8*0]= h->cbp_table[top_xy] & 4;
  2075. h->non_zero_count_cache[6+8*0]=
  2076. h->non_zero_count_cache[7+8*0]= h->cbp_table[top_xy] & 8;
  2077. }
  2078. if(IS_8x8DCT(left_type[0])){
  2079. h->non_zero_count_cache[3+8*1]=
  2080. h->non_zero_count_cache[3+8*2]= h->cbp_table[left_xy[0]]&2; //FIXME check MBAFF
  2081. }
  2082. if(IS_8x8DCT(left_type[1])){
  2083. h->non_zero_count_cache[3+8*3]=
  2084. h->non_zero_count_cache[3+8*4]= h->cbp_table[left_xy[1]]&8; //FIXME check MBAFF
  2085. }
  2086. if(IS_8x8DCT(mb_type)){
  2087. h->non_zero_count_cache[scan8[0 ]]= h->non_zero_count_cache[scan8[1 ]]=
  2088. h->non_zero_count_cache[scan8[2 ]]= h->non_zero_count_cache[scan8[3 ]]= h->cbp & 1;
  2089. h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=
  2090. h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= h->cbp & 2;
  2091. h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=
  2092. h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= h->cbp & 4;
  2093. h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=
  2094. h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= h->cbp & 8;
  2095. }
  2096. }
  2097. if(IS_INTER(mb_type) || IS_DIRECT(mb_type)){
  2098. int list;
  2099. for(list=0; list<h->list_count; list++){
  2100. if(USES_LIST(top_type, list)){
  2101. const int b_xy= h->mb2b_xy[top_xy] + 3*h->b_stride;
  2102. const int b8_xy= 4*top_xy + 2;
  2103. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[top_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2104. AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);
  2105. h->ref_cache[list][scan8[0] + 0 - 1*8]=
  2106. h->ref_cache[list][scan8[0] + 1 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 0]];
  2107. h->ref_cache[list][scan8[0] + 2 - 1*8]=
  2108. h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];
  2109. }else{
  2110. AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);
  2111. AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);
  2112. }
  2113. if(!IS_INTERLACED(mb_type^left_type[0])){
  2114. if(USES_LIST(left_type[0], list)){
  2115. const int b_xy= h->mb2b_xy[left_xy[0]] + 3;
  2116. const int b8_xy= 4*left_xy[0] + 1;
  2117. int (*ref2frm)[64] = h->ref2frm[ h->slice_table[left_xy[0]]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);
  2118. AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);
  2119. AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);
  2120. AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);
  2121. AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);
  2122. h->ref_cache[list][scan8[0] - 1 + 0 ]=
  2123. h->ref_cache[list][scan8[0] - 1 + 8 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*0]];
  2124. h->ref_cache[list][scan8[0] - 1 +16 ]=
  2125. h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];
  2126. }else{
  2127. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);
  2128. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);
  2129. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);
  2130. AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);
  2131. h->ref_cache[list][scan8[0] - 1 + 0 ]=
  2132. h->ref_cache[list][scan8[0] - 1 + 8 ]=
  2133. h->ref_cache[list][scan8[0] - 1 + 16 ]=
  2134. h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;
  2135. }
  2136. }
  2137. }
  2138. }
  2139. return 0;
  2140. }
  2141. static void loop_filter(H264Context *h){
  2142. MpegEncContext * const s = &h->s;
  2143. uint8_t *dest_y, *dest_cb, *dest_cr;
  2144. int linesize, uvlinesize, mb_x, mb_y;
  2145. const int end_mb_y= s->mb_y + FRAME_MBAFF;
  2146. const int old_slice_type= h->slice_type;
  2147. if(h->deblocking_filter) {
  2148. for(mb_x= 0; mb_x<s->mb_width; mb_x++){
  2149. for(mb_y=end_mb_y - FRAME_MBAFF; mb_y<= end_mb_y; mb_y++){
  2150. int mb_xy, mb_type;
  2151. mb_xy = h->mb_xy = mb_x + mb_y*s->mb_stride;
  2152. h->slice_num= h->slice_table[mb_xy];
  2153. mb_type= s->current_picture.mb_type[mb_xy];
  2154. h->list_count= h->list_counts[mb_xy];
  2155. if(FRAME_MBAFF)
  2156. h->mb_mbaff = h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  2157. s->mb_x= mb_x;
  2158. s->mb_y= mb_y;
  2159. dest_y = s->current_picture.data[0] + (mb_x + mb_y * s->linesize ) * 16;
  2160. dest_cb = s->current_picture.data[1] + (mb_x + mb_y * s->uvlinesize) * 8;
  2161. dest_cr = s->current_picture.data[2] + (mb_x + mb_y * s->uvlinesize) * 8;
  2162. //FIXME simplify above
  2163. if (MB_FIELD) {
  2164. linesize = h->mb_linesize = s->linesize * 2;
  2165. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  2166. if(mb_y&1){ //FIXME move out of this function?
  2167. dest_y -= s->linesize*15;
  2168. dest_cb-= s->uvlinesize*7;
  2169. dest_cr-= s->uvlinesize*7;
  2170. }
  2171. } else {
  2172. linesize = h->mb_linesize = s->linesize;
  2173. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  2174. }
  2175. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize, uvlinesize, 0);
  2176. if(fill_filter_caches(h, mb_type))
  2177. continue;
  2178. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.qscale_table[mb_xy]);
  2179. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.qscale_table[mb_xy]);
  2180. if (FRAME_MBAFF) {
  2181. ff_h264_filter_mb (h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2182. } else {
  2183. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb, dest_cr, linesize, uvlinesize);
  2184. }
  2185. }
  2186. }
  2187. }
  2188. h->slice_type= old_slice_type;
  2189. s->mb_x= 0;
  2190. s->mb_y= end_mb_y - FRAME_MBAFF;
  2191. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2192. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2193. }
  2194. static void predict_field_decoding_flag(H264Context *h){
  2195. MpegEncContext * const s = &h->s;
  2196. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  2197. int mb_type = (h->slice_table[mb_xy-1] == h->slice_num)
  2198. ? s->current_picture.mb_type[mb_xy-1]
  2199. : (h->slice_table[mb_xy-s->mb_stride] == h->slice_num)
  2200. ? s->current_picture.mb_type[mb_xy-s->mb_stride]
  2201. : 0;
  2202. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  2203. }
  2204. static int decode_slice(struct AVCodecContext *avctx, void *arg){
  2205. H264Context *h = *(void**)arg;
  2206. MpegEncContext * const s = &h->s;
  2207. const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;
  2208. s->mb_skip_run= -1;
  2209. h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||
  2210. (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));
  2211. if( h->pps.cabac ) {
  2212. /* realign */
  2213. align_get_bits( &s->gb );
  2214. /* init cabac */
  2215. ff_init_cabac_states( &h->cabac);
  2216. ff_init_cabac_decoder( &h->cabac,
  2217. s->gb.buffer + get_bits_count(&s->gb)/8,
  2218. (get_bits_left(&s->gb) + 7)/8);
  2219. ff_h264_init_cabac_states(h);
  2220. for(;;){
  2221. //START_TIMER
  2222. int ret = ff_h264_decode_mb_cabac(h);
  2223. int eos;
  2224. //STOP_TIMER("decode_mb_cabac")
  2225. if(ret>=0) ff_h264_hl_decode_mb(h);
  2226. if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?
  2227. s->mb_y++;
  2228. ret = ff_h264_decode_mb_cabac(h);
  2229. if(ret>=0) ff_h264_hl_decode_mb(h);
  2230. s->mb_y--;
  2231. }
  2232. eos = get_cabac_terminate( &h->cabac );
  2233. if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){
  2234. 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);
  2235. return 0;
  2236. }
  2237. if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  2238. 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);
  2239. 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);
  2240. return -1;
  2241. }
  2242. if( ++s->mb_x >= s->mb_width ) {
  2243. s->mb_x = 0;
  2244. loop_filter(h);
  2245. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  2246. ++s->mb_y;
  2247. if(FIELD_OR_MBAFF_PICTURE) {
  2248. ++s->mb_y;
  2249. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  2250. predict_field_decoding_flag(h);
  2251. }
  2252. }
  2253. if( eos || s->mb_y >= s->mb_height ) {
  2254. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2255. 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);
  2256. return 0;
  2257. }
  2258. }
  2259. } else {
  2260. for(;;){
  2261. int ret = ff_h264_decode_mb_cavlc(h);
  2262. if(ret>=0) ff_h264_hl_decode_mb(h);
  2263. if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?
  2264. s->mb_y++;
  2265. ret = ff_h264_decode_mb_cavlc(h);
  2266. if(ret>=0) ff_h264_hl_decode_mb(h);
  2267. s->mb_y--;
  2268. }
  2269. if(ret<0){
  2270. av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  2271. 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);
  2272. return -1;
  2273. }
  2274. if(++s->mb_x >= s->mb_width){
  2275. s->mb_x=0;
  2276. loop_filter(h);
  2277. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  2278. ++s->mb_y;
  2279. if(FIELD_OR_MBAFF_PICTURE) {
  2280. ++s->mb_y;
  2281. if(FRAME_MBAFF && s->mb_y < s->mb_height)
  2282. predict_field_decoding_flag(h);
  2283. }
  2284. if(s->mb_y >= s->mb_height){
  2285. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2286. if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {
  2287. 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);
  2288. return 0;
  2289. }else{
  2290. 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);
  2291. return -1;
  2292. }
  2293. }
  2294. }
  2295. if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){
  2296. tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);
  2297. if(get_bits_count(&s->gb) == s->gb.size_in_bits ){
  2298. 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);
  2299. return 0;
  2300. }else{
  2301. 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);
  2302. return -1;
  2303. }
  2304. }
  2305. }
  2306. }
  2307. #if 0
  2308. for(;s->mb_y < s->mb_height; s->mb_y++){
  2309. for(;s->mb_x < s->mb_width; s->mb_x++){
  2310. int ret= decode_mb(h);
  2311. ff_h264_hl_decode_mb(h);
  2312. if(ret<0){
  2313. av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  2314. 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);
  2315. return -1;
  2316. }
  2317. if(++s->mb_x >= s->mb_width){
  2318. s->mb_x=0;
  2319. if(++s->mb_y >= s->mb_height){
  2320. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  2321. 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);
  2322. return 0;
  2323. }else{
  2324. 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);
  2325. return -1;
  2326. }
  2327. }
  2328. }
  2329. if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){
  2330. if(get_bits_count(s->gb) == s->gb.size_in_bits){
  2331. 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);
  2332. return 0;
  2333. }else{
  2334. 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);
  2335. return -1;
  2336. }
  2337. }
  2338. }
  2339. s->mb_x=0;
  2340. ff_draw_horiz_band(s, 16*s->mb_y, 16);
  2341. }
  2342. #endif
  2343. return -1; //not reached
  2344. }
  2345. /**
  2346. * Call decode_slice() for each context.
  2347. *
  2348. * @param h h264 master context
  2349. * @param context_count number of contexts to execute
  2350. */
  2351. static void execute_decode_slices(H264Context *h, int context_count){
  2352. MpegEncContext * const s = &h->s;
  2353. AVCodecContext * const avctx= s->avctx;
  2354. H264Context *hx;
  2355. int i;
  2356. if (s->avctx->hwaccel)
  2357. return;
  2358. if(s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2359. return;
  2360. if(context_count == 1) {
  2361. decode_slice(avctx, &h);
  2362. } else {
  2363. for(i = 1; i < context_count; i++) {
  2364. hx = h->thread_context[i];
  2365. hx->s.error_recognition = avctx->error_recognition;
  2366. hx->s.error_count = 0;
  2367. }
  2368. avctx->execute(avctx, (void *)decode_slice,
  2369. h->thread_context, NULL, context_count, sizeof(void*));
  2370. /* pull back stuff from slices to master context */
  2371. hx = h->thread_context[context_count - 1];
  2372. s->mb_x = hx->s.mb_x;
  2373. s->mb_y = hx->s.mb_y;
  2374. s->dropable = hx->s.dropable;
  2375. s->picture_structure = hx->s.picture_structure;
  2376. for(i = 1; i < context_count; i++)
  2377. h->s.error_count += h->thread_context[i]->s.error_count;
  2378. }
  2379. }
  2380. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size){
  2381. MpegEncContext * const s = &h->s;
  2382. AVCodecContext * const avctx= s->avctx;
  2383. int buf_index=0;
  2384. H264Context *hx; ///< thread context
  2385. int context_count = 0;
  2386. int next_avc= h->is_avc ? 0 : buf_size;
  2387. h->max_contexts = avctx->thread_count;
  2388. #if 0
  2389. int i;
  2390. for(i=0; i<50; i++){
  2391. av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);
  2392. }
  2393. #endif
  2394. if(!(s->flags2 & CODEC_FLAG2_CHUNKS)){
  2395. h->current_slice = 0;
  2396. if (!s->first_field)
  2397. s->current_picture_ptr= NULL;
  2398. ff_h264_reset_sei(h);
  2399. }
  2400. for(;;){
  2401. int consumed;
  2402. int dst_length;
  2403. int bit_length;
  2404. const uint8_t *ptr;
  2405. int i, nalsize = 0;
  2406. int err;
  2407. if(buf_index >= next_avc) {
  2408. if(buf_index >= buf_size) break;
  2409. nalsize = 0;
  2410. for(i = 0; i < h->nal_length_size; i++)
  2411. nalsize = (nalsize << 8) | buf[buf_index++];
  2412. if(nalsize <= 1 || nalsize > buf_size - buf_index){
  2413. if(nalsize == 1){
  2414. buf_index++;
  2415. continue;
  2416. }else{
  2417. av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);
  2418. break;
  2419. }
  2420. }
  2421. next_avc= buf_index + nalsize;
  2422. } else {
  2423. // start code prefix search
  2424. for(; buf_index + 3 < next_avc; buf_index++){
  2425. // This should always succeed in the first iteration.
  2426. if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)
  2427. break;
  2428. }
  2429. if(buf_index+3 >= buf_size) break;
  2430. buf_index+=3;
  2431. if(buf_index >= next_avc) continue;
  2432. }
  2433. hx = h->thread_context[context_count];
  2434. ptr= ff_h264_decode_nal(hx, buf + buf_index, &dst_length, &consumed, next_avc - buf_index);
  2435. if (ptr==NULL || dst_length < 0){
  2436. return -1;
  2437. }
  2438. i= buf_index + consumed;
  2439. if((s->workaround_bugs & FF_BUG_AUTODETECT) && i+3<next_avc &&
  2440. buf[i]==0x00 && buf[i+1]==0x00 && buf[i+2]==0x01 && buf[i+3]==0xE0)
  2441. s->workaround_bugs |= FF_BUG_TRUNCATED;
  2442. if(!(s->workaround_bugs & FF_BUG_TRUNCATED)){
  2443. while(ptr[dst_length - 1] == 0 && dst_length > 0)
  2444. dst_length--;
  2445. }
  2446. bit_length= !dst_length ? 0 : (8*dst_length - ff_h264_decode_rbsp_trailing(h, ptr + dst_length - 1));
  2447. if(s->avctx->debug&FF_DEBUG_STARTCODE){
  2448. 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);
  2449. }
  2450. if (h->is_avc && (nalsize != consumed) && nalsize){
  2451. av_log(h->s.avctx, AV_LOG_DEBUG, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);
  2452. }
  2453. buf_index += consumed;
  2454. if( (s->hurry_up == 1 && h->nal_ref_idc == 0) //FIXME do not discard SEI id
  2455. ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0))
  2456. continue;
  2457. again:
  2458. err = 0;
  2459. switch(hx->nal_unit_type){
  2460. case NAL_IDR_SLICE:
  2461. if (h->nal_unit_type != NAL_IDR_SLICE) {
  2462. av_log(h->s.avctx, AV_LOG_ERROR, "Invalid mix of idr and non-idr slices");
  2463. return -1;
  2464. }
  2465. idr(h); //FIXME ensure we don't loose some frames if there is reordering
  2466. case NAL_SLICE:
  2467. init_get_bits(&hx->s.gb, ptr, bit_length);
  2468. hx->intra_gb_ptr=
  2469. hx->inter_gb_ptr= &hx->s.gb;
  2470. hx->s.data_partitioning = 0;
  2471. if((err = decode_slice_header(hx, h)))
  2472. break;
  2473. if (h->current_slice == 1) {
  2474. if (s->avctx->hwaccel && s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
  2475. return -1;
  2476. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
  2477. ff_vdpau_h264_picture_start(s);
  2478. }
  2479. s->current_picture_ptr->key_frame |=
  2480. (hx->nal_unit_type == NAL_IDR_SLICE) ||
  2481. (h->sei_recovery_frame_cnt >= 0);
  2482. if(hx->redundant_pic_count==0 && hx->s.hurry_up < 5
  2483. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  2484. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=FF_B_TYPE)
  2485. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
  2486. && avctx->skip_frame < AVDISCARD_ALL){
  2487. if(avctx->hwaccel) {
  2488. if (avctx->hwaccel->decode_slice(avctx, &buf[buf_index - consumed], consumed) < 0)
  2489. return -1;
  2490. }else
  2491. if(CONFIG_H264_VDPAU_DECODER && s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU){
  2492. static const uint8_t start_code[] = {0x00, 0x00, 0x01};
  2493. ff_vdpau_add_data_chunk(s, start_code, sizeof(start_code));
  2494. ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed], consumed );
  2495. }else
  2496. context_count++;
  2497. }
  2498. break;
  2499. case NAL_DPA:
  2500. init_get_bits(&hx->s.gb, ptr, bit_length);
  2501. hx->intra_gb_ptr=
  2502. hx->inter_gb_ptr= NULL;
  2503. if ((err = decode_slice_header(hx, h)) < 0)
  2504. break;
  2505. hx->s.data_partitioning = 1;
  2506. break;
  2507. case NAL_DPB:
  2508. init_get_bits(&hx->intra_gb, ptr, bit_length);
  2509. hx->intra_gb_ptr= &hx->intra_gb;
  2510. break;
  2511. case NAL_DPC:
  2512. init_get_bits(&hx->inter_gb, ptr, bit_length);
  2513. hx->inter_gb_ptr= &hx->inter_gb;
  2514. if(hx->redundant_pic_count==0 && hx->intra_gb_ptr && hx->s.data_partitioning
  2515. && s->context_initialized
  2516. && s->hurry_up < 5
  2517. && (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc)
  2518. && (avctx->skip_frame < AVDISCARD_BIDIR || hx->slice_type_nos!=FF_B_TYPE)
  2519. && (avctx->skip_frame < AVDISCARD_NONKEY || hx->slice_type_nos==FF_I_TYPE)
  2520. && avctx->skip_frame < AVDISCARD_ALL)
  2521. context_count++;
  2522. break;
  2523. case NAL_SEI:
  2524. init_get_bits(&s->gb, ptr, bit_length);
  2525. ff_h264_decode_sei(h);
  2526. break;
  2527. case NAL_SPS:
  2528. init_get_bits(&s->gb, ptr, bit_length);
  2529. ff_h264_decode_seq_parameter_set(h);
  2530. if(s->flags& CODEC_FLAG_LOW_DELAY)
  2531. s->low_delay=1;
  2532. if(avctx->has_b_frames < 2)
  2533. avctx->has_b_frames= !s->low_delay;
  2534. break;
  2535. case NAL_PPS:
  2536. init_get_bits(&s->gb, ptr, bit_length);
  2537. ff_h264_decode_picture_parameter_set(h, bit_length);
  2538. break;
  2539. case NAL_AUD:
  2540. case NAL_END_SEQUENCE:
  2541. case NAL_END_STREAM:
  2542. case NAL_FILLER_DATA:
  2543. case NAL_SPS_EXT:
  2544. case NAL_AUXILIARY_SLICE:
  2545. break;
  2546. default:
  2547. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n", hx->nal_unit_type, bit_length);
  2548. }
  2549. if(context_count == h->max_contexts) {
  2550. execute_decode_slices(h, context_count);
  2551. context_count = 0;
  2552. }
  2553. if (err < 0)
  2554. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  2555. else if(err == 1) {
  2556. /* Slice could not be decoded in parallel mode, copy down
  2557. * NAL unit stuff to context 0 and restart. Note that
  2558. * rbsp_buffer is not transferred, but since we no longer
  2559. * run in parallel mode this should not be an issue. */
  2560. h->nal_unit_type = hx->nal_unit_type;
  2561. h->nal_ref_idc = hx->nal_ref_idc;
  2562. hx = h;
  2563. goto again;
  2564. }
  2565. }
  2566. if(context_count)
  2567. execute_decode_slices(h, context_count);
  2568. return buf_index;
  2569. }
  2570. /**
  2571. * returns the number of bytes consumed for building the current frame
  2572. */
  2573. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size){
  2574. if(pos==0) pos=1; //avoid infinite loops (i doubt that is needed but ...)
  2575. if(pos+10>buf_size) pos=buf_size; // oops ;)
  2576. return pos;
  2577. }
  2578. static int decode_frame(AVCodecContext *avctx,
  2579. void *data, int *data_size,
  2580. AVPacket *avpkt)
  2581. {
  2582. const uint8_t *buf = avpkt->data;
  2583. int buf_size = avpkt->size;
  2584. H264Context *h = avctx->priv_data;
  2585. MpegEncContext *s = &h->s;
  2586. AVFrame *pict = data;
  2587. int buf_index;
  2588. s->flags= avctx->flags;
  2589. s->flags2= avctx->flags2;
  2590. /* end of stream, output what is still in the buffers */
  2591. if (buf_size == 0) {
  2592. Picture *out;
  2593. int i, out_idx;
  2594. //FIXME factorize this with the output code below
  2595. out = h->delayed_pic[0];
  2596. out_idx = 0;
  2597. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  2598. if(h->delayed_pic[i]->poc < out->poc){
  2599. out = h->delayed_pic[i];
  2600. out_idx = i;
  2601. }
  2602. for(i=out_idx; h->delayed_pic[i]; i++)
  2603. h->delayed_pic[i] = h->delayed_pic[i+1];
  2604. if(out){
  2605. *data_size = sizeof(AVFrame);
  2606. *pict= *(AVFrame*)out;
  2607. }
  2608. return 0;
  2609. }
  2610. buf_index=decode_nal_units(h, buf, buf_size);
  2611. if(buf_index < 0)
  2612. return -1;
  2613. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){
  2614. if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;
  2615. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  2616. return -1;
  2617. }
  2618. if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){
  2619. Picture *out = s->current_picture_ptr;
  2620. Picture *cur = s->current_picture_ptr;
  2621. int i, pics, out_of_order, out_idx;
  2622. field_end(h);
  2623. if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {
  2624. /* Wait for second field. */
  2625. *data_size = 0;
  2626. } else {
  2627. cur->interlaced_frame = 0;
  2628. cur->repeat_pict = 0;
  2629. /* Signal interlacing information externally. */
  2630. /* Prioritize picture timing SEI information over used decoding process if it exists. */
  2631. if(h->sps.pic_struct_present_flag){
  2632. switch (h->sei_pic_struct)
  2633. {
  2634. case SEI_PIC_STRUCT_FRAME:
  2635. break;
  2636. case SEI_PIC_STRUCT_TOP_FIELD:
  2637. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  2638. cur->interlaced_frame = 1;
  2639. break;
  2640. case SEI_PIC_STRUCT_TOP_BOTTOM:
  2641. case SEI_PIC_STRUCT_BOTTOM_TOP:
  2642. if (FIELD_OR_MBAFF_PICTURE)
  2643. cur->interlaced_frame = 1;
  2644. else
  2645. // try to flag soft telecine progressive
  2646. cur->interlaced_frame = h->prev_interlaced_frame;
  2647. break;
  2648. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  2649. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  2650. // Signal the possibility of telecined film externally (pic_struct 5,6)
  2651. // From these hints, let the applications decide if they apply deinterlacing.
  2652. cur->repeat_pict = 1;
  2653. break;
  2654. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  2655. // Force progressive here, as doubling interlaced frame is a bad idea.
  2656. cur->repeat_pict = 2;
  2657. break;
  2658. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  2659. cur->repeat_pict = 4;
  2660. break;
  2661. }
  2662. if ((h->sei_ct_type & 3) && h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  2663. cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;
  2664. }else{
  2665. /* Derive interlacing flag from used decoding process. */
  2666. cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  2667. }
  2668. h->prev_interlaced_frame = cur->interlaced_frame;
  2669. if (cur->field_poc[0] != cur->field_poc[1]){
  2670. /* Derive top_field_first from field pocs. */
  2671. cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  2672. }else{
  2673. if(cur->interlaced_frame || h->sps.pic_struct_present_flag){
  2674. /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */
  2675. if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM
  2676. || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  2677. cur->top_field_first = 1;
  2678. else
  2679. cur->top_field_first = 0;
  2680. }else{
  2681. /* Most likely progressive */
  2682. cur->top_field_first = 0;
  2683. }
  2684. }
  2685. //FIXME do something with unavailable reference frames
  2686. /* Sort B-frames into display order */
  2687. if(h->sps.bitstream_restriction_flag
  2688. && s->avctx->has_b_frames < h->sps.num_reorder_frames){
  2689. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  2690. s->low_delay = 0;
  2691. }
  2692. if( s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT
  2693. && !h->sps.bitstream_restriction_flag){
  2694. s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;
  2695. s->low_delay= 0;
  2696. }
  2697. pics = 0;
  2698. while(h->delayed_pic[pics]) pics++;
  2699. assert(pics <= MAX_DELAYED_PIC_COUNT);
  2700. h->delayed_pic[pics++] = cur;
  2701. if(cur->reference == 0)
  2702. cur->reference = DELAYED_PIC_REF;
  2703. out = h->delayed_pic[0];
  2704. out_idx = 0;
  2705. for(i=1; h->delayed_pic[i] && !h->delayed_pic[i]->key_frame && !h->delayed_pic[i]->mmco_reset; i++)
  2706. if(h->delayed_pic[i]->poc < out->poc){
  2707. out = h->delayed_pic[i];
  2708. out_idx = i;
  2709. }
  2710. if(s->avctx->has_b_frames == 0 && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset))
  2711. h->outputed_poc= INT_MIN;
  2712. out_of_order = out->poc < h->outputed_poc;
  2713. if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)
  2714. { }
  2715. else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)
  2716. || (s->low_delay &&
  2717. ((h->outputed_poc != INT_MIN && out->poc > h->outputed_poc + 2)
  2718. || cur->pict_type == FF_B_TYPE)))
  2719. {
  2720. s->low_delay = 0;
  2721. s->avctx->has_b_frames++;
  2722. }
  2723. if(out_of_order || pics > s->avctx->has_b_frames){
  2724. out->reference &= ~DELAYED_PIC_REF;
  2725. for(i=out_idx; h->delayed_pic[i]; i++)
  2726. h->delayed_pic[i] = h->delayed_pic[i+1];
  2727. }
  2728. if(!out_of_order && pics > s->avctx->has_b_frames){
  2729. *data_size = sizeof(AVFrame);
  2730. if(out_idx==0 && h->delayed_pic[0] && (h->delayed_pic[0]->key_frame || h->delayed_pic[0]->mmco_reset)) {
  2731. h->outputed_poc = INT_MIN;
  2732. } else
  2733. h->outputed_poc = out->poc;
  2734. *pict= *(AVFrame*)out;
  2735. }else{
  2736. av_log(avctx, AV_LOG_DEBUG, "no picture\n");
  2737. }
  2738. }
  2739. }
  2740. assert(pict->data[0] || !*data_size);
  2741. ff_print_debug_info(s, pict);
  2742. //printf("out %d\n", (int)pict->data[0]);
  2743. return get_consumed_bytes(s, buf_index, buf_size);
  2744. }
  2745. #if 0
  2746. static inline void fill_mb_avail(H264Context *h){
  2747. MpegEncContext * const s = &h->s;
  2748. const int mb_xy= s->mb_x + s->mb_y*s->mb_stride;
  2749. if(s->mb_y){
  2750. h->mb_avail[0]= s->mb_x && h->slice_table[mb_xy - s->mb_stride - 1] == h->slice_num;
  2751. h->mb_avail[1]= h->slice_table[mb_xy - s->mb_stride ] == h->slice_num;
  2752. h->mb_avail[2]= s->mb_x+1 < s->mb_width && h->slice_table[mb_xy - s->mb_stride + 1] == h->slice_num;
  2753. }else{
  2754. h->mb_avail[0]=
  2755. h->mb_avail[1]=
  2756. h->mb_avail[2]= 0;
  2757. }
  2758. h->mb_avail[3]= s->mb_x && h->slice_table[mb_xy - 1] == h->slice_num;
  2759. h->mb_avail[4]= 1; //FIXME move out
  2760. h->mb_avail[5]= 0; //FIXME move out
  2761. }
  2762. #endif
  2763. #ifdef TEST
  2764. #undef printf
  2765. #undef random
  2766. #define COUNT 8000
  2767. #define SIZE (COUNT*40)
  2768. int main(void){
  2769. int i;
  2770. uint8_t temp[SIZE];
  2771. PutBitContext pb;
  2772. GetBitContext gb;
  2773. // int int_temp[10000];
  2774. DSPContext dsp;
  2775. AVCodecContext avctx;
  2776. dsputil_init(&dsp, &avctx);
  2777. init_put_bits(&pb, temp, SIZE);
  2778. printf("testing unsigned exp golomb\n");
  2779. for(i=0; i<COUNT; i++){
  2780. START_TIMER
  2781. set_ue_golomb(&pb, i);
  2782. STOP_TIMER("set_ue_golomb");
  2783. }
  2784. flush_put_bits(&pb);
  2785. init_get_bits(&gb, temp, 8*SIZE);
  2786. for(i=0; i<COUNT; i++){
  2787. int j, s;
  2788. s= show_bits(&gb, 24);
  2789. START_TIMER
  2790. j= get_ue_golomb(&gb);
  2791. if(j != i){
  2792. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  2793. // return -1;
  2794. }
  2795. STOP_TIMER("get_ue_golomb");
  2796. }
  2797. init_put_bits(&pb, temp, SIZE);
  2798. printf("testing signed exp golomb\n");
  2799. for(i=0; i<COUNT; i++){
  2800. START_TIMER
  2801. set_se_golomb(&pb, i - COUNT/2);
  2802. STOP_TIMER("set_se_golomb");
  2803. }
  2804. flush_put_bits(&pb);
  2805. init_get_bits(&gb, temp, 8*SIZE);
  2806. for(i=0; i<COUNT; i++){
  2807. int j, s;
  2808. s= show_bits(&gb, 24);
  2809. START_TIMER
  2810. j= get_se_golomb(&gb);
  2811. if(j != i - COUNT/2){
  2812. printf("mismatch! at %d (%d should be %d) bits:%6X\n", i, j, i, s);
  2813. // return -1;
  2814. }
  2815. STOP_TIMER("get_se_golomb");
  2816. }
  2817. #if 0
  2818. printf("testing 4x4 (I)DCT\n");
  2819. DCTELEM block[16];
  2820. uint8_t src[16], ref[16];
  2821. uint64_t error= 0, max_error=0;
  2822. for(i=0; i<COUNT; i++){
  2823. int j;
  2824. // printf("%d %d %d\n", r1, r2, (r2-r1)*16);
  2825. for(j=0; j<16; j++){
  2826. ref[j]= random()%255;
  2827. src[j]= random()%255;
  2828. }
  2829. h264_diff_dct_c(block, src, ref, 4);
  2830. //normalize
  2831. for(j=0; j<16; j++){
  2832. // printf("%d ", block[j]);
  2833. block[j]= block[j]*4;
  2834. if(j&1) block[j]= (block[j]*4 + 2)/5;
  2835. if(j&4) block[j]= (block[j]*4 + 2)/5;
  2836. }
  2837. // printf("\n");
  2838. h->h264dsp.h264_idct_add(ref, block, 4);
  2839. /* for(j=0; j<16; j++){
  2840. printf("%d ", ref[j]);
  2841. }
  2842. printf("\n");*/
  2843. for(j=0; j<16; j++){
  2844. int diff= FFABS(src[j] - ref[j]);
  2845. error+= diff*diff;
  2846. max_error= FFMAX(max_error, diff);
  2847. }
  2848. }
  2849. printf("error=%f max_error=%d\n", ((float)error)/COUNT/16, (int)max_error );
  2850. printf("testing quantizer\n");
  2851. for(qp=0; qp<52; qp++){
  2852. for(i=0; i<16; i++)
  2853. src1_block[i]= src2_block[i]= random()%255;
  2854. }
  2855. printf("Testing NAL layer\n");
  2856. uint8_t bitstream[COUNT];
  2857. uint8_t nal[COUNT*2];
  2858. H264Context h;
  2859. memset(&h, 0, sizeof(H264Context));
  2860. for(i=0; i<COUNT; i++){
  2861. int zeros= i;
  2862. int nal_length;
  2863. int consumed;
  2864. int out_length;
  2865. uint8_t *out;
  2866. int j;
  2867. for(j=0; j<COUNT; j++){
  2868. bitstream[j]= (random() % 255) + 1;
  2869. }
  2870. for(j=0; j<zeros; j++){
  2871. int pos= random() % COUNT;
  2872. while(bitstream[pos] == 0){
  2873. pos++;
  2874. pos %= COUNT;
  2875. }
  2876. bitstream[pos]=0;
  2877. }
  2878. START_TIMER
  2879. nal_length= encode_nal(&h, nal, bitstream, COUNT, COUNT*2);
  2880. if(nal_length<0){
  2881. printf("encoding failed\n");
  2882. return -1;
  2883. }
  2884. out= ff_h264_decode_nal(&h, nal, &out_length, &consumed, nal_length);
  2885. STOP_TIMER("NAL")
  2886. if(out_length != COUNT){
  2887. printf("incorrect length %d %d\n", out_length, COUNT);
  2888. return -1;
  2889. }
  2890. if(consumed != nal_length){
  2891. printf("incorrect consumed length %d %d\n", nal_length, consumed);
  2892. return -1;
  2893. }
  2894. if(memcmp(bitstream, out, COUNT)){
  2895. printf("mismatch\n");
  2896. return -1;
  2897. }
  2898. }
  2899. #endif
  2900. printf("Testing RBSP\n");
  2901. return 0;
  2902. }
  2903. #endif /* TEST */
  2904. av_cold void ff_h264_free_context(H264Context *h)
  2905. {
  2906. int i;
  2907. free_tables(h); //FIXME cleanup init stuff perhaps
  2908. for(i = 0; i < MAX_SPS_COUNT; i++)
  2909. av_freep(h->sps_buffers + i);
  2910. for(i = 0; i < MAX_PPS_COUNT; i++)
  2911. av_freep(h->pps_buffers + i);
  2912. }
  2913. av_cold int ff_h264_decode_end(AVCodecContext *avctx)
  2914. {
  2915. H264Context *h = avctx->priv_data;
  2916. MpegEncContext *s = &h->s;
  2917. ff_h264_free_context(h);
  2918. MPV_common_end(s);
  2919. // memset(h, 0, sizeof(H264Context));
  2920. return 0;
  2921. }
  2922. AVCodec h264_decoder = {
  2923. "h264",
  2924. AVMEDIA_TYPE_VIDEO,
  2925. CODEC_ID_H264,
  2926. sizeof(H264Context),
  2927. ff_h264_decode_init,
  2928. NULL,
  2929. ff_h264_decode_end,
  2930. decode_frame,
  2931. /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 | CODEC_CAP_DELAY,
  2932. .flush= flush_dpb,
  2933. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  2934. };
  2935. #if CONFIG_H264_VDPAU_DECODER
  2936. AVCodec h264_vdpau_decoder = {
  2937. "h264_vdpau",
  2938. AVMEDIA_TYPE_VIDEO,
  2939. CODEC_ID_H264,
  2940. sizeof(H264Context),
  2941. ff_h264_decode_init,
  2942. NULL,
  2943. ff_h264_decode_end,
  2944. decode_frame,
  2945. CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  2946. .flush= flush_dpb,
  2947. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  2948. .pix_fmts = (const enum PixelFormat[]){PIX_FMT_VDPAU_H264, PIX_FMT_NONE},
  2949. };
  2950. #endif