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.

3429 lines
128KB

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