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.

2021 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 (sl != h->slice_ctx) {
  438. memset(er, 0, sizeof(*er));
  439. } else
  440. if (CONFIG_ERROR_RESILIENCE) {
  441. /* init ER */
  442. er->avctx = h->avctx;
  443. er->decode_mb = h264_er_decode_mb;
  444. er->opaque = h;
  445. er->quarter_sample = 1;
  446. er->mb_num = h->mb_num;
  447. er->mb_width = h->mb_width;
  448. er->mb_height = h->mb_height;
  449. er->mb_stride = h->mb_stride;
  450. er->b8_stride = h->mb_width * 2 + 1;
  451. // error resilience code looks cleaner with this
  452. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  453. (h->mb_num + 1) * sizeof(int), fail);
  454. for (y = 0; y < h->mb_height; y++)
  455. for (x = 0; x < h->mb_width; x++)
  456. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  457. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  458. h->mb_stride + h->mb_width;
  459. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  460. mb_array_size * sizeof(uint8_t), fail);
  461. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  462. h->mb_height * h->mb_stride, fail);
  463. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  464. yc_size * sizeof(int16_t), fail);
  465. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  466. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  467. er->dc_val[2] = er->dc_val[1] + c_size;
  468. for (i = 0; i < yc_size; i++)
  469. sl->dc_val_base[i] = 1024;
  470. }
  471. return 0;
  472. fail:
  473. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  474. }
  475. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  476. int parse_extradata);
  477. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  478. {
  479. AVCodecContext *avctx = h->avctx;
  480. int ret;
  481. if (!buf || size <= 0)
  482. return -1;
  483. if (buf[0] == 1) {
  484. int i, cnt, nalsize;
  485. const unsigned char *p = buf;
  486. h->is_avc = 1;
  487. if (size < 7) {
  488. av_log(avctx, AV_LOG_ERROR,
  489. "avcC %d too short\n", size);
  490. return AVERROR_INVALIDDATA;
  491. }
  492. /* sps and pps in the avcC always have length coded with 2 bytes,
  493. * so put a fake nal_length_size = 2 while parsing them */
  494. h->nal_length_size = 2;
  495. // Decode sps from avcC
  496. cnt = *(p + 5) & 0x1f; // Number of sps
  497. p += 6;
  498. for (i = 0; i < cnt; i++) {
  499. nalsize = AV_RB16(p) + 2;
  500. if(nalsize > size - (p-buf))
  501. return AVERROR_INVALIDDATA;
  502. ret = decode_nal_units(h, p, nalsize, 1);
  503. if (ret < 0) {
  504. av_log(avctx, AV_LOG_ERROR,
  505. "Decoding sps %d from avcC failed\n", i);
  506. return ret;
  507. }
  508. p += nalsize;
  509. }
  510. // Decode pps from avcC
  511. cnt = *(p++); // Number of pps
  512. for (i = 0; i < cnt; i++) {
  513. nalsize = AV_RB16(p) + 2;
  514. if(nalsize > size - (p-buf))
  515. return AVERROR_INVALIDDATA;
  516. ret = decode_nal_units(h, p, nalsize, 1);
  517. if (ret < 0) {
  518. av_log(avctx, AV_LOG_ERROR,
  519. "Decoding pps %d from avcC failed\n", i);
  520. return ret;
  521. }
  522. p += nalsize;
  523. }
  524. // Store right nal length size that will be used to parse all other nals
  525. h->nal_length_size = (buf[4] & 0x03) + 1;
  526. } else {
  527. h->is_avc = 0;
  528. ret = decode_nal_units(h, buf, size, 1);
  529. if (ret < 0)
  530. return ret;
  531. }
  532. return size;
  533. }
  534. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  535. {
  536. int i;
  537. h->avctx = avctx;
  538. h->dequant_coeff_pps = -1;
  539. h->current_sps_id = -1;
  540. h->cur_chroma_format_idc = -1;
  541. h->picture_structure = PICT_FRAME;
  542. h->slice_context_count = 1;
  543. h->workaround_bugs = avctx->workaround_bugs;
  544. h->flags = avctx->flags;
  545. h->prev_poc_msb = 1 << 16;
  546. h->x264_build = -1;
  547. h->recovery_frame = -1;
  548. h->frame_recovered = 0;
  549. h->prev_frame_num = -1;
  550. h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
  551. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  552. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  553. h->last_pocs[i] = INT_MIN;
  554. ff_h264_reset_sei(h);
  555. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  556. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
  557. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  558. if (!h->slice_ctx) {
  559. h->nb_slice_ctx = 0;
  560. return AVERROR(ENOMEM);
  561. }
  562. for (i = 0; i < h->nb_slice_ctx; i++)
  563. h->slice_ctx[i].h264 = h;
  564. return 0;
  565. }
  566. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  567. {
  568. H264Context *h = avctx->priv_data;
  569. int ret;
  570. ret = h264_init_context(avctx, h);
  571. if (ret < 0)
  572. return ret;
  573. /* set defaults */
  574. if (!avctx->has_b_frames)
  575. h->low_delay = 1;
  576. ff_h264_decode_init_vlc();
  577. ff_init_cabac_states();
  578. if (avctx->codec_id == AV_CODEC_ID_H264) {
  579. if (avctx->ticks_per_frame == 1) {
  580. if(h->avctx->time_base.den < INT_MAX/2) {
  581. h->avctx->time_base.den *= 2;
  582. } else
  583. h->avctx->time_base.num /= 2;
  584. }
  585. avctx->ticks_per_frame = 2;
  586. }
  587. if (avctx->extradata_size > 0 && avctx->extradata) {
  588. ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
  589. if (ret < 0) {
  590. ff_h264_free_context(h);
  591. return ret;
  592. }
  593. }
  594. if (h->sps.bitstream_restriction_flag &&
  595. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  596. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  597. h->low_delay = 0;
  598. }
  599. avctx->internal->allocate_progress = 1;
  600. ff_h264_flush_change(h);
  601. if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
  602. h->enable_er = 0;
  603. if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  604. av_log(avctx, AV_LOG_WARNING,
  605. "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
  606. "Use it at your own risk\n");
  607. }
  608. return 0;
  609. }
  610. static int decode_init_thread_copy(AVCodecContext *avctx)
  611. {
  612. H264Context *h = avctx->priv_data;
  613. int ret;
  614. if (!avctx->internal->is_copy)
  615. return 0;
  616. memset(h, 0, sizeof(*h));
  617. ret = h264_init_context(avctx, h);
  618. if (ret < 0)
  619. return ret;
  620. h->context_initialized = 0;
  621. return 0;
  622. }
  623. /**
  624. * Run setup operations that must be run after slice header decoding.
  625. * This includes finding the next displayed frame.
  626. *
  627. * @param h h264 master context
  628. * @param setup_finished enough NALs have been read that we can call
  629. * ff_thread_finish_setup()
  630. */
  631. static void decode_postinit(H264Context *h, int setup_finished)
  632. {
  633. H264Picture *out = h->cur_pic_ptr;
  634. H264Picture *cur = h->cur_pic_ptr;
  635. int i, pics, out_of_order, out_idx;
  636. h->cur_pic_ptr->f.pict_type = h->pict_type;
  637. if (h->next_output_pic)
  638. return;
  639. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  640. /* FIXME: if we have two PAFF fields in one packet, we can't start
  641. * the next thread here. If we have one field per packet, we can.
  642. * The check in decode_nal_units() is not good enough to find this
  643. * yet, so we assume the worst for now. */
  644. // if (setup_finished)
  645. // ff_thread_finish_setup(h->avctx);
  646. if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
  647. return;
  648. if (h->avctx->hwaccel || h->missing_fields <=1)
  649. return;
  650. }
  651. cur->f.interlaced_frame = 0;
  652. cur->f.repeat_pict = 0;
  653. /* Signal interlacing information externally. */
  654. /* Prioritize picture timing SEI information over used
  655. * decoding process if it exists. */
  656. if (h->sps.pic_struct_present_flag) {
  657. switch (h->sei_pic_struct) {
  658. case SEI_PIC_STRUCT_FRAME:
  659. break;
  660. case SEI_PIC_STRUCT_TOP_FIELD:
  661. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  662. cur->f.interlaced_frame = 1;
  663. break;
  664. case SEI_PIC_STRUCT_TOP_BOTTOM:
  665. case SEI_PIC_STRUCT_BOTTOM_TOP:
  666. if (FIELD_OR_MBAFF_PICTURE(h))
  667. cur->f.interlaced_frame = 1;
  668. else
  669. // try to flag soft telecine progressive
  670. cur->f.interlaced_frame = h->prev_interlaced_frame;
  671. break;
  672. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  673. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  674. /* Signal the possibility of telecined film externally
  675. * (pic_struct 5,6). From these hints, let the applications
  676. * decide if they apply deinterlacing. */
  677. cur->f.repeat_pict = 1;
  678. break;
  679. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  680. cur->f.repeat_pict = 2;
  681. break;
  682. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  683. cur->f.repeat_pict = 4;
  684. break;
  685. }
  686. if ((h->sei_ct_type & 3) &&
  687. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  688. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  689. } else {
  690. /* Derive interlacing flag from used decoding process. */
  691. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  692. }
  693. h->prev_interlaced_frame = cur->f.interlaced_frame;
  694. if (cur->field_poc[0] != cur->field_poc[1]) {
  695. /* Derive top_field_first from field pocs. */
  696. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  697. } else {
  698. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  699. /* Use picture timing SEI information. Even if it is a
  700. * information of a past frame, better than nothing. */
  701. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  702. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  703. cur->f.top_field_first = 1;
  704. else
  705. cur->f.top_field_first = 0;
  706. } else {
  707. /* Most likely progressive */
  708. cur->f.top_field_first = 0;
  709. }
  710. }
  711. if (h->sei_frame_packing_present &&
  712. h->frame_packing_arrangement_type >= 0 &&
  713. h->frame_packing_arrangement_type <= 6 &&
  714. h->content_interpretation_type > 0 &&
  715. h->content_interpretation_type < 3) {
  716. AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
  717. if (stereo) {
  718. switch (h->frame_packing_arrangement_type) {
  719. case 0:
  720. stereo->type = AV_STEREO3D_CHECKERBOARD;
  721. break;
  722. case 1:
  723. stereo->type = AV_STEREO3D_COLUMNS;
  724. break;
  725. case 2:
  726. stereo->type = AV_STEREO3D_LINES;
  727. break;
  728. case 3:
  729. if (h->quincunx_subsampling)
  730. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  731. else
  732. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  733. break;
  734. case 4:
  735. stereo->type = AV_STEREO3D_TOPBOTTOM;
  736. break;
  737. case 5:
  738. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  739. break;
  740. case 6:
  741. stereo->type = AV_STEREO3D_2D;
  742. break;
  743. }
  744. if (h->content_interpretation_type == 2)
  745. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  746. }
  747. }
  748. if (h->sei_display_orientation_present &&
  749. (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
  750. double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
  751. AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
  752. AV_FRAME_DATA_DISPLAYMATRIX,
  753. sizeof(int32_t) * 9);
  754. if (rotation) {
  755. av_display_rotation_set((int32_t *)rotation->data, angle);
  756. av_display_matrix_flip((int32_t *)rotation->data,
  757. h->sei_hflip, h->sei_vflip);
  758. }
  759. }
  760. cur->mmco_reset = h->mmco_reset;
  761. h->mmco_reset = 0;
  762. // FIXME do something with unavailable reference frames
  763. /* Sort B-frames into display order */
  764. if (h->sps.bitstream_restriction_flag &&
  765. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  766. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  767. h->low_delay = 0;
  768. }
  769. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  770. !h->sps.bitstream_restriction_flag) {
  771. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  772. h->low_delay = 0;
  773. }
  774. for (i = 0; 1; i++) {
  775. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  776. if(i)
  777. h->last_pocs[i-1] = cur->poc;
  778. break;
  779. } else if(i) {
  780. h->last_pocs[i-1]= h->last_pocs[i];
  781. }
  782. }
  783. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  784. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  785. || (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))
  786. out_of_order = FFMAX(out_of_order, 1);
  787. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  788. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  789. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  790. h->last_pocs[i] = INT_MIN;
  791. h->last_pocs[0] = cur->poc;
  792. cur->mmco_reset = 1;
  793. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  794. av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  795. h->avctx->has_b_frames = out_of_order;
  796. h->low_delay = 0;
  797. }
  798. pics = 0;
  799. while (h->delayed_pic[pics])
  800. pics++;
  801. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  802. h->delayed_pic[pics++] = cur;
  803. if (cur->reference == 0)
  804. cur->reference = DELAYED_PIC_REF;
  805. out = h->delayed_pic[0];
  806. out_idx = 0;
  807. for (i = 1; h->delayed_pic[i] &&
  808. !h->delayed_pic[i]->f.key_frame &&
  809. !h->delayed_pic[i]->mmco_reset;
  810. i++)
  811. if (h->delayed_pic[i]->poc < out->poc) {
  812. out = h->delayed_pic[i];
  813. out_idx = i;
  814. }
  815. if (h->avctx->has_b_frames == 0 &&
  816. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  817. h->next_outputed_poc = INT_MIN;
  818. out_of_order = out->poc < h->next_outputed_poc;
  819. if (out_of_order || pics > h->avctx->has_b_frames) {
  820. out->reference &= ~DELAYED_PIC_REF;
  821. // for frame threading, the owner must be the second field's thread or
  822. // else the first thread can release the picture and reuse it unsafely
  823. for (i = out_idx; h->delayed_pic[i]; i++)
  824. h->delayed_pic[i] = h->delayed_pic[i + 1];
  825. }
  826. if (!out_of_order && pics > h->avctx->has_b_frames) {
  827. h->next_output_pic = out;
  828. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  829. h->next_outputed_poc = INT_MIN;
  830. } else
  831. h->next_outputed_poc = out->poc;
  832. } else {
  833. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  834. }
  835. if (h->next_output_pic) {
  836. if (h->next_output_pic->recovered) {
  837. // We have reached an recovery point and all frames after it in
  838. // display order are "recovered".
  839. h->frame_recovered |= FRAME_RECOVERED_SEI;
  840. }
  841. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  842. }
  843. if (setup_finished && !h->avctx->hwaccel)
  844. ff_thread_finish_setup(h->avctx);
  845. }
  846. int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
  847. {
  848. int list, i;
  849. int luma_def, chroma_def;
  850. sl->use_weight = 0;
  851. sl->use_weight_chroma = 0;
  852. sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
  853. if (h->sps.chroma_format_idc)
  854. sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
  855. if (sl->luma_log2_weight_denom > 7U) {
  856. av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
  857. sl->luma_log2_weight_denom = 0;
  858. }
  859. if (sl->chroma_log2_weight_denom > 7U) {
  860. av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
  861. sl->chroma_log2_weight_denom = 0;
  862. }
  863. luma_def = 1 << sl->luma_log2_weight_denom;
  864. chroma_def = 1 << sl->chroma_log2_weight_denom;
  865. for (list = 0; list < 2; list++) {
  866. sl->luma_weight_flag[list] = 0;
  867. sl->chroma_weight_flag[list] = 0;
  868. for (i = 0; i < sl->ref_count[list]; i++) {
  869. int luma_weight_flag, chroma_weight_flag;
  870. luma_weight_flag = get_bits1(&sl->gb);
  871. if (luma_weight_flag) {
  872. sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
  873. sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
  874. if (sl->luma_weight[i][list][0] != luma_def ||
  875. sl->luma_weight[i][list][1] != 0) {
  876. sl->use_weight = 1;
  877. sl->luma_weight_flag[list] = 1;
  878. }
  879. } else {
  880. sl->luma_weight[i][list][0] = luma_def;
  881. sl->luma_weight[i][list][1] = 0;
  882. }
  883. if (h->sps.chroma_format_idc) {
  884. chroma_weight_flag = get_bits1(&sl->gb);
  885. if (chroma_weight_flag) {
  886. int j;
  887. for (j = 0; j < 2; j++) {
  888. sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
  889. sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
  890. if (sl->chroma_weight[i][list][j][0] != chroma_def ||
  891. sl->chroma_weight[i][list][j][1] != 0) {
  892. sl->use_weight_chroma = 1;
  893. sl->chroma_weight_flag[list] = 1;
  894. }
  895. }
  896. } else {
  897. int j;
  898. for (j = 0; j < 2; j++) {
  899. sl->chroma_weight[i][list][j][0] = chroma_def;
  900. sl->chroma_weight[i][list][j][1] = 0;
  901. }
  902. }
  903. }
  904. }
  905. if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
  906. break;
  907. }
  908. sl->use_weight = sl->use_weight || sl->use_weight_chroma;
  909. return 0;
  910. }
  911. /**
  912. * instantaneous decoder refresh.
  913. */
  914. static void idr(H264Context *h)
  915. {
  916. int i;
  917. ff_h264_remove_all_refs(h);
  918. h->prev_frame_num =
  919. h->prev_frame_num_offset = 0;
  920. h->prev_poc_msb = 1<<16;
  921. h->prev_poc_lsb = 0;
  922. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  923. h->last_pocs[i] = INT_MIN;
  924. }
  925. /* forget old pics after a seek */
  926. void ff_h264_flush_change(H264Context *h)
  927. {
  928. int i, j;
  929. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  930. h->prev_interlaced_frame = 1;
  931. idr(h);
  932. h->prev_frame_num = -1;
  933. if (h->cur_pic_ptr) {
  934. h->cur_pic_ptr->reference = 0;
  935. for (j=i=0; h->delayed_pic[i]; i++)
  936. if (h->delayed_pic[i] != h->cur_pic_ptr)
  937. h->delayed_pic[j++] = h->delayed_pic[i];
  938. h->delayed_pic[j] = NULL;
  939. }
  940. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  941. h->first_field = 0;
  942. ff_h264_reset_sei(h);
  943. h->recovery_frame = -1;
  944. h->frame_recovered = 0;
  945. h->current_slice = 0;
  946. h->mmco_reset = 1;
  947. for (i = 0; i < h->nb_slice_ctx; i++)
  948. h->slice_ctx[i].list_count = 0;
  949. }
  950. /* forget old pics after a seek */
  951. static void flush_dpb(AVCodecContext *avctx)
  952. {
  953. H264Context *h = avctx->priv_data;
  954. int i;
  955. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  956. ff_h264_flush_change(h);
  957. if (h->DPB)
  958. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  959. ff_h264_unref_picture(h, &h->DPB[i]);
  960. h->cur_pic_ptr = NULL;
  961. ff_h264_unref_picture(h, &h->cur_pic);
  962. h->mb_y = 0;
  963. ff_h264_free_tables(h, 1);
  964. h->context_initialized = 0;
  965. }
  966. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  967. {
  968. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  969. int field_poc[2];
  970. h->frame_num_offset = h->prev_frame_num_offset;
  971. if (h->frame_num < h->prev_frame_num)
  972. h->frame_num_offset += max_frame_num;
  973. if (h->sps.poc_type == 0) {
  974. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  975. if (h->poc_lsb < h->prev_poc_lsb &&
  976. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  977. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  978. else if (h->poc_lsb > h->prev_poc_lsb &&
  979. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  980. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  981. else
  982. h->poc_msb = h->prev_poc_msb;
  983. field_poc[0] =
  984. field_poc[1] = h->poc_msb + h->poc_lsb;
  985. if (h->picture_structure == PICT_FRAME)
  986. field_poc[1] += h->delta_poc_bottom;
  987. } else if (h->sps.poc_type == 1) {
  988. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  989. int i;
  990. if (h->sps.poc_cycle_length != 0)
  991. abs_frame_num = h->frame_num_offset + h->frame_num;
  992. else
  993. abs_frame_num = 0;
  994. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  995. abs_frame_num--;
  996. expected_delta_per_poc_cycle = 0;
  997. for (i = 0; i < h->sps.poc_cycle_length; i++)
  998. // FIXME integrate during sps parse
  999. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  1000. if (abs_frame_num > 0) {
  1001. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1002. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1003. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1004. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1005. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1006. } else
  1007. expectedpoc = 0;
  1008. if (h->nal_ref_idc == 0)
  1009. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1010. field_poc[0] = expectedpoc + h->delta_poc[0];
  1011. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1012. if (h->picture_structure == PICT_FRAME)
  1013. field_poc[1] += h->delta_poc[1];
  1014. } else {
  1015. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1016. if (!h->nal_ref_idc)
  1017. poc--;
  1018. field_poc[0] = poc;
  1019. field_poc[1] = poc;
  1020. }
  1021. if (h->picture_structure != PICT_BOTTOM_FIELD)
  1022. pic_field_poc[0] = field_poc[0];
  1023. if (h->picture_structure != PICT_TOP_FIELD)
  1024. pic_field_poc[1] = field_poc[1];
  1025. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  1026. return 0;
  1027. }
  1028. /**
  1029. * Compute profile from profile_idc and constraint_set?_flags.
  1030. *
  1031. * @param sps SPS
  1032. *
  1033. * @return profile as defined by FF_PROFILE_H264_*
  1034. */
  1035. int ff_h264_get_profile(SPS *sps)
  1036. {
  1037. int profile = sps->profile_idc;
  1038. switch (sps->profile_idc) {
  1039. case FF_PROFILE_H264_BASELINE:
  1040. // constraint_set1_flag set to 1
  1041. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  1042. break;
  1043. case FF_PROFILE_H264_HIGH_10:
  1044. case FF_PROFILE_H264_HIGH_422:
  1045. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  1046. // constraint_set3_flag set to 1
  1047. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  1048. break;
  1049. }
  1050. return profile;
  1051. }
  1052. int ff_h264_set_parameter_from_sps(H264Context *h)
  1053. {
  1054. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  1055. (h->sps.bitstream_restriction_flag &&
  1056. !h->sps.num_reorder_frames)) {
  1057. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  1058. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  1059. "Reenabling low delay requires a codec flush.\n");
  1060. else
  1061. h->low_delay = 1;
  1062. }
  1063. if (h->avctx->has_b_frames < 2)
  1064. h->avctx->has_b_frames = !h->low_delay;
  1065. if (h->cur_bit_depth_luma != h->sps.bit_depth_luma ||
  1066. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  1067. if (h->avctx->codec &&
  1068. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  1069. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  1070. av_log(h->avctx, AV_LOG_ERROR,
  1071. "VDPAU decoding does not support video colorspace.\n");
  1072. return AVERROR_INVALIDDATA;
  1073. }
  1074. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
  1075. h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
  1076. h->cur_bit_depth_luma =
  1077. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  1078. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  1079. h->pixel_shift = h->sps.bit_depth_luma > 8;
  1080. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  1081. h->sps.chroma_format_idc);
  1082. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  1083. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  1084. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  1085. h->sps.chroma_format_idc);
  1086. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  1087. } else {
  1088. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
  1089. h->sps.bit_depth_luma);
  1090. return AVERROR_INVALIDDATA;
  1091. }
  1092. }
  1093. return 0;
  1094. }
  1095. int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
  1096. {
  1097. int ref_count[2], list_count;
  1098. int num_ref_idx_active_override_flag;
  1099. // set defaults, might be overridden a few lines later
  1100. ref_count[0] = h->pps.ref_count[0];
  1101. ref_count[1] = h->pps.ref_count[1];
  1102. if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1103. unsigned max[2];
  1104. max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
  1105. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1106. sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
  1107. num_ref_idx_active_override_flag = get_bits1(&sl->gb);
  1108. if (num_ref_idx_active_override_flag) {
  1109. ref_count[0] = get_ue_golomb(&sl->gb) + 1;
  1110. if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  1111. ref_count[1] = get_ue_golomb(&sl->gb) + 1;
  1112. } else
  1113. // full range is spec-ok in this case, even for frames
  1114. ref_count[1] = 1;
  1115. }
  1116. if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
  1117. 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]);
  1118. sl->ref_count[0] = sl->ref_count[1] = 0;
  1119. sl->list_count = 0;
  1120. return AVERROR_INVALIDDATA;
  1121. }
  1122. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1123. list_count = 2;
  1124. else
  1125. list_count = 1;
  1126. } else {
  1127. list_count = 0;
  1128. ref_count[0] = ref_count[1] = 0;
  1129. }
  1130. if (list_count != sl->list_count ||
  1131. ref_count[0] != sl->ref_count[0] ||
  1132. ref_count[1] != sl->ref_count[1]) {
  1133. sl->ref_count[0] = ref_count[0];
  1134. sl->ref_count[1] = ref_count[1];
  1135. sl->list_count = list_count;
  1136. return 1;
  1137. }
  1138. return 0;
  1139. }
  1140. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  1141. static int get_bit_length(H264Context *h, const uint8_t *buf,
  1142. const uint8_t *ptr, int dst_length,
  1143. int i, int next_avc)
  1144. {
  1145. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  1146. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  1147. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  1148. h->workaround_bugs |= FF_BUG_TRUNCATED;
  1149. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  1150. while (dst_length > 0 && ptr[dst_length - 1] == 0)
  1151. dst_length--;
  1152. if (!dst_length)
  1153. return 0;
  1154. return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
  1155. }
  1156. static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
  1157. {
  1158. int next_avc = h->is_avc ? 0 : buf_size;
  1159. int nal_index = 0;
  1160. int buf_index = 0;
  1161. int nals_needed = 0;
  1162. int first_slice = 0;
  1163. while(1) {
  1164. GetBitContext gb;
  1165. int nalsize = 0;
  1166. int dst_length, bit_length, consumed;
  1167. const uint8_t *ptr;
  1168. if (buf_index >= next_avc) {
  1169. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1170. if (nalsize < 0)
  1171. break;
  1172. next_avc = buf_index + nalsize;
  1173. } else {
  1174. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1175. if (buf_index >= buf_size)
  1176. break;
  1177. if (buf_index >= next_avc)
  1178. continue;
  1179. }
  1180. ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
  1181. next_avc - buf_index);
  1182. if (!ptr || dst_length < 0)
  1183. return AVERROR_INVALIDDATA;
  1184. buf_index += consumed;
  1185. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1186. buf_index, next_avc);
  1187. nal_index++;
  1188. /* packets can sometimes contain multiple PPS/SPS,
  1189. * e.g. two PAFF field pictures in one packet, or a demuxer
  1190. * which splits NALs strangely if so, when frame threading we
  1191. * can't start the next thread until we've read all of them */
  1192. switch (h->nal_unit_type) {
  1193. case NAL_SPS:
  1194. case NAL_PPS:
  1195. nals_needed = nal_index;
  1196. break;
  1197. case NAL_DPA:
  1198. case NAL_IDR_SLICE:
  1199. case NAL_SLICE:
  1200. init_get_bits(&gb, ptr, bit_length);
  1201. if (!get_ue_golomb(&gb) ||
  1202. !first_slice ||
  1203. first_slice != h->nal_unit_type)
  1204. nals_needed = nal_index;
  1205. if (!first_slice)
  1206. first_slice = h->nal_unit_type;
  1207. }
  1208. }
  1209. return nals_needed;
  1210. }
  1211. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  1212. int parse_extradata)
  1213. {
  1214. AVCodecContext *const avctx = h->avctx;
  1215. H264SliceContext *sl;
  1216. int buf_index;
  1217. unsigned context_count;
  1218. int next_avc;
  1219. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  1220. int nal_index;
  1221. int idr_cleared=0;
  1222. int ret = 0;
  1223. h->nal_unit_type= 0;
  1224. if(!h->slice_context_count)
  1225. h->slice_context_count= 1;
  1226. h->max_contexts = h->slice_context_count;
  1227. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  1228. h->current_slice = 0;
  1229. if (!h->first_field)
  1230. h->cur_pic_ptr = NULL;
  1231. ff_h264_reset_sei(h);
  1232. }
  1233. if (h->nal_length_size == 4) {
  1234. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  1235. h->is_avc = 0;
  1236. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  1237. h->is_avc = 1;
  1238. }
  1239. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1240. nals_needed = get_last_needed_nal(h, buf, buf_size);
  1241. {
  1242. buf_index = 0;
  1243. context_count = 0;
  1244. next_avc = h->is_avc ? 0 : buf_size;
  1245. nal_index = 0;
  1246. for (;;) {
  1247. int consumed;
  1248. int dst_length;
  1249. int bit_length;
  1250. const uint8_t *ptr;
  1251. int nalsize = 0;
  1252. int err;
  1253. if (buf_index >= next_avc) {
  1254. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1255. if (nalsize < 0)
  1256. break;
  1257. next_avc = buf_index + nalsize;
  1258. } else {
  1259. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1260. if (buf_index >= buf_size)
  1261. break;
  1262. if (buf_index >= next_avc)
  1263. continue;
  1264. }
  1265. sl = &h->slice_ctx[context_count];
  1266. ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
  1267. &consumed, next_avc - buf_index);
  1268. if (!ptr || dst_length < 0) {
  1269. ret = -1;
  1270. goto end;
  1271. }
  1272. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1273. buf_index + consumed, next_avc);
  1274. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  1275. av_log(h->avctx, AV_LOG_DEBUG,
  1276. "NAL %d/%d at %d/%d length %d\n",
  1277. h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
  1278. if (h->is_avc && (nalsize != consumed) && nalsize)
  1279. av_log(h->avctx, AV_LOG_DEBUG,
  1280. "AVC: Consumed only %d bytes instead of %d\n",
  1281. consumed, nalsize);
  1282. buf_index += consumed;
  1283. nal_index++;
  1284. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  1285. h->nal_ref_idc == 0 &&
  1286. h->nal_unit_type != NAL_SEI)
  1287. continue;
  1288. again:
  1289. /* Ignore per frame NAL unit type during extradata
  1290. * parsing. Decoding slices is not possible in codec init
  1291. * with frame-mt */
  1292. if (parse_extradata) {
  1293. switch (h->nal_unit_type) {
  1294. case NAL_IDR_SLICE:
  1295. case NAL_SLICE:
  1296. case NAL_DPA:
  1297. case NAL_DPB:
  1298. case NAL_DPC:
  1299. av_log(h->avctx, AV_LOG_WARNING,
  1300. "Ignoring NAL %d in global header/extradata\n",
  1301. h->nal_unit_type);
  1302. // fall through to next case
  1303. case NAL_AUXILIARY_SLICE:
  1304. h->nal_unit_type = NAL_FF_IGNORE;
  1305. }
  1306. }
  1307. err = 0;
  1308. switch (h->nal_unit_type) {
  1309. case NAL_IDR_SLICE:
  1310. if ((ptr[0] & 0xFC) == 0x98) {
  1311. av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
  1312. h->next_outputed_poc = INT_MIN;
  1313. ret = -1;
  1314. goto end;
  1315. }
  1316. if (h->nal_unit_type != NAL_IDR_SLICE) {
  1317. av_log(h->avctx, AV_LOG_ERROR,
  1318. "Invalid mix of idr and non-idr slices\n");
  1319. ret = -1;
  1320. goto end;
  1321. }
  1322. if(!idr_cleared) {
  1323. if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  1324. av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
  1325. ret = AVERROR_INVALIDDATA;
  1326. goto end;
  1327. }
  1328. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  1329. }
  1330. idr_cleared = 1;
  1331. h->has_recovery_point = 1;
  1332. case NAL_SLICE:
  1333. init_get_bits(&sl->gb, ptr, bit_length);
  1334. if ( nals_needed >= nal_index
  1335. || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
  1336. h->au_pps_id = -1;
  1337. if ((err = ff_h264_decode_slice_header(h, sl)))
  1338. break;
  1339. if (h->sei_recovery_frame_cnt >= 0) {
  1340. if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
  1341. h->valid_recovery_point = 1;
  1342. if ( h->recovery_frame < 0
  1343. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
  1344. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
  1345. ((1 << h->sps.log2_max_frame_num) - 1);
  1346. if (!h->valid_recovery_point)
  1347. h->recovery_frame = h->frame_num;
  1348. }
  1349. }
  1350. h->cur_pic_ptr->f.key_frame |=
  1351. (h->nal_unit_type == NAL_IDR_SLICE);
  1352. if (h->nal_unit_type == NAL_IDR_SLICE ||
  1353. h->recovery_frame == h->frame_num) {
  1354. h->recovery_frame = -1;
  1355. h->cur_pic_ptr->recovered = 1;
  1356. }
  1357. // If we have an IDR, all frames after it in decoded order are
  1358. // "recovered".
  1359. if (h->nal_unit_type == NAL_IDR_SLICE)
  1360. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1361. h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
  1362. h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
  1363. #if 1
  1364. h->cur_pic_ptr->recovered |= h->frame_recovered;
  1365. #else
  1366. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1367. #endif
  1368. if (h->current_slice == 1) {
  1369. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  1370. decode_postinit(h, nal_index >= nals_needed);
  1371. if (h->avctx->hwaccel &&
  1372. (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
  1373. goto end;
  1374. if (CONFIG_H264_VDPAU_DECODER &&
  1375. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  1376. ff_vdpau_h264_picture_start(h);
  1377. }
  1378. if (sl->redundant_pic_count == 0) {
  1379. if (avctx->hwaccel) {
  1380. ret = avctx->hwaccel->decode_slice(avctx,
  1381. &buf[buf_index - consumed],
  1382. consumed);
  1383. if (ret < 0)
  1384. goto end;
  1385. } else if (CONFIG_H264_VDPAU_DECODER &&
  1386. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  1387. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  1388. start_code,
  1389. sizeof(start_code));
  1390. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  1391. &buf[buf_index - consumed],
  1392. consumed);
  1393. } else
  1394. context_count++;
  1395. }
  1396. break;
  1397. case NAL_DPA:
  1398. case NAL_DPB:
  1399. case NAL_DPC:
  1400. avpriv_request_sample(avctx, "data partitioning");
  1401. ret = AVERROR(ENOSYS);
  1402. goto end;
  1403. break;
  1404. case NAL_SEI:
  1405. init_get_bits(&h->gb, ptr, bit_length);
  1406. ret = ff_h264_decode_sei(h);
  1407. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1408. goto end;
  1409. break;
  1410. case NAL_SPS:
  1411. init_get_bits(&h->gb, ptr, bit_length);
  1412. if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
  1413. break;
  1414. if (h->is_avc ? nalsize : 1) {
  1415. av_log(h->avctx, AV_LOG_DEBUG,
  1416. "SPS decoding failure, trying again with the complete NAL\n");
  1417. if (h->is_avc)
  1418. av_assert0(next_avc - buf_index + consumed == nalsize);
  1419. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  1420. break;
  1421. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  1422. 8*(next_avc - buf_index + consumed - 1));
  1423. if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
  1424. break;
  1425. }
  1426. init_get_bits(&h->gb, ptr, bit_length);
  1427. ff_h264_decode_seq_parameter_set(h, 1);
  1428. break;
  1429. case NAL_PPS:
  1430. init_get_bits(&h->gb, ptr, bit_length);
  1431. ret = ff_h264_decode_picture_parameter_set(h, bit_length);
  1432. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1433. goto end;
  1434. break;
  1435. case NAL_AUD:
  1436. case NAL_END_SEQUENCE:
  1437. case NAL_END_STREAM:
  1438. case NAL_FILLER_DATA:
  1439. case NAL_SPS_EXT:
  1440. case NAL_AUXILIARY_SLICE:
  1441. break;
  1442. case NAL_FF_IGNORE:
  1443. break;
  1444. default:
  1445. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  1446. h->nal_unit_type, bit_length);
  1447. }
  1448. if (context_count == h->max_contexts) {
  1449. ret = ff_h264_execute_decode_slices(h, context_count);
  1450. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1451. goto end;
  1452. context_count = 0;
  1453. }
  1454. if (err < 0 || err == SLICE_SKIPED) {
  1455. if (err < 0)
  1456. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  1457. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  1458. } else if (err == SLICE_SINGLETHREAD) {
  1459. if (context_count > 1) {
  1460. ret = ff_h264_execute_decode_slices(h, context_count - 1);
  1461. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1462. goto end;
  1463. context_count = 0;
  1464. }
  1465. /* Slice could not be decoded in parallel mode, restart. Note
  1466. * that rbsp_buffer is not transferred, but since we no longer
  1467. * run in parallel mode this should not be an issue. */
  1468. sl = &h->slice_ctx[0];
  1469. goto again;
  1470. }
  1471. }
  1472. }
  1473. if (context_count) {
  1474. ret = ff_h264_execute_decode_slices(h, context_count);
  1475. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1476. goto end;
  1477. }
  1478. ret = 0;
  1479. end:
  1480. /* clean up */
  1481. if (h->cur_pic_ptr && !h->droppable) {
  1482. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1483. h->picture_structure == PICT_BOTTOM_FIELD);
  1484. }
  1485. return (ret < 0) ? ret : buf_index;
  1486. }
  1487. /**
  1488. * Return the number of bytes consumed for building the current frame.
  1489. */
  1490. static int get_consumed_bytes(int pos, int buf_size)
  1491. {
  1492. if (pos == 0)
  1493. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  1494. if (pos + 10 > buf_size)
  1495. pos = buf_size; // oops ;)
  1496. return pos;
  1497. }
  1498. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  1499. {
  1500. AVFrame *src = &srcp->f;
  1501. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  1502. int i;
  1503. int ret = av_frame_ref(dst, src);
  1504. if (ret < 0)
  1505. return ret;
  1506. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
  1507. if (srcp->sei_recovery_frame_cnt == 0)
  1508. dst->key_frame = 1;
  1509. if (!srcp->crop)
  1510. return 0;
  1511. for (i = 0; i < desc->nb_components; i++) {
  1512. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  1513. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  1514. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  1515. (srcp->crop_top >> vshift) * dst->linesize[i];
  1516. dst->data[i] += off;
  1517. }
  1518. return 0;
  1519. }
  1520. static int is_extra(const uint8_t *buf, int buf_size)
  1521. {
  1522. int cnt= buf[5]&0x1f;
  1523. const uint8_t *p= buf+6;
  1524. while(cnt--){
  1525. int nalsize= AV_RB16(p) + 2;
  1526. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  1527. return 0;
  1528. p += nalsize;
  1529. }
  1530. cnt = *(p++);
  1531. if(!cnt)
  1532. return 0;
  1533. while(cnt--){
  1534. int nalsize= AV_RB16(p) + 2;
  1535. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  1536. return 0;
  1537. p += nalsize;
  1538. }
  1539. return 1;
  1540. }
  1541. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1542. int *got_frame, AVPacket *avpkt)
  1543. {
  1544. const uint8_t *buf = avpkt->data;
  1545. int buf_size = avpkt->size;
  1546. H264Context *h = avctx->priv_data;
  1547. AVFrame *pict = data;
  1548. int buf_index = 0;
  1549. H264Picture *out;
  1550. int i, out_idx;
  1551. int ret;
  1552. h->flags = avctx->flags;
  1553. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1554. /* end of stream, output what is still in the buffers */
  1555. if (buf_size == 0) {
  1556. out:
  1557. h->cur_pic_ptr = NULL;
  1558. h->first_field = 0;
  1559. // FIXME factorize this with the output code below
  1560. out = h->delayed_pic[0];
  1561. out_idx = 0;
  1562. for (i = 1;
  1563. h->delayed_pic[i] &&
  1564. !h->delayed_pic[i]->f.key_frame &&
  1565. !h->delayed_pic[i]->mmco_reset;
  1566. i++)
  1567. if (h->delayed_pic[i]->poc < out->poc) {
  1568. out = h->delayed_pic[i];
  1569. out_idx = i;
  1570. }
  1571. for (i = out_idx; h->delayed_pic[i]; i++)
  1572. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1573. if (out) {
  1574. out->reference &= ~DELAYED_PIC_REF;
  1575. ret = output_frame(h, pict, out);
  1576. if (ret < 0)
  1577. return ret;
  1578. *got_frame = 1;
  1579. }
  1580. return buf_index;
  1581. }
  1582. if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
  1583. int side_size;
  1584. uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  1585. if (is_extra(side, side_size))
  1586. ff_h264_decode_extradata(h, side, side_size);
  1587. }
  1588. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  1589. if (is_extra(buf, buf_size))
  1590. return ff_h264_decode_extradata(h, buf, buf_size);
  1591. }
  1592. buf_index = decode_nal_units(h, buf, buf_size, 0);
  1593. if (buf_index < 0)
  1594. return AVERROR_INVALIDDATA;
  1595. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1596. av_assert0(buf_index <= buf_size);
  1597. goto out;
  1598. }
  1599. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1600. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  1601. buf_size >= 4 && !memcmp("Q264", buf, 4))
  1602. return buf_size;
  1603. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1604. return AVERROR_INVALIDDATA;
  1605. }
  1606. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  1607. (h->mb_y >= h->mb_height && h->mb_height)) {
  1608. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  1609. decode_postinit(h, 1);
  1610. ff_h264_field_end(h, &h->slice_ctx[0], 0);
  1611. /* Wait for second field. */
  1612. *got_frame = 0;
  1613. if (h->next_output_pic && (
  1614. h->next_output_pic->recovered)) {
  1615. if (!h->next_output_pic->recovered)
  1616. h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
  1617. if (!h->avctx->hwaccel &&
  1618. (h->next_output_pic->field_poc[0] == INT_MAX ||
  1619. h->next_output_pic->field_poc[1] == INT_MAX)
  1620. ) {
  1621. int p;
  1622. AVFrame *f = &h->next_output_pic->f;
  1623. int field = h->next_output_pic->field_poc[0] == INT_MAX;
  1624. uint8_t *dst_data[4];
  1625. int linesizes[4];
  1626. const uint8_t *src_data[4];
  1627. av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
  1628. for (p = 0; p<4; p++) {
  1629. dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
  1630. src_data[p] = f->data[p] + field *f->linesize[p];
  1631. linesizes[p] = 2*f->linesize[p];
  1632. }
  1633. av_image_copy(dst_data, linesizes, src_data, linesizes,
  1634. f->format, f->width, f->height>>1);
  1635. }
  1636. ret = output_frame(h, pict, h->next_output_pic);
  1637. if (ret < 0)
  1638. return ret;
  1639. *got_frame = 1;
  1640. if (CONFIG_MPEGVIDEO) {
  1641. ff_print_debug_info2(h->avctx, pict, NULL,
  1642. h->next_output_pic->mb_type,
  1643. h->next_output_pic->qscale_table,
  1644. h->next_output_pic->motion_val,
  1645. &h->low_delay,
  1646. h->mb_width, h->mb_height, h->mb_stride, 1);
  1647. }
  1648. }
  1649. }
  1650. av_assert0(pict->buf[0] || !*got_frame);
  1651. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1652. return get_consumed_bytes(buf_index, buf_size);
  1653. }
  1654. av_cold void ff_h264_free_context(H264Context *h)
  1655. {
  1656. int i;
  1657. ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
  1658. av_freep(&h->slice_ctx);
  1659. h->nb_slice_ctx = 0;
  1660. for (i = 0; i < MAX_SPS_COUNT; i++)
  1661. av_freep(h->sps_buffers + i);
  1662. for (i = 0; i < MAX_PPS_COUNT; i++)
  1663. av_freep(h->pps_buffers + i);
  1664. }
  1665. static av_cold int h264_decode_end(AVCodecContext *avctx)
  1666. {
  1667. H264Context *h = avctx->priv_data;
  1668. ff_h264_remove_all_refs(h);
  1669. ff_h264_free_context(h);
  1670. ff_h264_unref_picture(h, &h->cur_pic);
  1671. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1672. return 0;
  1673. }
  1674. #define OFFSET(x) offsetof(H264Context, x)
  1675. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1676. static const AVOption h264_options[] = {
  1677. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  1678. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  1679. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VD },
  1680. { NULL },
  1681. };
  1682. static const AVClass h264_class = {
  1683. .class_name = "H264 Decoder",
  1684. .item_name = av_default_item_name,
  1685. .option = h264_options,
  1686. .version = LIBAVUTIL_VERSION_INT,
  1687. };
  1688. static const AVProfile profiles[] = {
  1689. { FF_PROFILE_H264_BASELINE, "Baseline" },
  1690. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  1691. { FF_PROFILE_H264_MAIN, "Main" },
  1692. { FF_PROFILE_H264_EXTENDED, "Extended" },
  1693. { FF_PROFILE_H264_HIGH, "High" },
  1694. { FF_PROFILE_H264_HIGH_10, "High 10" },
  1695. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  1696. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  1697. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  1698. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  1699. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  1700. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  1701. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  1702. { FF_PROFILE_UNKNOWN },
  1703. };
  1704. AVCodec ff_h264_decoder = {
  1705. .name = "h264",
  1706. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1707. .type = AVMEDIA_TYPE_VIDEO,
  1708. .id = AV_CODEC_ID_H264,
  1709. .priv_data_size = sizeof(H264Context),
  1710. .init = ff_h264_decode_init,
  1711. .close = h264_decode_end,
  1712. .decode = h264_decode_frame,
  1713. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  1714. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  1715. CODEC_CAP_FRAME_THREADS,
  1716. .flush = flush_dpb,
  1717. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1718. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1719. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1720. .priv_class = &h264_class,
  1721. };
  1722. #if CONFIG_H264_VDPAU_DECODER
  1723. static const AVClass h264_vdpau_class = {
  1724. .class_name = "H264 VDPAU Decoder",
  1725. .item_name = av_default_item_name,
  1726. .option = h264_options,
  1727. .version = LIBAVUTIL_VERSION_INT,
  1728. };
  1729. AVCodec ff_h264_vdpau_decoder = {
  1730. .name = "h264_vdpau",
  1731. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  1732. .type = AVMEDIA_TYPE_VIDEO,
  1733. .id = AV_CODEC_ID_H264,
  1734. .priv_data_size = sizeof(H264Context),
  1735. .init = ff_h264_decode_init,
  1736. .close = h264_decode_end,
  1737. .decode = h264_decode_frame,
  1738. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  1739. .flush = flush_dpb,
  1740. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  1741. AV_PIX_FMT_NONE},
  1742. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1743. .priv_class = &h264_vdpau_class,
  1744. };
  1745. #endif