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.

3388 lines
126KB

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