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.

1120 lines
37KB

  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->nb_slice_ctx;
  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. return 0;
  181. fail:
  182. ff_h264_free_tables(h);
  183. return AVERROR(ENOMEM);
  184. }
  185. /**
  186. * Init context
  187. * Allocate buffers which are not shared amongst multiple threads.
  188. */
  189. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  190. {
  191. ERContext *er = &sl->er;
  192. int mb_array_size = h->mb_height * h->mb_stride;
  193. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  194. int c_size = h->mb_stride * (h->mb_height + 1);
  195. int yc_size = y_size + 2 * c_size;
  196. int x, y, i;
  197. sl->ref_cache[0][scan8[5] + 1] =
  198. sl->ref_cache[0][scan8[7] + 1] =
  199. sl->ref_cache[0][scan8[13] + 1] =
  200. sl->ref_cache[1][scan8[5] + 1] =
  201. sl->ref_cache[1][scan8[7] + 1] =
  202. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  203. if (CONFIG_ERROR_RESILIENCE) {
  204. /* init ER */
  205. er->avctx = h->avctx;
  206. er->decode_mb = h264_er_decode_mb;
  207. er->opaque = h;
  208. er->quarter_sample = 1;
  209. er->mb_num = h->mb_num;
  210. er->mb_width = h->mb_width;
  211. er->mb_height = h->mb_height;
  212. er->mb_stride = h->mb_stride;
  213. er->b8_stride = h->mb_width * 2 + 1;
  214. // error resilience code looks cleaner with this
  215. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  216. (h->mb_num + 1) * sizeof(int), fail);
  217. for (y = 0; y < h->mb_height; y++)
  218. for (x = 0; x < h->mb_width; x++)
  219. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  220. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  221. h->mb_stride + h->mb_width;
  222. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  223. mb_array_size * sizeof(uint8_t), fail);
  224. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  225. h->mb_height * h->mb_stride, fail);
  226. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  227. yc_size * sizeof(int16_t), fail);
  228. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  229. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  230. er->dc_val[2] = er->dc_val[1] + c_size;
  231. for (i = 0; i < yc_size; i++)
  232. sl->dc_val_base[i] = 1024;
  233. }
  234. return 0;
  235. fail:
  236. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  237. }
  238. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  239. {
  240. int i;
  241. h->avctx = avctx;
  242. h->picture_structure = PICT_FRAME;
  243. h->workaround_bugs = avctx->workaround_bugs;
  244. h->flags = avctx->flags;
  245. h->poc.prev_poc_msb = 1 << 16;
  246. h->recovery_frame = -1;
  247. h->frame_recovered = 0;
  248. h->next_outputed_poc = INT_MIN;
  249. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  250. h->last_pocs[i] = INT_MIN;
  251. ff_h264_sei_uninit(&h->sei);
  252. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  253. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
  254. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  255. if (!h->slice_ctx) {
  256. h->nb_slice_ctx = 0;
  257. return AVERROR(ENOMEM);
  258. }
  259. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  260. h->DPB[i].f = av_frame_alloc();
  261. if (!h->DPB[i].f)
  262. return AVERROR(ENOMEM);
  263. }
  264. h->cur_pic.f = av_frame_alloc();
  265. if (!h->cur_pic.f)
  266. return AVERROR(ENOMEM);
  267. for (i = 0; i < h->nb_slice_ctx; i++)
  268. h->slice_ctx[i].h264 = h;
  269. return 0;
  270. }
  271. static av_cold int h264_decode_end(AVCodecContext *avctx)
  272. {
  273. H264Context *h = avctx->priv_data;
  274. int i;
  275. ff_h264_free_tables(h);
  276. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  277. ff_h264_unref_picture(h, &h->DPB[i]);
  278. av_frame_free(&h->DPB[i].f);
  279. }
  280. h->cur_pic_ptr = NULL;
  281. av_freep(&h->slice_ctx);
  282. h->nb_slice_ctx = 0;
  283. for (i = 0; i < MAX_SPS_COUNT; i++)
  284. av_buffer_unref(&h->ps.sps_list[i]);
  285. for (i = 0; i < MAX_PPS_COUNT; i++)
  286. av_buffer_unref(&h->ps.pps_list[i]);
  287. ff_h2645_packet_uninit(&h->pkt);
  288. ff_h264_unref_picture(h, &h->cur_pic);
  289. av_frame_free(&h->cur_pic.f);
  290. return 0;
  291. }
  292. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  293. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  294. {
  295. H264Context *h = avctx->priv_data;
  296. int ret;
  297. ret = h264_init_context(avctx, h);
  298. if (ret < 0)
  299. return ret;
  300. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  301. if (ret != 0) {
  302. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  303. return AVERROR_UNKNOWN;
  304. }
  305. if (avctx->codec_id == AV_CODEC_ID_H264) {
  306. if (avctx->ticks_per_frame == 1)
  307. h->avctx->framerate.num *= 2;
  308. avctx->ticks_per_frame = 2;
  309. }
  310. if (avctx->extradata_size > 0 && avctx->extradata) {
  311. ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
  312. &h->ps, &h->is_avc, &h->nal_length_size,
  313. avctx->err_recognition, avctx);
  314. if (ret < 0) {
  315. h264_decode_end(avctx);
  316. return ret;
  317. }
  318. }
  319. if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
  320. h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
  321. h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
  322. }
  323. avctx->internal->allocate_progress = 1;
  324. if (h->enable_er) {
  325. av_log(avctx, AV_LOG_WARNING,
  326. "Error resilience is enabled. It is unsafe and unsupported and may crash. "
  327. "Use it at your own risk\n");
  328. }
  329. return 0;
  330. }
  331. static int decode_init_thread_copy(AVCodecContext *avctx)
  332. {
  333. H264Context *h = avctx->priv_data;
  334. int ret;
  335. if (!avctx->internal->is_copy)
  336. return 0;
  337. memset(h, 0, sizeof(*h));
  338. ret = h264_init_context(avctx, h);
  339. if (ret < 0)
  340. return ret;
  341. h->context_initialized = 0;
  342. return 0;
  343. }
  344. /**
  345. * Run setup operations that must be run after slice header decoding.
  346. * This includes finding the next displayed frame.
  347. *
  348. * @param h h264 master context
  349. * @param setup_finished enough NALs have been read that we can call
  350. * ff_thread_finish_setup()
  351. */
  352. static void decode_postinit(H264Context *h, int setup_finished)
  353. {
  354. const SPS *sps = h->ps.sps;
  355. H264Picture *out = h->cur_pic_ptr;
  356. H264Picture *cur = h->cur_pic_ptr;
  357. int i, pics, out_of_order, out_idx;
  358. int invalid = 0, cnt = 0;
  359. if (h->next_output_pic)
  360. return;
  361. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  362. /* FIXME: if we have two PAFF fields in one packet, we can't start
  363. * the next thread here. If we have one field per packet, we can.
  364. * The check in decode_nal_units() is not good enough to find this
  365. * yet, so we assume the worst for now. */
  366. // if (setup_finished)
  367. // ff_thread_finish_setup(h->avctx);
  368. return;
  369. }
  370. cur->f->interlaced_frame = 0;
  371. cur->f->repeat_pict = 0;
  372. /* Signal interlacing information externally. */
  373. /* Prioritize picture timing SEI information over used
  374. * decoding process if it exists. */
  375. if (sps->pic_struct_present_flag) {
  376. H264SEIPictureTiming *pt = &h->sei.picture_timing;
  377. switch (pt->pic_struct) {
  378. case SEI_PIC_STRUCT_FRAME:
  379. break;
  380. case SEI_PIC_STRUCT_TOP_FIELD:
  381. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  382. cur->f->interlaced_frame = 1;
  383. break;
  384. case SEI_PIC_STRUCT_TOP_BOTTOM:
  385. case SEI_PIC_STRUCT_BOTTOM_TOP:
  386. if (FIELD_OR_MBAFF_PICTURE(h))
  387. cur->f->interlaced_frame = 1;
  388. else
  389. // try to flag soft telecine progressive
  390. cur->f->interlaced_frame = h->prev_interlaced_frame;
  391. break;
  392. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  393. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  394. /* Signal the possibility of telecined film externally
  395. * (pic_struct 5,6). From these hints, let the applications
  396. * decide if they apply deinterlacing. */
  397. cur->f->repeat_pict = 1;
  398. break;
  399. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  400. cur->f->repeat_pict = 2;
  401. break;
  402. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  403. cur->f->repeat_pict = 4;
  404. break;
  405. }
  406. if ((pt->ct_type & 3) &&
  407. pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  408. cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
  409. } else {
  410. /* Derive interlacing flag from used decoding process. */
  411. cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  412. }
  413. h->prev_interlaced_frame = cur->f->interlaced_frame;
  414. if (cur->field_poc[0] != cur->field_poc[1]) {
  415. /* Derive top_field_first from field pocs. */
  416. cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  417. } else {
  418. if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
  419. /* Use picture timing SEI information. Even if it is a
  420. * information of a past frame, better than nothing. */
  421. if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  422. h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  423. cur->f->top_field_first = 1;
  424. else
  425. cur->f->top_field_first = 0;
  426. } else {
  427. /* Most likely progressive */
  428. cur->f->top_field_first = 0;
  429. }
  430. }
  431. if (h->sei.frame_packing.present &&
  432. h->sei.frame_packing.arrangement_type >= 0 &&
  433. h->sei.frame_packing.arrangement_type <= 6 &&
  434. h->sei.frame_packing.content_interpretation_type > 0 &&
  435. h->sei.frame_packing.content_interpretation_type < 3) {
  436. H264SEIFramePacking *fp = &h->sei.frame_packing;
  437. AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
  438. if (!stereo)
  439. return;
  440. switch (fp->arrangement_type) {
  441. case 0:
  442. stereo->type = AV_STEREO3D_CHECKERBOARD;
  443. break;
  444. case 1:
  445. stereo->type = AV_STEREO3D_COLUMNS;
  446. break;
  447. case 2:
  448. stereo->type = AV_STEREO3D_LINES;
  449. break;
  450. case 3:
  451. if (fp->quincunx_subsampling)
  452. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  453. else
  454. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  455. break;
  456. case 4:
  457. stereo->type = AV_STEREO3D_TOPBOTTOM;
  458. break;
  459. case 5:
  460. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  461. break;
  462. case 6:
  463. stereo->type = AV_STEREO3D_2D;
  464. break;
  465. }
  466. if (fp->content_interpretation_type == 2)
  467. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  468. }
  469. if (h->sei.display_orientation.present &&
  470. (h->sei.display_orientation.anticlockwise_rotation ||
  471. h->sei.display_orientation.hflip ||
  472. h->sei.display_orientation.vflip)) {
  473. H264SEIDisplayOrientation *o = &h->sei.display_orientation;
  474. double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
  475. AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
  476. AV_FRAME_DATA_DISPLAYMATRIX,
  477. sizeof(int32_t) * 9);
  478. if (!rotation)
  479. return;
  480. av_display_rotation_set((int32_t *)rotation->data, angle);
  481. av_display_matrix_flip((int32_t *)rotation->data,
  482. o->hflip, o->vflip);
  483. }
  484. if (h->sei.afd.present) {
  485. AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
  486. sizeof(uint8_t));
  487. if (!sd)
  488. return;
  489. *sd->data = h->sei.afd.active_format_description;
  490. h->sei.afd.present = 0;
  491. }
  492. if (h->sei.a53_caption.a53_caption) {
  493. H264SEIA53Caption *a53 = &h->sei.a53_caption;
  494. AVFrameSideData *sd = av_frame_new_side_data(cur->f,
  495. AV_FRAME_DATA_A53_CC,
  496. a53->a53_caption_size);
  497. if (!sd)
  498. return;
  499. memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
  500. av_freep(&a53->a53_caption);
  501. a53->a53_caption_size = 0;
  502. }
  503. // FIXME do something with unavailable reference frames
  504. /* Sort B-frames into display order */
  505. if (sps->bitstream_restriction_flag ||
  506. h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  507. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
  508. }
  509. pics = 0;
  510. while (h->delayed_pic[pics])
  511. pics++;
  512. assert(pics <= MAX_DELAYED_PIC_COUNT);
  513. h->delayed_pic[pics++] = cur;
  514. if (cur->reference == 0)
  515. cur->reference = DELAYED_PIC_REF;
  516. /* Frame reordering. This code takes pictures from coding order and sorts
  517. * them by their incremental POC value into display order. It supports POC
  518. * gaps, MMCO reset codes and random resets.
  519. * A "display group" can start either with a IDR frame (f.key_frame = 1),
  520. * and/or can be closed down with a MMCO reset code. In sequences where
  521. * there is no delay, we can't detect that (since the frame was already
  522. * output to the user), so we also set h->mmco_reset to detect the MMCO
  523. * reset code.
  524. * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
  525. * we increase the delay between input and output. All frames affected by
  526. * the lag (e.g. those that should have been output before another frame
  527. * that we already returned to the user) will be dropped. This is a bug
  528. * that we will fix later. */
  529. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  530. cnt += out->poc < h->last_pocs[i];
  531. invalid += out->poc == INT_MIN;
  532. }
  533. if (!h->mmco_reset && !cur->f->key_frame &&
  534. cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
  535. h->mmco_reset = 2;
  536. if (pics > 1)
  537. h->delayed_pic[pics - 2]->mmco_reset = 2;
  538. }
  539. if (h->mmco_reset || cur->f->key_frame) {
  540. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  541. h->last_pocs[i] = INT_MIN;
  542. cnt = 0;
  543. invalid = MAX_DELAYED_PIC_COUNT;
  544. }
  545. out = h->delayed_pic[0];
  546. out_idx = 0;
  547. for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
  548. h->delayed_pic[i] &&
  549. !h->delayed_pic[i - 1]->mmco_reset &&
  550. !h->delayed_pic[i]->f->key_frame;
  551. i++)
  552. if (h->delayed_pic[i]->poc < out->poc) {
  553. out = h->delayed_pic[i];
  554. out_idx = i;
  555. }
  556. if (h->avctx->has_b_frames == 0 &&
  557. (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
  558. h->next_outputed_poc = INT_MIN;
  559. out_of_order = !out->f->key_frame && !h->mmco_reset &&
  560. (out->poc < h->next_outputed_poc);
  561. if (sps->bitstream_restriction_flag &&
  562. h->avctx->has_b_frames >= sps->num_reorder_frames) {
  563. } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
  564. h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
  565. if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
  566. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
  567. }
  568. } else if (!h->avctx->has_b_frames &&
  569. ((h->next_outputed_poc != INT_MIN &&
  570. out->poc > h->next_outputed_poc + 2) ||
  571. cur->f->pict_type == AV_PICTURE_TYPE_B)) {
  572. h->avctx->has_b_frames++;
  573. }
  574. if (pics > h->avctx->has_b_frames) {
  575. out->reference &= ~DELAYED_PIC_REF;
  576. for (i = out_idx; h->delayed_pic[i]; i++)
  577. h->delayed_pic[i] = h->delayed_pic[i + 1];
  578. }
  579. memmove(h->last_pocs, &h->last_pocs[1],
  580. sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
  581. h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
  582. if (!out_of_order && pics > h->avctx->has_b_frames) {
  583. h->next_output_pic = out;
  584. if (out->mmco_reset) {
  585. if (out_idx > 0) {
  586. h->next_outputed_poc = out->poc;
  587. h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
  588. } else {
  589. h->next_outputed_poc = INT_MIN;
  590. }
  591. } else {
  592. if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
  593. h->next_outputed_poc = INT_MIN;
  594. } else {
  595. h->next_outputed_poc = out->poc;
  596. }
  597. }
  598. h->mmco_reset = 0;
  599. } else {
  600. av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
  601. }
  602. if (h->next_output_pic) {
  603. if (h->next_output_pic->recovered) {
  604. // We have reached an recovery point and all frames after it in
  605. // display order are "recovered".
  606. h->frame_recovered |= FRAME_RECOVERED_SEI;
  607. }
  608. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  609. }
  610. if (setup_finished && !h->avctx->hwaccel) {
  611. ff_thread_finish_setup(h->avctx);
  612. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  613. h->setup_finished = 1;
  614. }
  615. }
  616. /**
  617. * instantaneous decoder refresh.
  618. */
  619. static void idr(H264Context *h)
  620. {
  621. ff_h264_remove_all_refs(h);
  622. h->poc.prev_frame_num =
  623. h->poc.prev_frame_num_offset =
  624. h->poc.prev_poc_msb =
  625. h->poc.prev_poc_lsb = 0;
  626. }
  627. /* forget old pics after a seek */
  628. void ff_h264_flush_change(H264Context *h)
  629. {
  630. int i;
  631. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  632. h->last_pocs[i] = INT_MIN;
  633. h->next_outputed_poc = INT_MIN;
  634. h->prev_interlaced_frame = 1;
  635. idr(h);
  636. if (h->cur_pic_ptr)
  637. h->cur_pic_ptr->reference = 0;
  638. h->first_field = 0;
  639. ff_h264_sei_uninit(&h->sei);
  640. h->recovery_frame = -1;
  641. h->frame_recovered = 0;
  642. }
  643. /* forget old pics after a seek */
  644. static void flush_dpb(AVCodecContext *avctx)
  645. {
  646. H264Context *h = avctx->priv_data;
  647. int i;
  648. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  649. ff_h264_flush_change(h);
  650. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  651. ff_h264_unref_picture(h, &h->DPB[i]);
  652. h->cur_pic_ptr = NULL;
  653. ff_h264_unref_picture(h, &h->cur_pic);
  654. h->mb_y = 0;
  655. ff_h264_free_tables(h);
  656. h->context_initialized = 0;
  657. }
  658. static int get_last_needed_nal(H264Context *h)
  659. {
  660. int nals_needed = 0;
  661. int i;
  662. for (i = 0; i < h->pkt.nb_nals; i++) {
  663. H2645NAL *nal = &h->pkt.nals[i];
  664. GetBitContext gb;
  665. /* packets can sometimes contain multiple PPS/SPS,
  666. * e.g. two PAFF field pictures in one packet, or a demuxer
  667. * which splits NALs strangely if so, when frame threading we
  668. * can't start the next thread until we've read all of them */
  669. switch (nal->type) {
  670. case NAL_SPS:
  671. case NAL_PPS:
  672. nals_needed = i;
  673. break;
  674. case NAL_DPA:
  675. case NAL_IDR_SLICE:
  676. case NAL_SLICE:
  677. init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
  678. if (!get_ue_golomb(&gb))
  679. nals_needed = i;
  680. }
  681. }
  682. return nals_needed;
  683. }
  684. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  685. {
  686. AVCodecContext *const avctx = h->avctx;
  687. unsigned context_count = 0;
  688. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  689. int i, ret = 0;
  690. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  691. h->current_slice = 0;
  692. if (!h->first_field)
  693. h->cur_pic_ptr = NULL;
  694. ff_h264_sei_uninit(&h->sei);
  695. }
  696. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  697. h->nal_length_size, avctx->codec_id);
  698. if (ret < 0) {
  699. av_log(avctx, AV_LOG_ERROR,
  700. "Error splitting the input into NAL units.\n");
  701. return ret;
  702. }
  703. if (avctx->active_thread_type & FF_THREAD_FRAME)
  704. nals_needed = get_last_needed_nal(h);
  705. for (i = 0; i < h->pkt.nb_nals; i++) {
  706. H2645NAL *nal = &h->pkt.nals[i];
  707. H264SliceContext *sl = &h->slice_ctx[context_count];
  708. int err;
  709. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  710. nal->ref_idc == 0 && nal->type != NAL_SEI)
  711. continue;
  712. // FIXME these should stop being context-global variables
  713. h->nal_ref_idc = nal->ref_idc;
  714. h->nal_unit_type = nal->type;
  715. err = 0;
  716. switch (nal->type) {
  717. case NAL_IDR_SLICE:
  718. if (nal->type != NAL_IDR_SLICE) {
  719. av_log(h->avctx, AV_LOG_ERROR,
  720. "Invalid mix of idr and non-idr slices\n");
  721. ret = -1;
  722. goto end;
  723. }
  724. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  725. case NAL_SLICE:
  726. sl->gb = nal->gb;
  727. if ((err = ff_h264_decode_slice_header(h, sl)))
  728. break;
  729. if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
  730. h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
  731. ((1 << h->ps.sps->log2_max_frame_num) - 1);
  732. }
  733. h->cur_pic_ptr->f->key_frame |=
  734. (nal->type == NAL_IDR_SLICE) || (h->sei.recovery_point.recovery_frame_cnt >= 0);
  735. if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
  736. h->recovery_frame = -1;
  737. h->cur_pic_ptr->recovered = 1;
  738. }
  739. // If we have an IDR, all frames after it in decoded order are
  740. // "recovered".
  741. if (nal->type == NAL_IDR_SLICE)
  742. h->frame_recovered |= FRAME_RECOVERED_IDR;
  743. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  744. if (h->current_slice == 1) {
  745. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  746. decode_postinit(h, i >= nals_needed);
  747. if (h->avctx->hwaccel &&
  748. (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
  749. return ret;
  750. }
  751. if (sl->redundant_pic_count == 0 &&
  752. (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
  753. (avctx->skip_frame < AVDISCARD_BIDIR ||
  754. sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
  755. (avctx->skip_frame < AVDISCARD_NONKEY ||
  756. h->cur_pic_ptr->f->key_frame) &&
  757. avctx->skip_frame < AVDISCARD_ALL) {
  758. if (avctx->hwaccel) {
  759. ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
  760. if (ret < 0)
  761. return ret;
  762. } else
  763. context_count++;
  764. }
  765. break;
  766. case NAL_DPA:
  767. case NAL_DPB:
  768. case NAL_DPC:
  769. avpriv_request_sample(avctx, "data partitioning");
  770. ret = AVERROR(ENOSYS);
  771. goto end;
  772. break;
  773. case NAL_SEI:
  774. ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
  775. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  776. goto end;
  777. break;
  778. case NAL_SPS:
  779. ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
  780. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  781. goto end;
  782. break;
  783. case NAL_PPS:
  784. ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
  785. nal->size_bits);
  786. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  787. goto end;
  788. break;
  789. case NAL_AUD:
  790. case NAL_END_SEQUENCE:
  791. case NAL_END_STREAM:
  792. case NAL_FILLER_DATA:
  793. case NAL_SPS_EXT:
  794. case NAL_AUXILIARY_SLICE:
  795. break;
  796. case NAL_FF_IGNORE:
  797. break;
  798. default:
  799. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  800. nal->type, nal->size_bits);
  801. }
  802. if (context_count == h->nb_slice_ctx) {
  803. ret = ff_h264_execute_decode_slices(h, context_count);
  804. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  805. goto end;
  806. context_count = 0;
  807. }
  808. if (err < 0) {
  809. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  810. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  811. }
  812. }
  813. if (context_count) {
  814. ret = ff_h264_execute_decode_slices(h, context_count);
  815. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  816. goto end;
  817. }
  818. ret = 0;
  819. end:
  820. /* clean up */
  821. if (h->cur_pic_ptr && !h->droppable) {
  822. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  823. h->picture_structure == PICT_BOTTOM_FIELD);
  824. }
  825. return (ret < 0) ? ret : buf_size;
  826. }
  827. /**
  828. * Return the number of bytes consumed for building the current frame.
  829. */
  830. static int get_consumed_bytes(int pos, int buf_size)
  831. {
  832. if (pos == 0)
  833. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  834. if (pos + 10 > buf_size)
  835. pos = buf_size; // oops ;)
  836. return pos;
  837. }
  838. static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
  839. {
  840. int i;
  841. int ret = av_frame_ref(dst, src);
  842. if (ret < 0)
  843. return ret;
  844. if (!h->ps.sps || !h->ps.sps->crop)
  845. return 0;
  846. for (i = 0; i < 3; i++) {
  847. int hshift = (i > 0) ? h->chroma_x_shift : 0;
  848. int vshift = (i > 0) ? h->chroma_y_shift : 0;
  849. int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
  850. (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
  851. dst->data[i] += off;
  852. }
  853. return 0;
  854. }
  855. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  856. int *got_frame, AVPacket *avpkt)
  857. {
  858. const uint8_t *buf = avpkt->data;
  859. int buf_size = avpkt->size;
  860. H264Context *h = avctx->priv_data;
  861. AVFrame *pict = data;
  862. int buf_index = 0;
  863. int ret;
  864. h->flags = avctx->flags;
  865. h->setup_finished = 0;
  866. /* end of stream, output what is still in the buffers */
  867. out:
  868. if (buf_size == 0) {
  869. H264Picture *out;
  870. int i, out_idx;
  871. h->cur_pic_ptr = NULL;
  872. // FIXME factorize this with the output code below
  873. out = h->delayed_pic[0];
  874. out_idx = 0;
  875. for (i = 1;
  876. h->delayed_pic[i] &&
  877. !h->delayed_pic[i]->f->key_frame &&
  878. !h->delayed_pic[i]->mmco_reset;
  879. i++)
  880. if (h->delayed_pic[i]->poc < out->poc) {
  881. out = h->delayed_pic[i];
  882. out_idx = i;
  883. }
  884. for (i = out_idx; h->delayed_pic[i]; i++)
  885. h->delayed_pic[i] = h->delayed_pic[i + 1];
  886. if (out) {
  887. ret = output_frame(h, pict, out->f);
  888. if (ret < 0)
  889. return ret;
  890. *got_frame = 1;
  891. }
  892. return buf_index;
  893. }
  894. buf_index = decode_nal_units(h, buf, buf_size);
  895. if (buf_index < 0)
  896. return AVERROR_INVALIDDATA;
  897. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  898. buf_size = 0;
  899. goto out;
  900. }
  901. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  902. if (avctx->skip_frame >= AVDISCARD_NONREF)
  903. return 0;
  904. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  905. return AVERROR_INVALIDDATA;
  906. }
  907. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  908. (h->mb_y >= h->mb_height && h->mb_height)) {
  909. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  910. decode_postinit(h, 1);
  911. ff_h264_field_end(h, &h->slice_ctx[0], 0);
  912. *got_frame = 0;
  913. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  914. h->next_output_pic->recovered)) {
  915. if (!h->next_output_pic->recovered)
  916. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  917. ret = output_frame(h, pict, h->next_output_pic->f);
  918. if (ret < 0)
  919. return ret;
  920. *got_frame = 1;
  921. }
  922. }
  923. assert(pict->buf[0] || !*got_frame);
  924. return get_consumed_bytes(buf_index, buf_size);
  925. }
  926. #define OFFSET(x) offsetof(H264Context, x)
  927. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  928. static const AVOption h264_options[] = {
  929. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
  930. { NULL },
  931. };
  932. static const AVClass h264_class = {
  933. .class_name = "h264",
  934. .item_name = av_default_item_name,
  935. .option = h264_options,
  936. .version = LIBAVUTIL_VERSION_INT,
  937. };
  938. AVCodec ff_h264_decoder = {
  939. .name = "h264",
  940. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  941. .type = AVMEDIA_TYPE_VIDEO,
  942. .id = AV_CODEC_ID_H264,
  943. .priv_data_size = sizeof(H264Context),
  944. .init = ff_h264_decode_init,
  945. .close = h264_decode_end,
  946. .decode = h264_decode_frame,
  947. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  948. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  949. AV_CODEC_CAP_FRAME_THREADS,
  950. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  951. .flush = flush_dpb,
  952. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  953. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  954. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  955. .priv_class = &h264_class,
  956. };