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.

3394 lines
126KB

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