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.

2014 lines
68KB

  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. #define UNCHECKED_BITSTREAM_READER 1
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/display.h"
  29. #include "libavutil/imgutils.h"
  30. #include "libavutil/opt.h"
  31. #include "libavutil/stereo3d.h"
  32. #include "libavutil/timer.h"
  33. #include "internal.h"
  34. #include "cabac.h"
  35. #include "cabac_functions.h"
  36. #include "error_resilience.h"
  37. #include "avcodec.h"
  38. #include "h264.h"
  39. #include "h264data.h"
  40. #include "h264chroma.h"
  41. #include "h264_mvpred.h"
  42. #include "golomb.h"
  43. #include "mathops.h"
  44. #include "me_cmp.h"
  45. #include "mpegutils.h"
  46. #include "rectangle.h"
  47. #include "svq3.h"
  48. #include "thread.h"
  49. #include "vdpau_internal.h"
  50. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  51. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  52. {
  53. H264Context *h = avctx->priv_data;
  54. return h ? h->sps.num_reorder_frames : 0;
  55. }
  56. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  57. int (*mv)[2][4][2],
  58. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  59. {
  60. H264Context *h = opaque;
  61. H264SliceContext *sl = &h->slice_ctx[0];
  62. sl->mb_x = mb_x;
  63. sl->mb_y = mb_y;
  64. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  65. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  66. av_assert1(ref >= 0);
  67. /* FIXME: It is possible albeit uncommon that slice references
  68. * differ between slices. We take the easy approach and ignore
  69. * it for now. If this turns out to have any relevance in
  70. * practice then correct remapping should be added. */
  71. if (ref >= sl->ref_count[0])
  72. ref = 0;
  73. if (!sl->ref_list[0][ref].data[0]) {
  74. av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
  75. ref = 0;
  76. }
  77. if ((sl->ref_list[0][ref].reference&3) != 3) {
  78. av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
  79. return;
  80. }
  81. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  82. 2, 2, 2, ref, 1);
  83. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  84. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  85. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  86. sl->mb_mbaff =
  87. sl->mb_field_decoding_flag = 0;
  88. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  89. }
  90. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  91. int y, int height)
  92. {
  93. AVCodecContext *avctx = h->avctx;
  94. const AVFrame *src = &h->cur_pic.f;
  95. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  96. int vshift = desc->log2_chroma_h;
  97. const int field_pic = h->picture_structure != PICT_FRAME;
  98. if (field_pic) {
  99. height <<= 1;
  100. y <<= 1;
  101. }
  102. height = FFMIN(height, avctx->height - y);
  103. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  104. return;
  105. if (avctx->draw_horiz_band) {
  106. int offset[AV_NUM_DATA_POINTERS];
  107. int i;
  108. offset[0] = y * src->linesize[0];
  109. offset[1] =
  110. offset[2] = (y >> vshift) * src->linesize[1];
  111. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  112. offset[i] = 0;
  113. emms_c();
  114. avctx->draw_horiz_band(avctx, src, offset,
  115. y, h->picture_structure, height);
  116. }
  117. }
  118. /**
  119. * Check if the top & left blocks are available if needed and
  120. * change the dc mode so it only uses the available blocks.
  121. */
  122. int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
  123. {
  124. static const int8_t top[12] = {
  125. -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
  126. };
  127. static const int8_t left[12] = {
  128. 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
  129. };
  130. int i;
  131. if (!(sl->top_samples_available & 0x8000)) {
  132. for (i = 0; i < 4; i++) {
  133. int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
  134. if (status < 0) {
  135. av_log(h->avctx, AV_LOG_ERROR,
  136. "top block unavailable for requested intra4x4 mode %d at %d %d\n",
  137. status, sl->mb_x, sl->mb_y);
  138. return AVERROR_INVALIDDATA;
  139. } else if (status) {
  140. sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
  141. }
  142. }
  143. }
  144. if ((sl->left_samples_available & 0x8888) != 0x8888) {
  145. static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
  146. for (i = 0; i < 4; i++)
  147. if (!(sl->left_samples_available & mask[i])) {
  148. int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
  149. if (status < 0) {
  150. av_log(h->avctx, AV_LOG_ERROR,
  151. "left block unavailable for requested intra4x4 mode %d at %d %d\n",
  152. status, sl->mb_x, sl->mb_y);
  153. return AVERROR_INVALIDDATA;
  154. } else if (status) {
  155. sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
  156. }
  157. }
  158. }
  159. return 0;
  160. } // FIXME cleanup like ff_h264_check_intra_pred_mode
  161. /**
  162. * Check if the top & left blocks are available if needed and
  163. * change the dc mode so it only uses the available blocks.
  164. */
  165. int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
  166. int mode, int is_chroma)
  167. {
  168. static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
  169. static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
  170. if (mode > 3U) {
  171. av_log(h->avctx, AV_LOG_ERROR,
  172. "out of range intra chroma pred mode at %d %d\n",
  173. sl->mb_x, sl->mb_y);
  174. return AVERROR_INVALIDDATA;
  175. }
  176. if (!(sl->top_samples_available & 0x8000)) {
  177. mode = top[mode];
  178. if (mode < 0) {
  179. av_log(h->avctx, AV_LOG_ERROR,
  180. "top block unavailable for requested intra mode at %d %d\n",
  181. sl->mb_x, sl->mb_y);
  182. return AVERROR_INVALIDDATA;
  183. }
  184. }
  185. if ((sl->left_samples_available & 0x8080) != 0x8080) {
  186. mode = left[mode];
  187. if (mode < 0) {
  188. av_log(h->avctx, AV_LOG_ERROR,
  189. "left block unavailable for requested intra mode at %d %d\n",
  190. sl->mb_x, sl->mb_y);
  191. return AVERROR_INVALIDDATA;
  192. }
  193. if (is_chroma && (sl->left_samples_available & 0x8080)) {
  194. // mad cow disease mode, aka MBAFF + constrained_intra_pred
  195. mode = ALZHEIMER_DC_L0T_PRED8x8 +
  196. (!(sl->left_samples_available & 0x8000)) +
  197. 2 * (mode == DC_128_PRED8x8);
  198. }
  199. }
  200. return mode;
  201. }
  202. const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
  203. const uint8_t *src,
  204. int *dst_length, int *consumed, int length)
  205. {
  206. int i, si, di;
  207. uint8_t *dst;
  208. // src[0]&0x80; // forbidden bit
  209. h->nal_ref_idc = src[0] >> 5;
  210. h->nal_unit_type = src[0] & 0x1F;
  211. src++;
  212. length--;
  213. #define STARTCODE_TEST \
  214. if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
  215. if (src[i + 2] != 3 && src[i + 2] != 0) { \
  216. /* startcode, so we must be past the end */ \
  217. length = i; \
  218. } \
  219. break; \
  220. }
  221. #if HAVE_FAST_UNALIGNED
  222. #define FIND_FIRST_ZERO \
  223. if (i > 0 && !src[i]) \
  224. i--; \
  225. while (src[i]) \
  226. i++
  227. #if HAVE_FAST_64BIT
  228. for (i = 0; i + 1 < length; i += 9) {
  229. if (!((~AV_RN64A(src + i) &
  230. (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
  231. 0x8000800080008080ULL))
  232. continue;
  233. FIND_FIRST_ZERO;
  234. STARTCODE_TEST;
  235. i -= 7;
  236. }
  237. #else
  238. for (i = 0; i + 1 < length; i += 5) {
  239. if (!((~AV_RN32A(src + i) &
  240. (AV_RN32A(src + i) - 0x01000101U)) &
  241. 0x80008080U))
  242. continue;
  243. FIND_FIRST_ZERO;
  244. STARTCODE_TEST;
  245. i -= 3;
  246. }
  247. #endif
  248. #else
  249. for (i = 0; i + 1 < length; i += 2) {
  250. if (src[i])
  251. continue;
  252. if (i > 0 && src[i - 1] == 0)
  253. i--;
  254. STARTCODE_TEST;
  255. }
  256. #endif
  257. av_fast_padded_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size, length+MAX_MBPAIR_SIZE);
  258. dst = sl->rbsp_buffer;
  259. if (!dst)
  260. return NULL;
  261. if(i>=length-1){ //no escaped 0
  262. *dst_length= length;
  263. *consumed= length+1; //+1 for the header
  264. if(h->avctx->flags2 & CODEC_FLAG2_FAST){
  265. return src;
  266. }else{
  267. memcpy(dst, src, length);
  268. return dst;
  269. }
  270. }
  271. memcpy(dst, src, i);
  272. si = di = i;
  273. while (si + 2 < length) {
  274. // remove escapes (very rare 1:2^22)
  275. if (src[si + 2] > 3) {
  276. dst[di++] = src[si++];
  277. dst[di++] = src[si++];
  278. } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {
  279. if (src[si + 2] == 3) { // escape
  280. dst[di++] = 0;
  281. dst[di++] = 0;
  282. si += 3;
  283. continue;
  284. } else // next start code
  285. goto nsc;
  286. }
  287. dst[di++] = src[si++];
  288. }
  289. while (si < length)
  290. dst[di++] = src[si++];
  291. nsc:
  292. memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  293. *dst_length = di;
  294. *consumed = si + 1; // +1 for the header
  295. /* FIXME store exact number of bits in the getbitcontext
  296. * (it is needed for decoding) */
  297. return dst;
  298. }
  299. /**
  300. * Identify the exact end of the bitstream
  301. * @return the length of the trailing, or 0 if damaged
  302. */
  303. static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
  304. {
  305. int v = *src;
  306. int r;
  307. tprintf(h->avctx, "rbsp trailing %X\n", v);
  308. for (r = 1; r < 9; r++) {
  309. if (v & 1)
  310. return r;
  311. v >>= 1;
  312. }
  313. return 0;
  314. }
  315. void ff_h264_free_tables(H264Context *h, int free_rbsp)
  316. {
  317. int i;
  318. av_freep(&h->intra4x4_pred_mode);
  319. av_freep(&h->chroma_pred_mode_table);
  320. av_freep(&h->cbp_table);
  321. av_freep(&h->mvd_table[0]);
  322. av_freep(&h->mvd_table[1]);
  323. av_freep(&h->direct_table);
  324. av_freep(&h->non_zero_count);
  325. av_freep(&h->slice_table_base);
  326. h->slice_table = NULL;
  327. av_freep(&h->list_counts);
  328. av_freep(&h->mb2b_xy);
  329. av_freep(&h->mb2br_xy);
  330. av_buffer_pool_uninit(&h->qscale_table_pool);
  331. av_buffer_pool_uninit(&h->mb_type_pool);
  332. av_buffer_pool_uninit(&h->motion_val_pool);
  333. av_buffer_pool_uninit(&h->ref_index_pool);
  334. if (free_rbsp && h->DPB) {
  335. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  336. ff_h264_unref_picture(h, &h->DPB[i]);
  337. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  338. av_freep(&h->DPB);
  339. } else if (h->DPB) {
  340. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  341. h->DPB[i].needs_realloc = 1;
  342. }
  343. h->cur_pic_ptr = NULL;
  344. for (i = 0; i < h->nb_slice_ctx; i++) {
  345. H264SliceContext *sl = &h->slice_ctx[i];
  346. av_freep(&sl->dc_val_base);
  347. av_freep(&sl->er.mb_index2xy);
  348. av_freep(&sl->er.error_status_table);
  349. av_freep(&sl->er.er_temp_buffer);
  350. av_freep(&sl->bipred_scratchpad);
  351. av_freep(&sl->edge_emu_buffer);
  352. av_freep(&sl->top_borders[0]);
  353. av_freep(&sl->top_borders[1]);
  354. sl->bipred_scratchpad_allocated = 0;
  355. sl->edge_emu_buffer_allocated = 0;
  356. sl->top_borders_allocated[0] = 0;
  357. sl->top_borders_allocated[1] = 0;
  358. if (free_rbsp) {
  359. av_freep(&sl->rbsp_buffer);
  360. sl->rbsp_buffer_size = 0;
  361. }
  362. }
  363. }
  364. int ff_h264_alloc_tables(H264Context *h)
  365. {
  366. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  367. const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
  368. int x, y, i;
  369. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  370. row_mb_num, 8 * sizeof(uint8_t), fail)
  371. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  372. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  373. big_mb_num * 48 * sizeof(uint8_t), fail)
  374. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  375. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  376. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  377. big_mb_num * sizeof(uint16_t), fail)
  378. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  379. big_mb_num * sizeof(uint8_t), fail)
  380. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
  381. row_mb_num, 16 * sizeof(uint8_t), fail);
  382. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
  383. row_mb_num, 16 * sizeof(uint8_t), fail);
  384. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  385. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  386. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  387. 4 * big_mb_num * sizeof(uint8_t), fail);
  388. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  389. big_mb_num * sizeof(uint8_t), fail)
  390. memset(h->slice_table_base, -1,
  391. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  392. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  393. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  394. big_mb_num * sizeof(uint32_t), fail);
  395. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  396. big_mb_num * sizeof(uint32_t), fail);
  397. for (y = 0; y < h->mb_height; y++)
  398. for (x = 0; x < h->mb_width; x++) {
  399. const int mb_xy = x + y * h->mb_stride;
  400. const int b_xy = 4 * x + 4 * y * h->b_stride;
  401. h->mb2b_xy[mb_xy] = b_xy;
  402. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  403. }
  404. if (!h->dequant4_coeff[0])
  405. ff_h264_init_dequant_tables(h);
  406. if (!h->DPB) {
  407. h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
  408. if (!h->DPB)
  409. goto fail;
  410. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  411. av_frame_unref(&h->DPB[i].f);
  412. av_frame_unref(&h->cur_pic.f);
  413. }
  414. return 0;
  415. fail:
  416. ff_h264_free_tables(h, 1);
  417. return AVERROR(ENOMEM);
  418. }
  419. /**
  420. * Init context
  421. * Allocate buffers which are not shared amongst multiple threads.
  422. */
  423. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  424. {
  425. ERContext *er = &sl->er;
  426. int mb_array_size = h->mb_height * h->mb_stride;
  427. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  428. int c_size = h->mb_stride * (h->mb_height + 1);
  429. int yc_size = y_size + 2 * c_size;
  430. int x, y, i;
  431. sl->ref_cache[0][scan8[5] + 1] =
  432. sl->ref_cache[0][scan8[7] + 1] =
  433. sl->ref_cache[0][scan8[13] + 1] =
  434. sl->ref_cache[1][scan8[5] + 1] =
  435. sl->ref_cache[1][scan8[7] + 1] =
  436. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  437. if (CONFIG_ERROR_RESILIENCE) {
  438. /* init ER */
  439. er->avctx = h->avctx;
  440. er->decode_mb = h264_er_decode_mb;
  441. er->opaque = h;
  442. er->quarter_sample = 1;
  443. er->mb_num = h->mb_num;
  444. er->mb_width = h->mb_width;
  445. er->mb_height = h->mb_height;
  446. er->mb_stride = h->mb_stride;
  447. er->b8_stride = h->mb_width * 2 + 1;
  448. // error resilience code looks cleaner with this
  449. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  450. (h->mb_num + 1) * sizeof(int), fail);
  451. for (y = 0; y < h->mb_height; y++)
  452. for (x = 0; x < h->mb_width; x++)
  453. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  454. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  455. h->mb_stride + h->mb_width;
  456. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  457. mb_array_size * sizeof(uint8_t), fail);
  458. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  459. h->mb_height * h->mb_stride, fail);
  460. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  461. yc_size * sizeof(int16_t), fail);
  462. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  463. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  464. er->dc_val[2] = er->dc_val[1] + c_size;
  465. for (i = 0; i < yc_size; i++)
  466. sl->dc_val_base[i] = 1024;
  467. }
  468. return 0;
  469. fail:
  470. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  471. }
  472. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  473. int parse_extradata);
  474. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  475. {
  476. AVCodecContext *avctx = h->avctx;
  477. int ret;
  478. if (!buf || size <= 0)
  479. return -1;
  480. if (buf[0] == 1) {
  481. int i, cnt, nalsize;
  482. const unsigned char *p = buf;
  483. h->is_avc = 1;
  484. if (size < 7) {
  485. av_log(avctx, AV_LOG_ERROR,
  486. "avcC %d too short\n", size);
  487. return AVERROR_INVALIDDATA;
  488. }
  489. /* sps and pps in the avcC always have length coded with 2 bytes,
  490. * so put a fake nal_length_size = 2 while parsing them */
  491. h->nal_length_size = 2;
  492. // Decode sps from avcC
  493. cnt = *(p + 5) & 0x1f; // Number of sps
  494. p += 6;
  495. for (i = 0; i < cnt; i++) {
  496. nalsize = AV_RB16(p) + 2;
  497. if(nalsize > size - (p-buf))
  498. return AVERROR_INVALIDDATA;
  499. ret = decode_nal_units(h, p, nalsize, 1);
  500. if (ret < 0) {
  501. av_log(avctx, AV_LOG_ERROR,
  502. "Decoding sps %d from avcC failed\n", i);
  503. return ret;
  504. }
  505. p += nalsize;
  506. }
  507. // Decode pps from avcC
  508. cnt = *(p++); // Number of pps
  509. for (i = 0; i < cnt; i++) {
  510. nalsize = AV_RB16(p) + 2;
  511. if(nalsize > size - (p-buf))
  512. return AVERROR_INVALIDDATA;
  513. ret = decode_nal_units(h, p, nalsize, 1);
  514. if (ret < 0) {
  515. av_log(avctx, AV_LOG_ERROR,
  516. "Decoding pps %d from avcC failed\n", i);
  517. return ret;
  518. }
  519. p += nalsize;
  520. }
  521. // Store right nal length size that will be used to parse all other nals
  522. h->nal_length_size = (buf[4] & 0x03) + 1;
  523. } else {
  524. h->is_avc = 0;
  525. ret = decode_nal_units(h, buf, size, 1);
  526. if (ret < 0)
  527. return ret;
  528. }
  529. return size;
  530. }
  531. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  532. {
  533. H264Context *h = avctx->priv_data;
  534. int i;
  535. int ret;
  536. h->avctx = avctx;
  537. h->bit_depth_luma = 8;
  538. h->chroma_format_idc = 1;
  539. h->cur_chroma_format_idc = 1;
  540. ff_h264dsp_init(&h->h264dsp, 8, 1);
  541. av_assert0(h->sps.bit_depth_chroma == 0);
  542. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  543. ff_h264qpel_init(&h->h264qpel, 8);
  544. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
  545. h->dequant_coeff_pps = -1;
  546. h->current_sps_id = -1;
  547. /* needed so that IDCT permutation is known early */
  548. ff_videodsp_init(&h->vdsp, 8);
  549. memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
  550. memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  551. h->picture_structure = PICT_FRAME;
  552. h->slice_context_count = 1;
  553. h->workaround_bugs = avctx->workaround_bugs;
  554. h->flags = avctx->flags;
  555. /* set defaults */
  556. // s->decode_mb = ff_h263_decode_mb;
  557. if (!avctx->has_b_frames)
  558. h->low_delay = 1;
  559. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  560. ff_h264_decode_init_vlc();
  561. ff_init_cabac_states();
  562. h->pixel_shift = 0;
  563. h->cur_bit_depth_luma =
  564. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  565. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
  566. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  567. if (!h->slice_ctx) {
  568. h->nb_slice_ctx = 0;
  569. return AVERROR(ENOMEM);
  570. }
  571. for (i = 0; i < h->nb_slice_ctx; i++)
  572. h->slice_ctx[i].h264 = h;
  573. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  574. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  575. h->last_pocs[i] = INT_MIN;
  576. h->prev_poc_msb = 1 << 16;
  577. h->prev_frame_num = -1;
  578. h->x264_build = -1;
  579. h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
  580. ff_h264_reset_sei(h);
  581. if (avctx->codec_id == AV_CODEC_ID_H264) {
  582. if (avctx->ticks_per_frame == 1) {
  583. if(h->avctx->time_base.den < INT_MAX/2) {
  584. h->avctx->time_base.den *= 2;
  585. } else
  586. h->avctx->time_base.num /= 2;
  587. }
  588. avctx->ticks_per_frame = 2;
  589. }
  590. if (avctx->extradata_size > 0 && avctx->extradata) {
  591. ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
  592. if (ret < 0) {
  593. ff_h264_free_context(h);
  594. return ret;
  595. }
  596. }
  597. if (h->sps.bitstream_restriction_flag &&
  598. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  599. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  600. h->low_delay = 0;
  601. }
  602. avctx->internal->allocate_progress = 1;
  603. ff_h264_flush_change(h);
  604. if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
  605. h->enable_er = 0;
  606. if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  607. av_log(avctx, AV_LOG_WARNING,
  608. "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
  609. "Use it at your own risk\n");
  610. }
  611. return 0;
  612. }
  613. static int decode_init_thread_copy(AVCodecContext *avctx)
  614. {
  615. H264Context *h = avctx->priv_data;
  616. int i;
  617. if (!avctx->internal->is_copy)
  618. return 0;
  619. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  620. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  621. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
  622. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  623. if (!h->slice_ctx) {
  624. h->nb_slice_ctx = 0;
  625. return AVERROR(ENOMEM);
  626. }
  627. for (i = 0; i < h->nb_slice_ctx; i++)
  628. h->slice_ctx[i].h264 = h;
  629. h->avctx = avctx;
  630. h->context_initialized = 0;
  631. return 0;
  632. }
  633. /**
  634. * Run setup operations that must be run after slice header decoding.
  635. * This includes finding the next displayed frame.
  636. *
  637. * @param h h264 master context
  638. * @param setup_finished enough NALs have been read that we can call
  639. * ff_thread_finish_setup()
  640. */
  641. static void decode_postinit(H264Context *h, int setup_finished)
  642. {
  643. H264Picture *out = h->cur_pic_ptr;
  644. H264Picture *cur = h->cur_pic_ptr;
  645. int i, pics, out_of_order, out_idx;
  646. h->cur_pic_ptr->f.pict_type = h->pict_type;
  647. if (h->next_output_pic)
  648. return;
  649. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  650. /* FIXME: if we have two PAFF fields in one packet, we can't start
  651. * the next thread here. If we have one field per packet, we can.
  652. * The check in decode_nal_units() is not good enough to find this
  653. * yet, so we assume the worst for now. */
  654. // if (setup_finished)
  655. // ff_thread_finish_setup(h->avctx);
  656. if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
  657. return;
  658. if (h->avctx->hwaccel || h->missing_fields <=1)
  659. return;
  660. }
  661. cur->f.interlaced_frame = 0;
  662. cur->f.repeat_pict = 0;
  663. /* Signal interlacing information externally. */
  664. /* Prioritize picture timing SEI information over used
  665. * decoding process if it exists. */
  666. if (h->sps.pic_struct_present_flag) {
  667. switch (h->sei_pic_struct) {
  668. case SEI_PIC_STRUCT_FRAME:
  669. break;
  670. case SEI_PIC_STRUCT_TOP_FIELD:
  671. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  672. cur->f.interlaced_frame = 1;
  673. break;
  674. case SEI_PIC_STRUCT_TOP_BOTTOM:
  675. case SEI_PIC_STRUCT_BOTTOM_TOP:
  676. if (FIELD_OR_MBAFF_PICTURE(h))
  677. cur->f.interlaced_frame = 1;
  678. else
  679. // try to flag soft telecine progressive
  680. cur->f.interlaced_frame = h->prev_interlaced_frame;
  681. break;
  682. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  683. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  684. /* Signal the possibility of telecined film externally
  685. * (pic_struct 5,6). From these hints, let the applications
  686. * decide if they apply deinterlacing. */
  687. cur->f.repeat_pict = 1;
  688. break;
  689. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  690. cur->f.repeat_pict = 2;
  691. break;
  692. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  693. cur->f.repeat_pict = 4;
  694. break;
  695. }
  696. if ((h->sei_ct_type & 3) &&
  697. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  698. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  699. } else {
  700. /* Derive interlacing flag from used decoding process. */
  701. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  702. }
  703. h->prev_interlaced_frame = cur->f.interlaced_frame;
  704. if (cur->field_poc[0] != cur->field_poc[1]) {
  705. /* Derive top_field_first from field pocs. */
  706. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  707. } else {
  708. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  709. /* Use picture timing SEI information. Even if it is a
  710. * information of a past frame, better than nothing. */
  711. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  712. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  713. cur->f.top_field_first = 1;
  714. else
  715. cur->f.top_field_first = 0;
  716. } else {
  717. /* Most likely progressive */
  718. cur->f.top_field_first = 0;
  719. }
  720. }
  721. if (h->sei_frame_packing_present &&
  722. h->frame_packing_arrangement_type >= 0 &&
  723. h->frame_packing_arrangement_type <= 6 &&
  724. h->content_interpretation_type > 0 &&
  725. h->content_interpretation_type < 3) {
  726. AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
  727. if (stereo) {
  728. switch (h->frame_packing_arrangement_type) {
  729. case 0:
  730. stereo->type = AV_STEREO3D_CHECKERBOARD;
  731. break;
  732. case 1:
  733. stereo->type = AV_STEREO3D_COLUMNS;
  734. break;
  735. case 2:
  736. stereo->type = AV_STEREO3D_LINES;
  737. break;
  738. case 3:
  739. if (h->quincunx_subsampling)
  740. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  741. else
  742. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  743. break;
  744. case 4:
  745. stereo->type = AV_STEREO3D_TOPBOTTOM;
  746. break;
  747. case 5:
  748. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  749. break;
  750. case 6:
  751. stereo->type = AV_STEREO3D_2D;
  752. break;
  753. }
  754. if (h->content_interpretation_type == 2)
  755. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  756. }
  757. }
  758. if (h->sei_display_orientation_present &&
  759. (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
  760. double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
  761. AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
  762. AV_FRAME_DATA_DISPLAYMATRIX,
  763. sizeof(int32_t) * 9);
  764. if (rotation) {
  765. av_display_rotation_set((int32_t *)rotation->data, angle);
  766. av_display_matrix_flip((int32_t *)rotation->data,
  767. h->sei_hflip, h->sei_vflip);
  768. }
  769. }
  770. cur->mmco_reset = h->mmco_reset;
  771. h->mmco_reset = 0;
  772. // FIXME do something with unavailable reference frames
  773. /* Sort B-frames into display order */
  774. if (h->sps.bitstream_restriction_flag &&
  775. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  776. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  777. h->low_delay = 0;
  778. }
  779. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  780. !h->sps.bitstream_restriction_flag) {
  781. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  782. h->low_delay = 0;
  783. }
  784. for (i = 0; 1; i++) {
  785. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  786. if(i)
  787. h->last_pocs[i-1] = cur->poc;
  788. break;
  789. } else if(i) {
  790. h->last_pocs[i-1]= h->last_pocs[i];
  791. }
  792. }
  793. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  794. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  795. || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
  796. out_of_order = FFMAX(out_of_order, 1);
  797. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  798. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  799. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  800. h->last_pocs[i] = INT_MIN;
  801. h->last_pocs[0] = cur->poc;
  802. cur->mmco_reset = 1;
  803. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  804. av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  805. h->avctx->has_b_frames = out_of_order;
  806. h->low_delay = 0;
  807. }
  808. pics = 0;
  809. while (h->delayed_pic[pics])
  810. pics++;
  811. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  812. h->delayed_pic[pics++] = cur;
  813. if (cur->reference == 0)
  814. cur->reference = DELAYED_PIC_REF;
  815. out = h->delayed_pic[0];
  816. out_idx = 0;
  817. for (i = 1; h->delayed_pic[i] &&
  818. !h->delayed_pic[i]->f.key_frame &&
  819. !h->delayed_pic[i]->mmco_reset;
  820. i++)
  821. if (h->delayed_pic[i]->poc < out->poc) {
  822. out = h->delayed_pic[i];
  823. out_idx = i;
  824. }
  825. if (h->avctx->has_b_frames == 0 &&
  826. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  827. h->next_outputed_poc = INT_MIN;
  828. out_of_order = out->poc < h->next_outputed_poc;
  829. if (out_of_order || pics > h->avctx->has_b_frames) {
  830. out->reference &= ~DELAYED_PIC_REF;
  831. // for frame threading, the owner must be the second field's thread or
  832. // else the first thread can release the picture and reuse it unsafely
  833. for (i = out_idx; h->delayed_pic[i]; i++)
  834. h->delayed_pic[i] = h->delayed_pic[i + 1];
  835. }
  836. if (!out_of_order && pics > h->avctx->has_b_frames) {
  837. h->next_output_pic = out;
  838. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  839. h->next_outputed_poc = INT_MIN;
  840. } else
  841. h->next_outputed_poc = out->poc;
  842. } else {
  843. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  844. }
  845. if (h->next_output_pic) {
  846. if (h->next_output_pic->recovered) {
  847. // We have reached an recovery point and all frames after it in
  848. // display order are "recovered".
  849. h->frame_recovered |= FRAME_RECOVERED_SEI;
  850. }
  851. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  852. }
  853. if (setup_finished && !h->avctx->hwaccel)
  854. ff_thread_finish_setup(h->avctx);
  855. }
  856. int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
  857. {
  858. int list, i;
  859. int luma_def, chroma_def;
  860. sl->use_weight = 0;
  861. sl->use_weight_chroma = 0;
  862. sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
  863. if (h->sps.chroma_format_idc)
  864. sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
  865. if (sl->luma_log2_weight_denom > 7U) {
  866. av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
  867. sl->luma_log2_weight_denom = 0;
  868. }
  869. if (sl->chroma_log2_weight_denom > 7U) {
  870. av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
  871. sl->chroma_log2_weight_denom = 0;
  872. }
  873. luma_def = 1 << sl->luma_log2_weight_denom;
  874. chroma_def = 1 << sl->chroma_log2_weight_denom;
  875. for (list = 0; list < 2; list++) {
  876. sl->luma_weight_flag[list] = 0;
  877. sl->chroma_weight_flag[list] = 0;
  878. for (i = 0; i < sl->ref_count[list]; i++) {
  879. int luma_weight_flag, chroma_weight_flag;
  880. luma_weight_flag = get_bits1(&sl->gb);
  881. if (luma_weight_flag) {
  882. sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
  883. sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
  884. if (sl->luma_weight[i][list][0] != luma_def ||
  885. sl->luma_weight[i][list][1] != 0) {
  886. sl->use_weight = 1;
  887. sl->luma_weight_flag[list] = 1;
  888. }
  889. } else {
  890. sl->luma_weight[i][list][0] = luma_def;
  891. sl->luma_weight[i][list][1] = 0;
  892. }
  893. if (h->sps.chroma_format_idc) {
  894. chroma_weight_flag = get_bits1(&sl->gb);
  895. if (chroma_weight_flag) {
  896. int j;
  897. for (j = 0; j < 2; j++) {
  898. sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
  899. sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
  900. if (sl->chroma_weight[i][list][j][0] != chroma_def ||
  901. sl->chroma_weight[i][list][j][1] != 0) {
  902. sl->use_weight_chroma = 1;
  903. sl->chroma_weight_flag[list] = 1;
  904. }
  905. }
  906. } else {
  907. int j;
  908. for (j = 0; j < 2; j++) {
  909. sl->chroma_weight[i][list][j][0] = chroma_def;
  910. sl->chroma_weight[i][list][j][1] = 0;
  911. }
  912. }
  913. }
  914. }
  915. if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
  916. break;
  917. }
  918. sl->use_weight = sl->use_weight || sl->use_weight_chroma;
  919. return 0;
  920. }
  921. /**
  922. * instantaneous decoder refresh.
  923. */
  924. static void idr(H264Context *h)
  925. {
  926. int i;
  927. ff_h264_remove_all_refs(h);
  928. h->prev_frame_num =
  929. h->prev_frame_num_offset = 0;
  930. h->prev_poc_msb = 1<<16;
  931. h->prev_poc_lsb = 0;
  932. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  933. h->last_pocs[i] = INT_MIN;
  934. }
  935. /* forget old pics after a seek */
  936. void ff_h264_flush_change(H264Context *h)
  937. {
  938. int i, j;
  939. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  940. h->prev_interlaced_frame = 1;
  941. idr(h);
  942. h->prev_frame_num = -1;
  943. if (h->cur_pic_ptr) {
  944. h->cur_pic_ptr->reference = 0;
  945. for (j=i=0; h->delayed_pic[i]; i++)
  946. if (h->delayed_pic[i] != h->cur_pic_ptr)
  947. h->delayed_pic[j++] = h->delayed_pic[i];
  948. h->delayed_pic[j] = NULL;
  949. }
  950. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  951. h->first_field = 0;
  952. ff_h264_reset_sei(h);
  953. h->recovery_frame = -1;
  954. h->frame_recovered = 0;
  955. h->current_slice = 0;
  956. h->mmco_reset = 1;
  957. for (i = 0; i < h->nb_slice_ctx; i++)
  958. h->slice_ctx[i].list_count = 0;
  959. }
  960. /* forget old pics after a seek */
  961. static void flush_dpb(AVCodecContext *avctx)
  962. {
  963. H264Context *h = avctx->priv_data;
  964. int i;
  965. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  966. ff_h264_flush_change(h);
  967. if (h->DPB)
  968. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  969. ff_h264_unref_picture(h, &h->DPB[i]);
  970. h->cur_pic_ptr = NULL;
  971. ff_h264_unref_picture(h, &h->cur_pic);
  972. h->mb_y = 0;
  973. ff_h264_free_tables(h, 1);
  974. h->context_initialized = 0;
  975. }
  976. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  977. {
  978. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  979. int field_poc[2];
  980. h->frame_num_offset = h->prev_frame_num_offset;
  981. if (h->frame_num < h->prev_frame_num)
  982. h->frame_num_offset += max_frame_num;
  983. if (h->sps.poc_type == 0) {
  984. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  985. if (h->poc_lsb < h->prev_poc_lsb &&
  986. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  987. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  988. else if (h->poc_lsb > h->prev_poc_lsb &&
  989. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  990. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  991. else
  992. h->poc_msb = h->prev_poc_msb;
  993. field_poc[0] =
  994. field_poc[1] = h->poc_msb + h->poc_lsb;
  995. if (h->picture_structure == PICT_FRAME)
  996. field_poc[1] += h->delta_poc_bottom;
  997. } else if (h->sps.poc_type == 1) {
  998. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  999. int i;
  1000. if (h->sps.poc_cycle_length != 0)
  1001. abs_frame_num = h->frame_num_offset + h->frame_num;
  1002. else
  1003. abs_frame_num = 0;
  1004. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  1005. abs_frame_num--;
  1006. expected_delta_per_poc_cycle = 0;
  1007. for (i = 0; i < h->sps.poc_cycle_length; i++)
  1008. // FIXME integrate during sps parse
  1009. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  1010. if (abs_frame_num > 0) {
  1011. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1012. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1013. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1014. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1015. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1016. } else
  1017. expectedpoc = 0;
  1018. if (h->nal_ref_idc == 0)
  1019. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1020. field_poc[0] = expectedpoc + h->delta_poc[0];
  1021. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1022. if (h->picture_structure == PICT_FRAME)
  1023. field_poc[1] += h->delta_poc[1];
  1024. } else {
  1025. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1026. if (!h->nal_ref_idc)
  1027. poc--;
  1028. field_poc[0] = poc;
  1029. field_poc[1] = poc;
  1030. }
  1031. if (h->picture_structure != PICT_BOTTOM_FIELD)
  1032. pic_field_poc[0] = field_poc[0];
  1033. if (h->picture_structure != PICT_TOP_FIELD)
  1034. pic_field_poc[1] = field_poc[1];
  1035. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  1036. return 0;
  1037. }
  1038. /**
  1039. * Compute profile from profile_idc and constraint_set?_flags.
  1040. *
  1041. * @param sps SPS
  1042. *
  1043. * @return profile as defined by FF_PROFILE_H264_*
  1044. */
  1045. int ff_h264_get_profile(SPS *sps)
  1046. {
  1047. int profile = sps->profile_idc;
  1048. switch (sps->profile_idc) {
  1049. case FF_PROFILE_H264_BASELINE:
  1050. // constraint_set1_flag set to 1
  1051. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  1052. break;
  1053. case FF_PROFILE_H264_HIGH_10:
  1054. case FF_PROFILE_H264_HIGH_422:
  1055. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  1056. // constraint_set3_flag set to 1
  1057. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  1058. break;
  1059. }
  1060. return profile;
  1061. }
  1062. int ff_h264_set_parameter_from_sps(H264Context *h)
  1063. {
  1064. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  1065. (h->sps.bitstream_restriction_flag &&
  1066. !h->sps.num_reorder_frames)) {
  1067. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  1068. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  1069. "Reenabling low delay requires a codec flush.\n");
  1070. else
  1071. h->low_delay = 1;
  1072. }
  1073. if (h->avctx->has_b_frames < 2)
  1074. h->avctx->has_b_frames = !h->low_delay;
  1075. if (h->cur_bit_depth_luma != h->sps.bit_depth_luma ||
  1076. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  1077. if (h->avctx->codec &&
  1078. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  1079. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  1080. av_log(h->avctx, AV_LOG_ERROR,
  1081. "VDPAU decoding does not support video colorspace.\n");
  1082. return AVERROR_INVALIDDATA;
  1083. }
  1084. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
  1085. h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
  1086. h->cur_bit_depth_luma =
  1087. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  1088. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  1089. h->pixel_shift = h->sps.bit_depth_luma > 8;
  1090. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  1091. h->sps.chroma_format_idc);
  1092. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  1093. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  1094. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  1095. h->sps.chroma_format_idc);
  1096. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  1097. } else {
  1098. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
  1099. h->sps.bit_depth_luma);
  1100. return AVERROR_INVALIDDATA;
  1101. }
  1102. }
  1103. return 0;
  1104. }
  1105. int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
  1106. {
  1107. int ref_count[2], list_count;
  1108. int num_ref_idx_active_override_flag;
  1109. // set defaults, might be overridden a few lines later
  1110. ref_count[0] = h->pps.ref_count[0];
  1111. ref_count[1] = h->pps.ref_count[1];
  1112. if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1113. unsigned max[2];
  1114. max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
  1115. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1116. sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
  1117. num_ref_idx_active_override_flag = get_bits1(&sl->gb);
  1118. if (num_ref_idx_active_override_flag) {
  1119. ref_count[0] = get_ue_golomb(&sl->gb) + 1;
  1120. if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  1121. ref_count[1] = get_ue_golomb(&sl->gb) + 1;
  1122. } else
  1123. // full range is spec-ok in this case, even for frames
  1124. ref_count[1] = 1;
  1125. }
  1126. if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
  1127. av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]);
  1128. sl->ref_count[0] = sl->ref_count[1] = 0;
  1129. sl->list_count = 0;
  1130. return AVERROR_INVALIDDATA;
  1131. }
  1132. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1133. list_count = 2;
  1134. else
  1135. list_count = 1;
  1136. } else {
  1137. list_count = 0;
  1138. ref_count[0] = ref_count[1] = 0;
  1139. }
  1140. if (list_count != sl->list_count ||
  1141. ref_count[0] != sl->ref_count[0] ||
  1142. ref_count[1] != sl->ref_count[1]) {
  1143. sl->ref_count[0] = ref_count[0];
  1144. sl->ref_count[1] = ref_count[1];
  1145. sl->list_count = list_count;
  1146. return 1;
  1147. }
  1148. return 0;
  1149. }
  1150. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  1151. static int get_bit_length(H264Context *h, const uint8_t *buf,
  1152. const uint8_t *ptr, int dst_length,
  1153. int i, int next_avc)
  1154. {
  1155. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  1156. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  1157. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  1158. h->workaround_bugs |= FF_BUG_TRUNCATED;
  1159. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  1160. while (dst_length > 0 && ptr[dst_length - 1] == 0)
  1161. dst_length--;
  1162. if (!dst_length)
  1163. return 0;
  1164. return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
  1165. }
  1166. static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
  1167. {
  1168. int next_avc = h->is_avc ? 0 : buf_size;
  1169. int nal_index = 0;
  1170. int buf_index = 0;
  1171. int nals_needed = 0;
  1172. int first_slice = 0;
  1173. while(1) {
  1174. GetBitContext gb;
  1175. int nalsize = 0;
  1176. int dst_length, bit_length, consumed;
  1177. const uint8_t *ptr;
  1178. if (buf_index >= next_avc) {
  1179. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1180. if (nalsize < 0)
  1181. break;
  1182. next_avc = buf_index + nalsize;
  1183. } else {
  1184. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1185. if (buf_index >= buf_size)
  1186. break;
  1187. if (buf_index >= next_avc)
  1188. continue;
  1189. }
  1190. ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
  1191. next_avc - buf_index);
  1192. if (!ptr || dst_length < 0)
  1193. return AVERROR_INVALIDDATA;
  1194. buf_index += consumed;
  1195. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1196. buf_index, next_avc);
  1197. nal_index++;
  1198. /* packets can sometimes contain multiple PPS/SPS,
  1199. * e.g. two PAFF field pictures in one packet, or a demuxer
  1200. * which splits NALs strangely if so, when frame threading we
  1201. * can't start the next thread until we've read all of them */
  1202. switch (h->nal_unit_type) {
  1203. case NAL_SPS:
  1204. case NAL_PPS:
  1205. nals_needed = nal_index;
  1206. break;
  1207. case NAL_DPA:
  1208. case NAL_IDR_SLICE:
  1209. case NAL_SLICE:
  1210. init_get_bits(&gb, ptr, bit_length);
  1211. if (!get_ue_golomb(&gb) ||
  1212. !first_slice ||
  1213. first_slice != h->nal_unit_type)
  1214. nals_needed = nal_index;
  1215. if (!first_slice)
  1216. first_slice = h->nal_unit_type;
  1217. }
  1218. }
  1219. return nals_needed;
  1220. }
  1221. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  1222. int parse_extradata)
  1223. {
  1224. AVCodecContext *const avctx = h->avctx;
  1225. H264SliceContext *sl;
  1226. int buf_index;
  1227. unsigned context_count;
  1228. int next_avc;
  1229. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  1230. int nal_index;
  1231. int idr_cleared=0;
  1232. int ret = 0;
  1233. h->nal_unit_type= 0;
  1234. if(!h->slice_context_count)
  1235. h->slice_context_count= 1;
  1236. h->max_contexts = h->slice_context_count;
  1237. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  1238. h->current_slice = 0;
  1239. if (!h->first_field)
  1240. h->cur_pic_ptr = NULL;
  1241. ff_h264_reset_sei(h);
  1242. }
  1243. if (h->nal_length_size == 4) {
  1244. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  1245. h->is_avc = 0;
  1246. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  1247. h->is_avc = 1;
  1248. }
  1249. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1250. nals_needed = get_last_needed_nal(h, buf, buf_size);
  1251. {
  1252. buf_index = 0;
  1253. context_count = 0;
  1254. next_avc = h->is_avc ? 0 : buf_size;
  1255. nal_index = 0;
  1256. for (;;) {
  1257. int consumed;
  1258. int dst_length;
  1259. int bit_length;
  1260. const uint8_t *ptr;
  1261. int nalsize = 0;
  1262. int err;
  1263. if (buf_index >= next_avc) {
  1264. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1265. if (nalsize < 0)
  1266. break;
  1267. next_avc = buf_index + nalsize;
  1268. } else {
  1269. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1270. if (buf_index >= buf_size)
  1271. break;
  1272. if (buf_index >= next_avc)
  1273. continue;
  1274. }
  1275. sl = &h->slice_ctx[context_count];
  1276. ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
  1277. &consumed, next_avc - buf_index);
  1278. if (!ptr || dst_length < 0) {
  1279. ret = -1;
  1280. goto end;
  1281. }
  1282. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1283. buf_index + consumed, next_avc);
  1284. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  1285. av_log(h->avctx, AV_LOG_DEBUG,
  1286. "NAL %d/%d at %d/%d length %d\n",
  1287. h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
  1288. if (h->is_avc && (nalsize != consumed) && nalsize)
  1289. av_log(h->avctx, AV_LOG_DEBUG,
  1290. "AVC: Consumed only %d bytes instead of %d\n",
  1291. consumed, nalsize);
  1292. buf_index += consumed;
  1293. nal_index++;
  1294. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  1295. h->nal_ref_idc == 0 &&
  1296. h->nal_unit_type != NAL_SEI)
  1297. continue;
  1298. again:
  1299. if ( (!(avctx->active_thread_type & FF_THREAD_FRAME) || nals_needed >= nal_index)
  1300. && !h->current_slice)
  1301. h->au_pps_id = -1;
  1302. /* Ignore per frame NAL unit type during extradata
  1303. * parsing. Decoding slices is not possible in codec init
  1304. * with frame-mt */
  1305. if (parse_extradata) {
  1306. switch (h->nal_unit_type) {
  1307. case NAL_IDR_SLICE:
  1308. case NAL_SLICE:
  1309. case NAL_DPA:
  1310. case NAL_DPB:
  1311. case NAL_DPC:
  1312. av_log(h->avctx, AV_LOG_WARNING,
  1313. "Ignoring NAL %d in global header/extradata\n",
  1314. h->nal_unit_type);
  1315. // fall through to next case
  1316. case NAL_AUXILIARY_SLICE:
  1317. h->nal_unit_type = NAL_FF_IGNORE;
  1318. }
  1319. }
  1320. err = 0;
  1321. switch (h->nal_unit_type) {
  1322. case NAL_IDR_SLICE:
  1323. if ((ptr[0] & 0xFC) == 0x98) {
  1324. av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
  1325. h->next_outputed_poc = INT_MIN;
  1326. ret = -1;
  1327. goto end;
  1328. }
  1329. if (h->nal_unit_type != NAL_IDR_SLICE) {
  1330. av_log(h->avctx, AV_LOG_ERROR,
  1331. "Invalid mix of idr and non-idr slices\n");
  1332. ret = -1;
  1333. goto end;
  1334. }
  1335. if(!idr_cleared)
  1336. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  1337. idr_cleared = 1;
  1338. h->has_recovery_point = 1;
  1339. case NAL_SLICE:
  1340. init_get_bits(&sl->gb, ptr, bit_length);
  1341. if ((err = ff_h264_decode_slice_header(h, sl)))
  1342. break;
  1343. if (h->sei_recovery_frame_cnt >= 0) {
  1344. if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
  1345. h->valid_recovery_point = 1;
  1346. if ( h->recovery_frame < 0
  1347. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
  1348. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
  1349. ((1 << h->sps.log2_max_frame_num) - 1);
  1350. if (!h->valid_recovery_point)
  1351. h->recovery_frame = h->frame_num;
  1352. }
  1353. }
  1354. h->cur_pic_ptr->f.key_frame |=
  1355. (h->nal_unit_type == NAL_IDR_SLICE);
  1356. if (h->nal_unit_type == NAL_IDR_SLICE ||
  1357. h->recovery_frame == h->frame_num) {
  1358. h->recovery_frame = -1;
  1359. h->cur_pic_ptr->recovered = 1;
  1360. }
  1361. // If we have an IDR, all frames after it in decoded order are
  1362. // "recovered".
  1363. if (h->nal_unit_type == NAL_IDR_SLICE)
  1364. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1365. h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
  1366. h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
  1367. #if 1
  1368. h->cur_pic_ptr->recovered |= h->frame_recovered;
  1369. #else
  1370. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1371. #endif
  1372. if (h->current_slice == 1) {
  1373. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  1374. decode_postinit(h, nal_index >= nals_needed);
  1375. if (h->avctx->hwaccel &&
  1376. (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
  1377. return ret;
  1378. if (CONFIG_H264_VDPAU_DECODER &&
  1379. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  1380. ff_vdpau_h264_picture_start(h);
  1381. }
  1382. if (sl->redundant_pic_count == 0) {
  1383. if (avctx->hwaccel) {
  1384. ret = avctx->hwaccel->decode_slice(avctx,
  1385. &buf[buf_index - consumed],
  1386. consumed);
  1387. if (ret < 0)
  1388. return ret;
  1389. } else if (CONFIG_H264_VDPAU_DECODER &&
  1390. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  1391. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  1392. start_code,
  1393. sizeof(start_code));
  1394. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  1395. &buf[buf_index - consumed],
  1396. consumed);
  1397. } else
  1398. context_count++;
  1399. }
  1400. break;
  1401. case NAL_DPA:
  1402. case NAL_DPB:
  1403. case NAL_DPC:
  1404. avpriv_request_sample(avctx, "data partitioning");
  1405. ret = AVERROR(ENOSYS);
  1406. goto end;
  1407. break;
  1408. case NAL_SEI:
  1409. init_get_bits(&h->gb, ptr, bit_length);
  1410. ret = ff_h264_decode_sei(h);
  1411. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1412. goto end;
  1413. break;
  1414. case NAL_SPS:
  1415. init_get_bits(&h->gb, ptr, bit_length);
  1416. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
  1417. av_log(h->avctx, AV_LOG_DEBUG,
  1418. "SPS decoding failure, trying again with the complete NAL\n");
  1419. if (h->is_avc)
  1420. av_assert0(next_avc - buf_index + consumed == nalsize);
  1421. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  1422. break;
  1423. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  1424. 8*(next_avc - buf_index + consumed - 1));
  1425. ff_h264_decode_seq_parameter_set(h);
  1426. }
  1427. break;
  1428. case NAL_PPS:
  1429. init_get_bits(&h->gb, ptr, bit_length);
  1430. ret = ff_h264_decode_picture_parameter_set(h, bit_length);
  1431. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1432. goto end;
  1433. break;
  1434. case NAL_AUD:
  1435. case NAL_END_SEQUENCE:
  1436. case NAL_END_STREAM:
  1437. case NAL_FILLER_DATA:
  1438. case NAL_SPS_EXT:
  1439. case NAL_AUXILIARY_SLICE:
  1440. break;
  1441. case NAL_FF_IGNORE:
  1442. break;
  1443. default:
  1444. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  1445. h->nal_unit_type, bit_length);
  1446. }
  1447. if (context_count == h->max_contexts) {
  1448. ret = ff_h264_execute_decode_slices(h, context_count);
  1449. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1450. goto end;
  1451. context_count = 0;
  1452. }
  1453. if (err < 0 || err == SLICE_SKIPED) {
  1454. if (err < 0)
  1455. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  1456. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  1457. } else if (err == SLICE_SINGLETHREAD) {
  1458. /* Slice could not be decoded in parallel mode, restart. Note
  1459. * that rbsp_buffer is not transferred, but since we no longer
  1460. * run in parallel mode this should not be an issue. */
  1461. sl = &h->slice_ctx[0];
  1462. goto again;
  1463. }
  1464. }
  1465. }
  1466. if (context_count) {
  1467. ret = ff_h264_execute_decode_slices(h, context_count);
  1468. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1469. goto end;
  1470. }
  1471. ret = 0;
  1472. end:
  1473. /* clean up */
  1474. if (h->cur_pic_ptr && !h->droppable) {
  1475. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1476. h->picture_structure == PICT_BOTTOM_FIELD);
  1477. }
  1478. return (ret < 0) ? ret : buf_index;
  1479. }
  1480. /**
  1481. * Return the number of bytes consumed for building the current frame.
  1482. */
  1483. static int get_consumed_bytes(int pos, int buf_size)
  1484. {
  1485. if (pos == 0)
  1486. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  1487. if (pos + 10 > buf_size)
  1488. pos = buf_size; // oops ;)
  1489. return pos;
  1490. }
  1491. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  1492. {
  1493. AVFrame *src = &srcp->f;
  1494. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  1495. int i;
  1496. int ret = av_frame_ref(dst, src);
  1497. if (ret < 0)
  1498. return ret;
  1499. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
  1500. if (srcp->sei_recovery_frame_cnt == 0)
  1501. dst->key_frame = 1;
  1502. if (!srcp->crop)
  1503. return 0;
  1504. for (i = 0; i < desc->nb_components; i++) {
  1505. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  1506. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  1507. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  1508. (srcp->crop_top >> vshift) * dst->linesize[i];
  1509. dst->data[i] += off;
  1510. }
  1511. return 0;
  1512. }
  1513. static int is_extra(const uint8_t *buf, int buf_size)
  1514. {
  1515. int cnt= buf[5]&0x1f;
  1516. const uint8_t *p= buf+6;
  1517. while(cnt--){
  1518. int nalsize= AV_RB16(p) + 2;
  1519. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  1520. return 0;
  1521. p += nalsize;
  1522. }
  1523. cnt = *(p++);
  1524. if(!cnt)
  1525. return 0;
  1526. while(cnt--){
  1527. int nalsize= AV_RB16(p) + 2;
  1528. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  1529. return 0;
  1530. p += nalsize;
  1531. }
  1532. return 1;
  1533. }
  1534. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1535. int *got_frame, AVPacket *avpkt)
  1536. {
  1537. const uint8_t *buf = avpkt->data;
  1538. int buf_size = avpkt->size;
  1539. H264Context *h = avctx->priv_data;
  1540. AVFrame *pict = data;
  1541. int buf_index = 0;
  1542. H264Picture *out;
  1543. int i, out_idx;
  1544. int ret;
  1545. h->flags = avctx->flags;
  1546. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1547. /* end of stream, output what is still in the buffers */
  1548. if (buf_size == 0) {
  1549. out:
  1550. h->cur_pic_ptr = NULL;
  1551. h->first_field = 0;
  1552. // FIXME factorize this with the output code below
  1553. out = h->delayed_pic[0];
  1554. out_idx = 0;
  1555. for (i = 1;
  1556. h->delayed_pic[i] &&
  1557. !h->delayed_pic[i]->f.key_frame &&
  1558. !h->delayed_pic[i]->mmco_reset;
  1559. i++)
  1560. if (h->delayed_pic[i]->poc < out->poc) {
  1561. out = h->delayed_pic[i];
  1562. out_idx = i;
  1563. }
  1564. for (i = out_idx; h->delayed_pic[i]; i++)
  1565. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1566. if (out) {
  1567. out->reference &= ~DELAYED_PIC_REF;
  1568. ret = output_frame(h, pict, out);
  1569. if (ret < 0)
  1570. return ret;
  1571. *got_frame = 1;
  1572. }
  1573. return buf_index;
  1574. }
  1575. if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
  1576. int side_size;
  1577. uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  1578. if (is_extra(side, side_size))
  1579. ff_h264_decode_extradata(h, side, side_size);
  1580. }
  1581. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  1582. if (is_extra(buf, buf_size))
  1583. return ff_h264_decode_extradata(h, buf, buf_size);
  1584. }
  1585. buf_index = decode_nal_units(h, buf, buf_size, 0);
  1586. if (buf_index < 0)
  1587. return AVERROR_INVALIDDATA;
  1588. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1589. av_assert0(buf_index <= buf_size);
  1590. goto out;
  1591. }
  1592. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1593. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  1594. buf_size >= 4 && !memcmp("Q264", buf, 4))
  1595. return buf_size;
  1596. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1597. return AVERROR_INVALIDDATA;
  1598. }
  1599. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  1600. (h->mb_y >= h->mb_height && h->mb_height)) {
  1601. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  1602. decode_postinit(h, 1);
  1603. ff_h264_field_end(h, &h->slice_ctx[0], 0);
  1604. /* Wait for second field. */
  1605. *got_frame = 0;
  1606. if (h->next_output_pic && (
  1607. h->next_output_pic->recovered)) {
  1608. if (!h->next_output_pic->recovered)
  1609. h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
  1610. if (!h->avctx->hwaccel &&
  1611. (h->next_output_pic->field_poc[0] == INT_MAX ||
  1612. h->next_output_pic->field_poc[1] == INT_MAX)
  1613. ) {
  1614. int p;
  1615. AVFrame *f = &h->next_output_pic->f;
  1616. int field = h->next_output_pic->field_poc[0] == INT_MAX;
  1617. uint8_t *dst_data[4];
  1618. int linesizes[4];
  1619. const uint8_t *src_data[4];
  1620. av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
  1621. for (p = 0; p<4; p++) {
  1622. dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
  1623. src_data[p] = f->data[p] + field *f->linesize[p];
  1624. linesizes[p] = 2*f->linesize[p];
  1625. }
  1626. av_image_copy(dst_data, linesizes, src_data, linesizes,
  1627. f->format, f->width, f->height>>1);
  1628. }
  1629. ret = output_frame(h, pict, h->next_output_pic);
  1630. if (ret < 0)
  1631. return ret;
  1632. *got_frame = 1;
  1633. if (CONFIG_MPEGVIDEO) {
  1634. ff_print_debug_info2(h->avctx, pict, NULL,
  1635. h->next_output_pic->mb_type,
  1636. h->next_output_pic->qscale_table,
  1637. h->next_output_pic->motion_val,
  1638. &h->low_delay,
  1639. h->mb_width, h->mb_height, h->mb_stride, 1);
  1640. }
  1641. }
  1642. }
  1643. av_assert0(pict->buf[0] || !*got_frame);
  1644. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1645. return get_consumed_bytes(buf_index, buf_size);
  1646. }
  1647. av_cold void ff_h264_free_context(H264Context *h)
  1648. {
  1649. int i;
  1650. ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
  1651. av_freep(&h->slice_ctx);
  1652. h->nb_slice_ctx = 0;
  1653. for (i = 0; i < MAX_SPS_COUNT; i++)
  1654. av_freep(h->sps_buffers + i);
  1655. for (i = 0; i < MAX_PPS_COUNT; i++)
  1656. av_freep(h->pps_buffers + i);
  1657. }
  1658. static av_cold int h264_decode_end(AVCodecContext *avctx)
  1659. {
  1660. H264Context *h = avctx->priv_data;
  1661. ff_h264_remove_all_refs(h);
  1662. ff_h264_free_context(h);
  1663. ff_h264_unref_picture(h, &h->cur_pic);
  1664. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1665. return 0;
  1666. }
  1667. #define OFFSET(x) offsetof(H264Context, x)
  1668. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1669. static const AVOption h264_options[] = {
  1670. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  1671. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  1672. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VD },
  1673. { NULL },
  1674. };
  1675. static const AVClass h264_class = {
  1676. .class_name = "H264 Decoder",
  1677. .item_name = av_default_item_name,
  1678. .option = h264_options,
  1679. .version = LIBAVUTIL_VERSION_INT,
  1680. };
  1681. static const AVProfile profiles[] = {
  1682. { FF_PROFILE_H264_BASELINE, "Baseline" },
  1683. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  1684. { FF_PROFILE_H264_MAIN, "Main" },
  1685. { FF_PROFILE_H264_EXTENDED, "Extended" },
  1686. { FF_PROFILE_H264_HIGH, "High" },
  1687. { FF_PROFILE_H264_HIGH_10, "High 10" },
  1688. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  1689. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  1690. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  1691. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  1692. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  1693. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  1694. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  1695. { FF_PROFILE_UNKNOWN },
  1696. };
  1697. AVCodec ff_h264_decoder = {
  1698. .name = "h264",
  1699. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1700. .type = AVMEDIA_TYPE_VIDEO,
  1701. .id = AV_CODEC_ID_H264,
  1702. .priv_data_size = sizeof(H264Context),
  1703. .init = ff_h264_decode_init,
  1704. .close = h264_decode_end,
  1705. .decode = h264_decode_frame,
  1706. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  1707. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  1708. CODEC_CAP_FRAME_THREADS,
  1709. .flush = flush_dpb,
  1710. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1711. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1712. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1713. .priv_class = &h264_class,
  1714. };
  1715. #if CONFIG_H264_VDPAU_DECODER
  1716. static const AVClass h264_vdpau_class = {
  1717. .class_name = "H264 VDPAU Decoder",
  1718. .item_name = av_default_item_name,
  1719. .option = h264_options,
  1720. .version = LIBAVUTIL_VERSION_INT,
  1721. };
  1722. AVCodec ff_h264_vdpau_decoder = {
  1723. .name = "h264_vdpau",
  1724. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  1725. .type = AVMEDIA_TYPE_VIDEO,
  1726. .id = AV_CODEC_ID_H264,
  1727. .priv_data_size = sizeof(H264Context),
  1728. .init = ff_h264_decode_init,
  1729. .close = h264_decode_end,
  1730. .decode = h264_decode_frame,
  1731. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  1732. .flush = flush_dpb,
  1733. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  1734. AV_PIX_FMT_NONE},
  1735. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1736. .priv_class = &h264_vdpau_class,
  1737. };
  1738. #endif