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.

3438 lines
128KB

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