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.

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