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.

1424 lines
46KB

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