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.

3521 lines
128KB

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