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.

1670 lines
56KB

  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 "bytestream.h"
  35. #include "cabac.h"
  36. #include "cabac_functions.h"
  37. #include "error_resilience.h"
  38. #include "avcodec.h"
  39. #include "h264.h"
  40. #include "h2645_parse.h"
  41. #include "h264data.h"
  42. #include "h264chroma.h"
  43. #include "h264_mvpred.h"
  44. #include "golomb.h"
  45. #include "mathops.h"
  46. #include "me_cmp.h"
  47. #include "mpegutils.h"
  48. #include "profiles.h"
  49. #include "rectangle.h"
  50. #include "thread.h"
  51. #include "vdpau_compat.h"
  52. static int h264_decode_end(AVCodecContext *avctx);
  53. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  54. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  55. {
  56. H264Context *h = avctx->priv_data;
  57. return h ? h->sps.num_reorder_frames : 0;
  58. }
  59. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  60. int (*mv)[2][4][2],
  61. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  62. {
  63. H264Context *h = opaque;
  64. H264SliceContext *sl = &h->slice_ctx[0];
  65. sl->mb_x = mb_x;
  66. sl->mb_y = mb_y;
  67. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  68. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  69. av_assert1(ref >= 0);
  70. /* FIXME: It is possible albeit uncommon that slice references
  71. * differ between slices. We take the easy approach and ignore
  72. * it for now. If this turns out to have any relevance in
  73. * practice then correct remapping should be added. */
  74. if (ref >= sl->ref_count[0])
  75. ref = 0;
  76. if (!sl->ref_list[0][ref].data[0]) {
  77. av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
  78. ref = 0;
  79. }
  80. if ((sl->ref_list[0][ref].reference&3) != 3) {
  81. av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
  82. return;
  83. }
  84. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  85. 2, 2, 2, ref, 1);
  86. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  87. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  88. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  89. sl->mb_mbaff =
  90. sl->mb_field_decoding_flag = 0;
  91. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  92. }
  93. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  94. int y, int height)
  95. {
  96. AVCodecContext *avctx = h->avctx;
  97. const AVFrame *src = h->cur_pic.f;
  98. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  99. int vshift = desc->log2_chroma_h;
  100. const int field_pic = h->picture_structure != PICT_FRAME;
  101. if (field_pic) {
  102. height <<= 1;
  103. y <<= 1;
  104. }
  105. height = FFMIN(height, avctx->height - y);
  106. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  107. return;
  108. if (avctx->draw_horiz_band) {
  109. int offset[AV_NUM_DATA_POINTERS];
  110. int i;
  111. offset[0] = y * src->linesize[0];
  112. offset[1] =
  113. offset[2] = (y >> vshift) * src->linesize[1];
  114. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  115. offset[i] = 0;
  116. emms_c();
  117. avctx->draw_horiz_band(avctx, src, offset,
  118. y, h->picture_structure, height);
  119. }
  120. }
  121. void ff_h264_free_tables(H264Context *h)
  122. {
  123. int i;
  124. av_freep(&h->intra4x4_pred_mode);
  125. av_freep(&h->chroma_pred_mode_table);
  126. av_freep(&h->cbp_table);
  127. av_freep(&h->mvd_table[0]);
  128. av_freep(&h->mvd_table[1]);
  129. av_freep(&h->direct_table);
  130. av_freep(&h->non_zero_count);
  131. av_freep(&h->slice_table_base);
  132. h->slice_table = NULL;
  133. av_freep(&h->list_counts);
  134. av_freep(&h->mb2b_xy);
  135. av_freep(&h->mb2br_xy);
  136. av_buffer_pool_uninit(&h->qscale_table_pool);
  137. av_buffer_pool_uninit(&h->mb_type_pool);
  138. av_buffer_pool_uninit(&h->motion_val_pool);
  139. av_buffer_pool_uninit(&h->ref_index_pool);
  140. for (i = 0; i < h->nb_slice_ctx; i++) {
  141. H264SliceContext *sl = &h->slice_ctx[i];
  142. av_freep(&sl->dc_val_base);
  143. av_freep(&sl->er.mb_index2xy);
  144. av_freep(&sl->er.error_status_table);
  145. av_freep(&sl->er.er_temp_buffer);
  146. av_freep(&sl->bipred_scratchpad);
  147. av_freep(&sl->edge_emu_buffer);
  148. av_freep(&sl->top_borders[0]);
  149. av_freep(&sl->top_borders[1]);
  150. sl->bipred_scratchpad_allocated = 0;
  151. sl->edge_emu_buffer_allocated = 0;
  152. sl->top_borders_allocated[0] = 0;
  153. sl->top_borders_allocated[1] = 0;
  154. }
  155. }
  156. int ff_h264_alloc_tables(H264Context *h)
  157. {
  158. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  159. const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
  160. int x, y;
  161. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  162. row_mb_num, 8 * sizeof(uint8_t), fail)
  163. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  164. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  165. big_mb_num * 48 * sizeof(uint8_t), fail)
  166. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  167. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  168. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  169. big_mb_num * sizeof(uint16_t), fail)
  170. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  171. big_mb_num * sizeof(uint8_t), fail)
  172. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
  173. row_mb_num, 16 * sizeof(uint8_t), fail);
  174. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
  175. row_mb_num, 16 * sizeof(uint8_t), fail);
  176. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  177. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  178. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  179. 4 * big_mb_num * sizeof(uint8_t), fail);
  180. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  181. big_mb_num * sizeof(uint8_t), fail)
  182. memset(h->slice_table_base, -1,
  183. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  184. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  185. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  186. big_mb_num * sizeof(uint32_t), fail);
  187. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  188. big_mb_num * sizeof(uint32_t), fail);
  189. for (y = 0; y < h->mb_height; y++)
  190. for (x = 0; x < h->mb_width; x++) {
  191. const int mb_xy = x + y * h->mb_stride;
  192. const int b_xy = 4 * x + 4 * y * h->b_stride;
  193. h->mb2b_xy[mb_xy] = b_xy;
  194. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  195. }
  196. if (!h->dequant4_coeff[0])
  197. ff_h264_init_dequant_tables(h);
  198. return 0;
  199. fail:
  200. ff_h264_free_tables(h);
  201. return AVERROR(ENOMEM);
  202. }
  203. /**
  204. * Init context
  205. * Allocate buffers which are not shared amongst multiple threads.
  206. */
  207. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  208. {
  209. ERContext *er = &sl->er;
  210. int mb_array_size = h->mb_height * h->mb_stride;
  211. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  212. int c_size = h->mb_stride * (h->mb_height + 1);
  213. int yc_size = y_size + 2 * c_size;
  214. int x, y, i;
  215. sl->ref_cache[0][scan8[5] + 1] =
  216. sl->ref_cache[0][scan8[7] + 1] =
  217. sl->ref_cache[0][scan8[13] + 1] =
  218. sl->ref_cache[1][scan8[5] + 1] =
  219. sl->ref_cache[1][scan8[7] + 1] =
  220. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  221. if (sl != h->slice_ctx) {
  222. memset(er, 0, sizeof(*er));
  223. } else
  224. if (CONFIG_ERROR_RESILIENCE) {
  225. /* init ER */
  226. er->avctx = h->avctx;
  227. er->decode_mb = h264_er_decode_mb;
  228. er->opaque = h;
  229. er->quarter_sample = 1;
  230. er->mb_num = h->mb_num;
  231. er->mb_width = h->mb_width;
  232. er->mb_height = h->mb_height;
  233. er->mb_stride = h->mb_stride;
  234. er->b8_stride = h->mb_width * 2 + 1;
  235. // error resilience code looks cleaner with this
  236. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  237. (h->mb_num + 1) * sizeof(int), fail);
  238. for (y = 0; y < h->mb_height; y++)
  239. for (x = 0; x < h->mb_width; x++)
  240. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  241. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  242. h->mb_stride + h->mb_width;
  243. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  244. mb_array_size * sizeof(uint8_t), fail);
  245. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  246. h->mb_height * h->mb_stride, fail);
  247. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  248. yc_size * sizeof(int16_t), fail);
  249. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  250. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  251. er->dc_val[2] = er->dc_val[1] + c_size;
  252. for (i = 0; i < yc_size; i++)
  253. sl->dc_val_base[i] = 1024;
  254. }
  255. return 0;
  256. fail:
  257. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  258. }
  259. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  260. int parse_extradata);
  261. /* There are (invalid) samples in the wild with mp4-style extradata, where the
  262. * parameter sets are stored unescaped (i.e. as RBSP).
  263. * This function catches the parameter set decoding failure and tries again
  264. * after escaping it */
  265. static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
  266. {
  267. int ret;
  268. ret = decode_nal_units(h, buf, buf_size, 1);
  269. if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
  270. GetByteContext gbc;
  271. PutByteContext pbc;
  272. uint8_t *escaped_buf;
  273. int escaped_buf_size;
  274. av_log(h->avctx, AV_LOG_WARNING,
  275. "SPS decoding failure, trying again after escaping the NAL\n");
  276. if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
  277. return AVERROR(ERANGE);
  278. escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
  279. escaped_buf = av_mallocz(escaped_buf_size);
  280. if (!escaped_buf)
  281. return AVERROR(ENOMEM);
  282. bytestream2_init(&gbc, buf, buf_size);
  283. bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
  284. while (bytestream2_get_bytes_left(&gbc)) {
  285. if (bytestream2_get_bytes_left(&gbc) >= 3 &&
  286. bytestream2_peek_be24(&gbc) <= 3) {
  287. bytestream2_put_be24(&pbc, 3);
  288. bytestream2_skip(&gbc, 2);
  289. } else
  290. bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
  291. }
  292. escaped_buf_size = bytestream2_tell_p(&pbc);
  293. AV_WB16(escaped_buf, escaped_buf_size - 2);
  294. ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
  295. av_freep(&escaped_buf);
  296. if (ret < 0)
  297. return ret;
  298. }
  299. return 0;
  300. }
  301. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  302. {
  303. AVCodecContext *avctx = h->avctx;
  304. int ret;
  305. if (!buf || size <= 0)
  306. return -1;
  307. if (buf[0] == 1) {
  308. int i, cnt, nalsize;
  309. const unsigned char *p = buf;
  310. h->is_avc = 1;
  311. if (size < 7) {
  312. av_log(avctx, AV_LOG_ERROR,
  313. "avcC %d too short\n", size);
  314. return AVERROR_INVALIDDATA;
  315. }
  316. /* sps and pps in the avcC always have length coded with 2 bytes,
  317. * so put a fake nal_length_size = 2 while parsing them */
  318. h->nal_length_size = 2;
  319. // Decode sps from avcC
  320. cnt = *(p + 5) & 0x1f; // Number of sps
  321. p += 6;
  322. for (i = 0; i < cnt; i++) {
  323. nalsize = AV_RB16(p) + 2;
  324. if(nalsize > size - (p-buf))
  325. return AVERROR_INVALIDDATA;
  326. ret = decode_extradata_ps_mp4(h, p, nalsize);
  327. if (ret < 0) {
  328. av_log(avctx, AV_LOG_ERROR,
  329. "Decoding sps %d from avcC failed\n", i);
  330. return ret;
  331. }
  332. p += nalsize;
  333. }
  334. // Decode pps from avcC
  335. cnt = *(p++); // Number of pps
  336. for (i = 0; i < cnt; i++) {
  337. nalsize = AV_RB16(p) + 2;
  338. if(nalsize > size - (p-buf))
  339. return AVERROR_INVALIDDATA;
  340. ret = decode_extradata_ps_mp4(h, p, nalsize);
  341. if (ret < 0) {
  342. av_log(avctx, AV_LOG_ERROR,
  343. "Decoding pps %d from avcC failed\n", i);
  344. return ret;
  345. }
  346. p += nalsize;
  347. }
  348. // Store right nal length size that will be used to parse all other nals
  349. h->nal_length_size = (buf[4] & 0x03) + 1;
  350. } else {
  351. h->is_avc = 0;
  352. ret = decode_nal_units(h, buf, size, 1);
  353. if (ret < 0)
  354. return ret;
  355. }
  356. return size;
  357. }
  358. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  359. {
  360. int i;
  361. h->avctx = avctx;
  362. h->backup_width = -1;
  363. h->backup_height = -1;
  364. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  365. h->dequant_coeff_pps = -1;
  366. h->current_sps_id = -1;
  367. h->cur_chroma_format_idc = -1;
  368. h->picture_structure = PICT_FRAME;
  369. h->slice_context_count = 1;
  370. h->workaround_bugs = avctx->workaround_bugs;
  371. h->flags = avctx->flags;
  372. h->prev_poc_msb = 1 << 16;
  373. h->x264_build = -1;
  374. h->recovery_frame = -1;
  375. h->frame_recovered = 0;
  376. h->prev_frame_num = -1;
  377. h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
  378. h->next_outputed_poc = INT_MIN;
  379. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  380. h->last_pocs[i] = INT_MIN;
  381. ff_h264_reset_sei(h);
  382. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  383. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
  384. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  385. if (!h->slice_ctx) {
  386. h->nb_slice_ctx = 0;
  387. return AVERROR(ENOMEM);
  388. }
  389. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  390. h->DPB[i].f = av_frame_alloc();
  391. if (!h->DPB[i].f)
  392. return AVERROR(ENOMEM);
  393. }
  394. h->cur_pic.f = av_frame_alloc();
  395. if (!h->cur_pic.f)
  396. return AVERROR(ENOMEM);
  397. h->last_pic_for_ec.f = av_frame_alloc();
  398. if (!h->last_pic_for_ec.f)
  399. return AVERROR(ENOMEM);
  400. for (i = 0; i < h->nb_slice_ctx; i++)
  401. h->slice_ctx[i].h264 = h;
  402. return 0;
  403. }
  404. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  405. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  406. {
  407. H264Context *h = avctx->priv_data;
  408. int ret;
  409. ret = h264_init_context(avctx, h);
  410. if (ret < 0)
  411. return ret;
  412. /* set defaults */
  413. if (!avctx->has_b_frames)
  414. h->low_delay = 1;
  415. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  416. if (ret != 0) {
  417. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  418. return AVERROR_UNKNOWN;
  419. }
  420. if (avctx->codec_id == AV_CODEC_ID_H264) {
  421. if (avctx->ticks_per_frame == 1) {
  422. if(h->avctx->time_base.den < INT_MAX/2) {
  423. h->avctx->time_base.den *= 2;
  424. } else
  425. h->avctx->time_base.num /= 2;
  426. }
  427. avctx->ticks_per_frame = 2;
  428. }
  429. if (avctx->extradata_size > 0 && avctx->extradata) {
  430. ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
  431. if (ret < 0) {
  432. h264_decode_end(avctx);
  433. return ret;
  434. }
  435. }
  436. if (h->sps.bitstream_restriction_flag &&
  437. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  438. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  439. h->low_delay = 0;
  440. }
  441. avctx->internal->allocate_progress = 1;
  442. ff_h264_flush_change(h);
  443. if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
  444. h->enable_er = 0;
  445. if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  446. av_log(avctx, AV_LOG_WARNING,
  447. "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
  448. "Use it at your own risk\n");
  449. }
  450. return 0;
  451. }
  452. #if HAVE_THREADS
  453. static int decode_init_thread_copy(AVCodecContext *avctx)
  454. {
  455. H264Context *h = avctx->priv_data;
  456. int ret;
  457. if (!avctx->internal->is_copy)
  458. return 0;
  459. memset(h, 0, sizeof(*h));
  460. ret = h264_init_context(avctx, h);
  461. if (ret < 0)
  462. return ret;
  463. h->context_initialized = 0;
  464. return 0;
  465. }
  466. #endif
  467. /**
  468. * Run setup operations that must be run after slice header decoding.
  469. * This includes finding the next displayed frame.
  470. *
  471. * @param h h264 master context
  472. * @param setup_finished enough NALs have been read that we can call
  473. * ff_thread_finish_setup()
  474. */
  475. static void decode_postinit(H264Context *h, int setup_finished)
  476. {
  477. H264Picture *out = h->cur_pic_ptr;
  478. H264Picture *cur = h->cur_pic_ptr;
  479. int i, pics, out_of_order, out_idx;
  480. h->cur_pic_ptr->f->pict_type = h->pict_type;
  481. if (h->next_output_pic)
  482. return;
  483. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  484. /* FIXME: if we have two PAFF fields in one packet, we can't start
  485. * the next thread here. If we have one field per packet, we can.
  486. * The check in decode_nal_units() is not good enough to find this
  487. * yet, so we assume the worst for now. */
  488. // if (setup_finished)
  489. // ff_thread_finish_setup(h->avctx);
  490. if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
  491. return;
  492. if (h->avctx->hwaccel || h->missing_fields <=1)
  493. return;
  494. }
  495. cur->f->interlaced_frame = 0;
  496. cur->f->repeat_pict = 0;
  497. /* Signal interlacing information externally. */
  498. /* Prioritize picture timing SEI information over used
  499. * decoding process if it exists. */
  500. if (h->sps.pic_struct_present_flag) {
  501. switch (h->sei_pic_struct) {
  502. case SEI_PIC_STRUCT_FRAME:
  503. break;
  504. case SEI_PIC_STRUCT_TOP_FIELD:
  505. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  506. cur->f->interlaced_frame = 1;
  507. break;
  508. case SEI_PIC_STRUCT_TOP_BOTTOM:
  509. case SEI_PIC_STRUCT_BOTTOM_TOP:
  510. if (FIELD_OR_MBAFF_PICTURE(h))
  511. cur->f->interlaced_frame = 1;
  512. else
  513. // try to flag soft telecine progressive
  514. cur->f->interlaced_frame = h->prev_interlaced_frame;
  515. break;
  516. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  517. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  518. /* Signal the possibility of telecined film externally
  519. * (pic_struct 5,6). From these hints, let the applications
  520. * decide if they apply deinterlacing. */
  521. cur->f->repeat_pict = 1;
  522. break;
  523. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  524. cur->f->repeat_pict = 2;
  525. break;
  526. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  527. cur->f->repeat_pict = 4;
  528. break;
  529. }
  530. if ((h->sei_ct_type & 3) &&
  531. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  532. cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  533. } else {
  534. /* Derive interlacing flag from used decoding process. */
  535. cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  536. }
  537. h->prev_interlaced_frame = cur->f->interlaced_frame;
  538. if (cur->field_poc[0] != cur->field_poc[1]) {
  539. /* Derive top_field_first from field pocs. */
  540. cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  541. } else {
  542. if (h->sps.pic_struct_present_flag) {
  543. /* Use picture timing SEI information. Even if it is a
  544. * information of a past frame, better than nothing. */
  545. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  546. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  547. cur->f->top_field_first = 1;
  548. else
  549. cur->f->top_field_first = 0;
  550. } else if (cur->f->interlaced_frame) {
  551. /* Default to top field first when pic_struct_present_flag
  552. * is not set but interlaced frame detected */
  553. cur->f->top_field_first = 1;
  554. } else {
  555. /* Most likely progressive */
  556. cur->f->top_field_first = 0;
  557. }
  558. }
  559. if (h->sei_frame_packing_present &&
  560. h->frame_packing_arrangement_type >= 0 &&
  561. h->frame_packing_arrangement_type <= 6 &&
  562. h->content_interpretation_type > 0 &&
  563. h->content_interpretation_type < 3) {
  564. AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
  565. if (stereo) {
  566. switch (h->frame_packing_arrangement_type) {
  567. case 0:
  568. stereo->type = AV_STEREO3D_CHECKERBOARD;
  569. break;
  570. case 1:
  571. stereo->type = AV_STEREO3D_COLUMNS;
  572. break;
  573. case 2:
  574. stereo->type = AV_STEREO3D_LINES;
  575. break;
  576. case 3:
  577. if (h->quincunx_subsampling)
  578. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  579. else
  580. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  581. break;
  582. case 4:
  583. stereo->type = AV_STEREO3D_TOPBOTTOM;
  584. break;
  585. case 5:
  586. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  587. break;
  588. case 6:
  589. stereo->type = AV_STEREO3D_2D;
  590. break;
  591. }
  592. if (h->content_interpretation_type == 2)
  593. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  594. }
  595. }
  596. if (h->sei_display_orientation_present &&
  597. (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
  598. double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
  599. AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
  600. AV_FRAME_DATA_DISPLAYMATRIX,
  601. sizeof(int32_t) * 9);
  602. if (rotation) {
  603. av_display_rotation_set((int32_t *)rotation->data, angle);
  604. av_display_matrix_flip((int32_t *)rotation->data,
  605. h->sei_hflip, h->sei_vflip);
  606. }
  607. }
  608. if (h->sei_reguserdata_afd_present) {
  609. AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
  610. sizeof(uint8_t));
  611. if (sd) {
  612. *sd->data = h->active_format_description;
  613. h->sei_reguserdata_afd_present = 0;
  614. }
  615. }
  616. if (h->a53_caption) {
  617. AVFrameSideData *sd = av_frame_new_side_data(cur->f,
  618. AV_FRAME_DATA_A53_CC,
  619. h->a53_caption_size);
  620. if (sd)
  621. memcpy(sd->data, h->a53_caption, h->a53_caption_size);
  622. av_freep(&h->a53_caption);
  623. h->a53_caption_size = 0;
  624. h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
  625. }
  626. cur->mmco_reset = h->mmco_reset;
  627. h->mmco_reset = 0;
  628. // FIXME do something with unavailable reference frames
  629. /* Sort B-frames into display order */
  630. if (h->sps.bitstream_restriction_flag ||
  631. h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  632. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
  633. }
  634. h->low_delay = !h->avctx->has_b_frames;
  635. for (i = 0; 1; i++) {
  636. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  637. if(i)
  638. h->last_pocs[i-1] = cur->poc;
  639. break;
  640. } else if(i) {
  641. h->last_pocs[i-1]= h->last_pocs[i];
  642. }
  643. }
  644. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  645. if( cur->f->pict_type == AV_PICTURE_TYPE_B
  646. || (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))
  647. out_of_order = FFMAX(out_of_order, 1);
  648. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  649. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  650. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  651. h->last_pocs[i] = INT_MIN;
  652. h->last_pocs[0] = cur->poc;
  653. cur->mmco_reset = 1;
  654. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  655. av_log(h->avctx, AV_LOG_INFO, "Increasing reorder buffer to %d\n", out_of_order);
  656. h->avctx->has_b_frames = out_of_order;
  657. h->low_delay = 0;
  658. }
  659. pics = 0;
  660. while (h->delayed_pic[pics])
  661. pics++;
  662. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  663. h->delayed_pic[pics++] = cur;
  664. if (cur->reference == 0)
  665. cur->reference = DELAYED_PIC_REF;
  666. out = h->delayed_pic[0];
  667. out_idx = 0;
  668. for (i = 1; h->delayed_pic[i] &&
  669. !h->delayed_pic[i]->f->key_frame &&
  670. !h->delayed_pic[i]->mmco_reset;
  671. i++)
  672. if (h->delayed_pic[i]->poc < out->poc) {
  673. out = h->delayed_pic[i];
  674. out_idx = i;
  675. }
  676. if (h->avctx->has_b_frames == 0 &&
  677. (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
  678. h->next_outputed_poc = INT_MIN;
  679. out_of_order = out->poc < h->next_outputed_poc;
  680. if (out_of_order || pics > h->avctx->has_b_frames) {
  681. out->reference &= ~DELAYED_PIC_REF;
  682. // for frame threading, the owner must be the second field's thread or
  683. // else the first thread can release the picture and reuse it unsafely
  684. for (i = out_idx; h->delayed_pic[i]; i++)
  685. h->delayed_pic[i] = h->delayed_pic[i + 1];
  686. }
  687. if (!out_of_order && pics > h->avctx->has_b_frames) {
  688. h->next_output_pic = out;
  689. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
  690. h->next_outputed_poc = INT_MIN;
  691. } else
  692. h->next_outputed_poc = out->poc;
  693. } else {
  694. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  695. }
  696. if (h->next_output_pic) {
  697. if (h->next_output_pic->recovered) {
  698. // We have reached an recovery point and all frames after it in
  699. // display order are "recovered".
  700. h->frame_recovered |= FRAME_RECOVERED_SEI;
  701. }
  702. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  703. }
  704. if (setup_finished && !h->avctx->hwaccel) {
  705. ff_thread_finish_setup(h->avctx);
  706. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  707. h->setup_finished = 1;
  708. }
  709. }
  710. /**
  711. * instantaneous decoder refresh.
  712. */
  713. static void idr(H264Context *h)
  714. {
  715. int i;
  716. ff_h264_remove_all_refs(h);
  717. h->prev_frame_num =
  718. h->prev_frame_num_offset = 0;
  719. h->prev_poc_msb = 1<<16;
  720. h->prev_poc_lsb = 0;
  721. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  722. h->last_pocs[i] = INT_MIN;
  723. }
  724. /* forget old pics after a seek */
  725. void ff_h264_flush_change(H264Context *h)
  726. {
  727. int i, j;
  728. h->next_outputed_poc = INT_MIN;
  729. h->prev_interlaced_frame = 1;
  730. idr(h);
  731. h->prev_frame_num = -1;
  732. if (h->cur_pic_ptr) {
  733. h->cur_pic_ptr->reference = 0;
  734. for (j=i=0; h->delayed_pic[i]; i++)
  735. if (h->delayed_pic[i] != h->cur_pic_ptr)
  736. h->delayed_pic[j++] = h->delayed_pic[i];
  737. h->delayed_pic[j] = NULL;
  738. }
  739. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  740. h->first_field = 0;
  741. ff_h264_reset_sei(h);
  742. h->recovery_frame = -1;
  743. h->frame_recovered = 0;
  744. h->current_slice = 0;
  745. h->mmco_reset = 1;
  746. for (i = 0; i < h->nb_slice_ctx; i++)
  747. h->slice_ctx[i].list_count = 0;
  748. }
  749. /* forget old pics after a seek */
  750. static void flush_dpb(AVCodecContext *avctx)
  751. {
  752. H264Context *h = avctx->priv_data;
  753. int i;
  754. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  755. ff_h264_flush_change(h);
  756. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  757. ff_h264_unref_picture(h, &h->DPB[i]);
  758. h->cur_pic_ptr = NULL;
  759. ff_h264_unref_picture(h, &h->cur_pic);
  760. h->mb_y = 0;
  761. ff_h264_free_tables(h);
  762. h->context_initialized = 0;
  763. }
  764. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  765. {
  766. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  767. int field_poc[2];
  768. h->frame_num_offset = h->prev_frame_num_offset;
  769. if (h->frame_num < h->prev_frame_num)
  770. h->frame_num_offset += max_frame_num;
  771. if (h->sps.poc_type == 0) {
  772. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  773. if (h->poc_lsb < h->prev_poc_lsb &&
  774. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  775. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  776. else if (h->poc_lsb > h->prev_poc_lsb &&
  777. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  778. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  779. else
  780. h->poc_msb = h->prev_poc_msb;
  781. field_poc[0] =
  782. field_poc[1] = h->poc_msb + h->poc_lsb;
  783. if (h->picture_structure == PICT_FRAME)
  784. field_poc[1] += h->delta_poc_bottom;
  785. } else if (h->sps.poc_type == 1) {
  786. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  787. int i;
  788. if (h->sps.poc_cycle_length != 0)
  789. abs_frame_num = h->frame_num_offset + h->frame_num;
  790. else
  791. abs_frame_num = 0;
  792. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  793. abs_frame_num--;
  794. expected_delta_per_poc_cycle = 0;
  795. for (i = 0; i < h->sps.poc_cycle_length; i++)
  796. // FIXME integrate during sps parse
  797. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  798. if (abs_frame_num > 0) {
  799. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  800. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  801. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  802. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  803. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  804. } else
  805. expectedpoc = 0;
  806. if (h->nal_ref_idc == 0)
  807. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  808. field_poc[0] = expectedpoc + h->delta_poc[0];
  809. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  810. if (h->picture_structure == PICT_FRAME)
  811. field_poc[1] += h->delta_poc[1];
  812. } else {
  813. int poc = 2 * (h->frame_num_offset + h->frame_num);
  814. if (!h->nal_ref_idc)
  815. poc--;
  816. field_poc[0] = poc;
  817. field_poc[1] = poc;
  818. }
  819. if (h->picture_structure != PICT_BOTTOM_FIELD)
  820. pic_field_poc[0] = field_poc[0];
  821. if (h->picture_structure != PICT_TOP_FIELD)
  822. pic_field_poc[1] = field_poc[1];
  823. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  824. return 0;
  825. }
  826. /**
  827. * Compute profile from profile_idc and constraint_set?_flags.
  828. *
  829. * @param sps SPS
  830. *
  831. * @return profile as defined by FF_PROFILE_H264_*
  832. */
  833. int ff_h264_get_profile(SPS *sps)
  834. {
  835. int profile = sps->profile_idc;
  836. switch (sps->profile_idc) {
  837. case FF_PROFILE_H264_BASELINE:
  838. // constraint_set1_flag set to 1
  839. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  840. break;
  841. case FF_PROFILE_H264_HIGH_10:
  842. case FF_PROFILE_H264_HIGH_422:
  843. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  844. // constraint_set3_flag set to 1
  845. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  846. break;
  847. }
  848. return profile;
  849. }
  850. #if FF_API_CAP_VDPAU
  851. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  852. #endif
  853. static int get_last_needed_nal(H264Context *h)
  854. {
  855. int nals_needed = 0;
  856. int first_slice = 0;
  857. int i;
  858. int ret;
  859. for (i = 0; i < h->pkt.nb_nals; i++) {
  860. H2645NAL *nal = &h->pkt.nals[i];
  861. GetBitContext gb;
  862. /* packets can sometimes contain multiple PPS/SPS,
  863. * e.g. two PAFF field pictures in one packet, or a demuxer
  864. * which splits NALs strangely if so, when frame threading we
  865. * can't start the next thread until we've read all of them */
  866. switch (nal->type) {
  867. case NAL_SPS:
  868. case NAL_PPS:
  869. nals_needed = i;
  870. break;
  871. case NAL_DPA:
  872. case NAL_IDR_SLICE:
  873. case NAL_SLICE:
  874. ret = init_get_bits8(&gb, nal->data + 1, (nal->size - 1));
  875. if (ret < 0)
  876. return ret;
  877. if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
  878. !first_slice ||
  879. first_slice != nal->type)
  880. nals_needed = i;
  881. if (!first_slice)
  882. first_slice = nal->type;
  883. }
  884. }
  885. return nals_needed;
  886. }
  887. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  888. int parse_extradata)
  889. {
  890. AVCodecContext *const avctx = h->avctx;
  891. unsigned context_count = 0;
  892. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  893. int idr_cleared=0;
  894. int i, ret = 0;
  895. h->nal_unit_type= 0;
  896. if(!h->slice_context_count)
  897. h->slice_context_count= 1;
  898. h->max_contexts = h->slice_context_count;
  899. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  900. h->current_slice = 0;
  901. if (!h->first_field)
  902. h->cur_pic_ptr = NULL;
  903. ff_h264_reset_sei(h);
  904. }
  905. if (h->nal_length_size == 4) {
  906. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  907. h->is_avc = 0;
  908. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  909. h->is_avc = 1;
  910. }
  911. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  912. h->nal_length_size, avctx->codec_id);
  913. if (ret < 0) {
  914. av_log(avctx, AV_LOG_ERROR,
  915. "Error splitting the input into NAL units.\n");
  916. /* don't consider NAL parsing failure a fatal error when parsing extradata, as the stream may work without it */
  917. return parse_extradata ? buf_size : ret;
  918. }
  919. if (avctx->active_thread_type & FF_THREAD_FRAME)
  920. nals_needed = get_last_needed_nal(h);
  921. if (nals_needed < 0)
  922. return nals_needed;
  923. for (i = 0; i < h->pkt.nb_nals; i++) {
  924. H2645NAL *nal = &h->pkt.nals[i];
  925. H264SliceContext *sl = &h->slice_ctx[context_count];
  926. int err;
  927. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  928. nal->ref_idc == 0 && nal->type != NAL_SEI)
  929. continue;
  930. again:
  931. /* Ignore per frame NAL unit type during extradata
  932. * parsing. Decoding slices is not possible in codec init
  933. * with frame-mt */
  934. if (parse_extradata) {
  935. switch (nal->type) {
  936. case NAL_IDR_SLICE:
  937. case NAL_SLICE:
  938. case NAL_DPA:
  939. case NAL_DPB:
  940. case NAL_DPC:
  941. av_log(h->avctx, AV_LOG_WARNING,
  942. "Ignoring NAL %d in global header/extradata\n",
  943. nal->type);
  944. // fall through to next case
  945. case NAL_AUXILIARY_SLICE:
  946. nal->type = NAL_FF_IGNORE;
  947. }
  948. }
  949. // FIXME these should stop being context-global variables
  950. h->nal_ref_idc = nal->ref_idc;
  951. h->nal_unit_type = nal->type;
  952. err = 0;
  953. switch (nal->type) {
  954. case NAL_IDR_SLICE:
  955. if ((nal->data[1] & 0xFC) == 0x98) {
  956. av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
  957. h->next_outputed_poc = INT_MIN;
  958. ret = -1;
  959. goto end;
  960. }
  961. if (nal->type != NAL_IDR_SLICE) {
  962. av_log(h->avctx, AV_LOG_ERROR,
  963. "Invalid mix of idr and non-idr slices\n");
  964. ret = -1;
  965. goto end;
  966. }
  967. if(!idr_cleared) {
  968. if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  969. av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
  970. ret = AVERROR_INVALIDDATA;
  971. goto end;
  972. }
  973. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  974. }
  975. idr_cleared = 1;
  976. h->has_recovery_point = 1;
  977. case NAL_SLICE:
  978. sl->gb = nal->gb;
  979. if ( nals_needed >= i
  980. || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
  981. h->au_pps_id = -1;
  982. if ((err = ff_h264_decode_slice_header(h, sl)))
  983. break;
  984. if (h->sei_recovery_frame_cnt >= 0) {
  985. if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
  986. h->valid_recovery_point = 1;
  987. if ( h->recovery_frame < 0
  988. || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
  989. h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
  990. if (!h->valid_recovery_point)
  991. h->recovery_frame = h->frame_num;
  992. }
  993. }
  994. h->cur_pic_ptr->f->key_frame |= (nal->type == NAL_IDR_SLICE);
  995. if (nal->type == NAL_IDR_SLICE ||
  996. (h->recovery_frame == h->frame_num && nal->ref_idc)) {
  997. h->recovery_frame = -1;
  998. h->cur_pic_ptr->recovered = 1;
  999. }
  1000. // If we have an IDR, all frames after it in decoded order are
  1001. // "recovered".
  1002. if (nal->type == NAL_IDR_SLICE)
  1003. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1004. #if 1
  1005. h->cur_pic_ptr->recovered |= h->frame_recovered;
  1006. #else
  1007. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1008. #endif
  1009. if (h->current_slice == 1) {
  1010. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  1011. decode_postinit(h, i >= nals_needed);
  1012. if (h->avctx->hwaccel &&
  1013. (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
  1014. goto end;
  1015. #if FF_API_CAP_VDPAU
  1016. if (CONFIG_H264_VDPAU_DECODER &&
  1017. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
  1018. ff_vdpau_h264_picture_start(h);
  1019. #endif
  1020. }
  1021. if (sl->redundant_pic_count == 0) {
  1022. if (avctx->hwaccel) {
  1023. ret = avctx->hwaccel->decode_slice(avctx,
  1024. nal->raw_data,
  1025. nal->raw_size);
  1026. if (ret < 0)
  1027. goto end;
  1028. #if FF_API_CAP_VDPAU
  1029. } else if (CONFIG_H264_VDPAU_DECODER &&
  1030. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
  1031. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  1032. start_code,
  1033. sizeof(start_code));
  1034. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  1035. nal->raw_data,
  1036. nal->raw_size);
  1037. #endif
  1038. } else
  1039. context_count++;
  1040. }
  1041. break;
  1042. case NAL_DPA:
  1043. case NAL_DPB:
  1044. case NAL_DPC:
  1045. avpriv_request_sample(avctx, "data partitioning");
  1046. break;
  1047. case NAL_SEI:
  1048. h->gb = nal->gb;
  1049. ret = ff_h264_decode_sei(h);
  1050. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1051. goto end;
  1052. break;
  1053. case NAL_SPS:
  1054. h->gb = nal->gb;
  1055. if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
  1056. break;
  1057. av_log(h->avctx, AV_LOG_DEBUG,
  1058. "SPS decoding failure, trying again with the complete NAL\n");
  1059. init_get_bits8(&h->gb, nal->raw_data + 1, nal->raw_size - 1);
  1060. if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
  1061. break;
  1062. h->gb = nal->gb;
  1063. ff_h264_decode_seq_parameter_set(h, 1);
  1064. break;
  1065. case NAL_PPS:
  1066. h->gb = nal->gb;
  1067. ret = ff_h264_decode_picture_parameter_set(h, nal->size_bits);
  1068. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1069. goto end;
  1070. break;
  1071. case NAL_AUD:
  1072. case NAL_END_SEQUENCE:
  1073. case NAL_END_STREAM:
  1074. case NAL_FILLER_DATA:
  1075. case NAL_SPS_EXT:
  1076. case NAL_AUXILIARY_SLICE:
  1077. break;
  1078. case NAL_FF_IGNORE:
  1079. break;
  1080. default:
  1081. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  1082. nal->type, nal->size_bits);
  1083. }
  1084. if (context_count == h->max_contexts) {
  1085. ret = ff_h264_execute_decode_slices(h, context_count);
  1086. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1087. goto end;
  1088. context_count = 0;
  1089. }
  1090. if (err < 0 || err == SLICE_SKIPED) {
  1091. if (err < 0)
  1092. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  1093. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  1094. } else if (err == SLICE_SINGLETHREAD) {
  1095. ret = ff_h264_execute_decode_slices(h, context_count);
  1096. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1097. goto end;
  1098. context_count = 0;
  1099. /* Slice could not be decoded in parallel mode, restart. Note
  1100. * that rbsp_buffer is not transferred, but since we no longer
  1101. * run in parallel mode this should not be an issue. */
  1102. sl = &h->slice_ctx[0];
  1103. goto again;
  1104. }
  1105. }
  1106. if (context_count) {
  1107. ret = ff_h264_execute_decode_slices(h, context_count);
  1108. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1109. goto end;
  1110. }
  1111. ret = 0;
  1112. end:
  1113. #if CONFIG_ERROR_RESILIENCE
  1114. /*
  1115. * FIXME: Error handling code does not seem to support interlaced
  1116. * when slices span multiple rows
  1117. * The ff_er_add_slice calls don't work right for bottom
  1118. * fields; they cause massive erroneous error concealing
  1119. * Error marking covers both fields (top and bottom).
  1120. * This causes a mismatched s->error_count
  1121. * and a bad error table. Further, the error count goes to
  1122. * INT_MAX when called for bottom field, because mb_y is
  1123. * past end by one (callers fault) and resync_mb_y != 0
  1124. * causes problems for the first MB line, too.
  1125. */
  1126. if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new && h->enable_er) {
  1127. H264SliceContext *sl = h->slice_ctx;
  1128. int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
  1129. ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
  1130. if (use_last_pic) {
  1131. ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
  1132. sl->ref_list[0][0].parent = &h->last_pic_for_ec;
  1133. memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
  1134. memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
  1135. sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
  1136. } else if (sl->ref_count[0]) {
  1137. ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
  1138. } else
  1139. ff_h264_set_erpic(&sl->er.last_pic, NULL);
  1140. if (sl->ref_count[1])
  1141. ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
  1142. sl->er.ref_count = sl->ref_count[0];
  1143. ff_er_frame_end(&sl->er);
  1144. if (use_last_pic)
  1145. memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
  1146. }
  1147. #endif /* CONFIG_ERROR_RESILIENCE */
  1148. /* clean up */
  1149. if (h->cur_pic_ptr && !h->droppable) {
  1150. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1151. h->picture_structure == PICT_BOTTOM_FIELD);
  1152. }
  1153. return (ret < 0) ? ret : buf_size;
  1154. }
  1155. /**
  1156. * Return the number of bytes consumed for building the current frame.
  1157. */
  1158. static int get_consumed_bytes(int pos, int buf_size)
  1159. {
  1160. if (pos == 0)
  1161. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  1162. if (pos + 10 > buf_size)
  1163. pos = buf_size; // oops ;)
  1164. return pos;
  1165. }
  1166. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  1167. {
  1168. AVFrame *src = srcp->f;
  1169. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  1170. int i;
  1171. int ret = av_frame_ref(dst, src);
  1172. if (ret < 0)
  1173. return ret;
  1174. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
  1175. h->backup_width = h->avctx->width;
  1176. h->backup_height = h->avctx->height;
  1177. h->backup_pix_fmt = h->avctx->pix_fmt;
  1178. h->avctx->width = dst->width;
  1179. h->avctx->height = dst->height;
  1180. h->avctx->pix_fmt = dst->format;
  1181. if (srcp->sei_recovery_frame_cnt == 0)
  1182. dst->key_frame = 1;
  1183. if (!srcp->crop)
  1184. return 0;
  1185. for (i = 0; i < desc->nb_components; i++) {
  1186. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  1187. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  1188. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  1189. (srcp->crop_top >> vshift) * dst->linesize[i];
  1190. dst->data[i] += off;
  1191. }
  1192. return 0;
  1193. }
  1194. static int is_extra(const uint8_t *buf, int buf_size)
  1195. {
  1196. int cnt= buf[5]&0x1f;
  1197. const uint8_t *p= buf+6;
  1198. while(cnt--){
  1199. int nalsize= AV_RB16(p) + 2;
  1200. if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
  1201. return 0;
  1202. p += nalsize;
  1203. }
  1204. cnt = *(p++);
  1205. if(!cnt)
  1206. return 0;
  1207. while(cnt--){
  1208. int nalsize= AV_RB16(p) + 2;
  1209. if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
  1210. return 0;
  1211. p += nalsize;
  1212. }
  1213. return 1;
  1214. }
  1215. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1216. int *got_frame, AVPacket *avpkt)
  1217. {
  1218. const uint8_t *buf = avpkt->data;
  1219. int buf_size = avpkt->size;
  1220. H264Context *h = avctx->priv_data;
  1221. AVFrame *pict = data;
  1222. int buf_index = 0;
  1223. H264Picture *out;
  1224. int i, out_idx;
  1225. int ret;
  1226. h->flags = avctx->flags;
  1227. h->setup_finished = 0;
  1228. if (h->backup_width != -1) {
  1229. avctx->width = h->backup_width;
  1230. h->backup_width = -1;
  1231. }
  1232. if (h->backup_height != -1) {
  1233. avctx->height = h->backup_height;
  1234. h->backup_height = -1;
  1235. }
  1236. if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
  1237. avctx->pix_fmt = h->backup_pix_fmt;
  1238. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  1239. }
  1240. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1241. /* end of stream, output what is still in the buffers */
  1242. if (buf_size == 0) {
  1243. out:
  1244. h->cur_pic_ptr = NULL;
  1245. h->first_field = 0;
  1246. // FIXME factorize this with the output code below
  1247. out = h->delayed_pic[0];
  1248. out_idx = 0;
  1249. for (i = 1;
  1250. h->delayed_pic[i] &&
  1251. !h->delayed_pic[i]->f->key_frame &&
  1252. !h->delayed_pic[i]->mmco_reset;
  1253. i++)
  1254. if (h->delayed_pic[i]->poc < out->poc) {
  1255. out = h->delayed_pic[i];
  1256. out_idx = i;
  1257. }
  1258. for (i = out_idx; h->delayed_pic[i]; i++)
  1259. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1260. if (out) {
  1261. out->reference &= ~DELAYED_PIC_REF;
  1262. ret = output_frame(h, pict, out);
  1263. if (ret < 0)
  1264. return ret;
  1265. *got_frame = 1;
  1266. }
  1267. return buf_index;
  1268. }
  1269. if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
  1270. int side_size;
  1271. uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  1272. if (is_extra(side, side_size))
  1273. ff_h264_decode_extradata(h, side, side_size);
  1274. }
  1275. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  1276. if (is_extra(buf, buf_size))
  1277. return ff_h264_decode_extradata(h, buf, buf_size);
  1278. }
  1279. buf_index = decode_nal_units(h, buf, buf_size, 0);
  1280. if (buf_index < 0)
  1281. return AVERROR_INVALIDDATA;
  1282. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1283. av_assert0(buf_index <= buf_size);
  1284. goto out;
  1285. }
  1286. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1287. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  1288. buf_size >= 4 && !memcmp("Q264", buf, 4))
  1289. return buf_size;
  1290. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1291. return AVERROR_INVALIDDATA;
  1292. }
  1293. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  1294. (h->mb_y >= h->mb_height && h->mb_height)) {
  1295. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  1296. decode_postinit(h, 1);
  1297. if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
  1298. return ret;
  1299. /* Wait for second field. */
  1300. *got_frame = 0;
  1301. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  1302. (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
  1303. h->next_output_pic->recovered)) {
  1304. if (!h->next_output_pic->recovered)
  1305. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  1306. if (!h->avctx->hwaccel &&
  1307. (h->next_output_pic->field_poc[0] == INT_MAX ||
  1308. h->next_output_pic->field_poc[1] == INT_MAX)
  1309. ) {
  1310. int p;
  1311. AVFrame *f = h->next_output_pic->f;
  1312. int field = h->next_output_pic->field_poc[0] == INT_MAX;
  1313. uint8_t *dst_data[4];
  1314. int linesizes[4];
  1315. const uint8_t *src_data[4];
  1316. av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
  1317. for (p = 0; p<4; p++) {
  1318. dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
  1319. src_data[p] = f->data[p] + field *f->linesize[p];
  1320. linesizes[p] = 2*f->linesize[p];
  1321. }
  1322. av_image_copy(dst_data, linesizes, src_data, linesizes,
  1323. f->format, f->width, f->height>>1);
  1324. }
  1325. ret = output_frame(h, pict, h->next_output_pic);
  1326. if (ret < 0)
  1327. return ret;
  1328. *got_frame = 1;
  1329. if (CONFIG_MPEGVIDEO) {
  1330. ff_print_debug_info2(h->avctx, pict, NULL,
  1331. h->next_output_pic->mb_type,
  1332. h->next_output_pic->qscale_table,
  1333. h->next_output_pic->motion_val,
  1334. &h->low_delay,
  1335. h->mb_width, h->mb_height, h->mb_stride, 1);
  1336. }
  1337. }
  1338. }
  1339. av_assert0(pict->buf[0] || !*got_frame);
  1340. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1341. return get_consumed_bytes(buf_index, buf_size);
  1342. }
  1343. av_cold void ff_h264_free_context(H264Context *h)
  1344. {
  1345. int i;
  1346. ff_h264_free_tables(h);
  1347. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  1348. ff_h264_unref_picture(h, &h->DPB[i]);
  1349. av_frame_free(&h->DPB[i].f);
  1350. }
  1351. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  1352. h->cur_pic_ptr = NULL;
  1353. for (i = 0; i < h->nb_slice_ctx; i++)
  1354. av_freep(&h->slice_ctx[i].rbsp_buffer);
  1355. av_freep(&h->slice_ctx);
  1356. h->nb_slice_ctx = 0;
  1357. h->a53_caption_size = 0;
  1358. av_freep(&h->a53_caption);
  1359. for (i = 0; i < MAX_SPS_COUNT; i++)
  1360. av_freep(h->sps_buffers + i);
  1361. for (i = 0; i < MAX_PPS_COUNT; i++)
  1362. av_freep(h->pps_buffers + i);
  1363. ff_h2645_packet_uninit(&h->pkt);
  1364. }
  1365. static av_cold int h264_decode_end(AVCodecContext *avctx)
  1366. {
  1367. H264Context *h = avctx->priv_data;
  1368. ff_h264_remove_all_refs(h);
  1369. ff_h264_free_context(h);
  1370. ff_h264_unref_picture(h, &h->cur_pic);
  1371. av_frame_free(&h->cur_pic.f);
  1372. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1373. av_frame_free(&h->last_pic_for_ec.f);
  1374. return 0;
  1375. }
  1376. #define OFFSET(x) offsetof(H264Context, x)
  1377. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1378. static const AVOption h264_options[] = {
  1379. {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
  1380. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  1381. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
  1382. { NULL },
  1383. };
  1384. static const AVClass h264_class = {
  1385. .class_name = "H264 Decoder",
  1386. .item_name = av_default_item_name,
  1387. .option = h264_options,
  1388. .version = LIBAVUTIL_VERSION_INT,
  1389. };
  1390. AVCodec ff_h264_decoder = {
  1391. .name = "h264",
  1392. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1393. .type = AVMEDIA_TYPE_VIDEO,
  1394. .id = AV_CODEC_ID_H264,
  1395. .priv_data_size = sizeof(H264Context),
  1396. .init = ff_h264_decode_init,
  1397. .close = h264_decode_end,
  1398. .decode = h264_decode_frame,
  1399. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  1400. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  1401. AV_CODEC_CAP_FRAME_THREADS,
  1402. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1403. .flush = flush_dpb,
  1404. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1405. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1406. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  1407. .priv_class = &h264_class,
  1408. };
  1409. #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
  1410. static const AVClass h264_vdpau_class = {
  1411. .class_name = "H264 VDPAU Decoder",
  1412. .item_name = av_default_item_name,
  1413. .option = h264_options,
  1414. .version = LIBAVUTIL_VERSION_INT,
  1415. };
  1416. AVCodec ff_h264_vdpau_decoder = {
  1417. .name = "h264_vdpau",
  1418. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  1419. .type = AVMEDIA_TYPE_VIDEO,
  1420. .id = AV_CODEC_ID_H264,
  1421. .priv_data_size = sizeof(H264Context),
  1422. .init = ff_h264_decode_init,
  1423. .close = h264_decode_end,
  1424. .decode = h264_decode_frame,
  1425. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
  1426. .flush = flush_dpb,
  1427. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  1428. AV_PIX_FMT_NONE},
  1429. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  1430. .priv_class = &h264_vdpau_class,
  1431. };
  1432. #endif