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.

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