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.

1147 lines
38KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * H.264 / AVC / MPEG-4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #define UNCHECKED_BITSTREAM_READER 1
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/display.h"
  29. #include "libavutil/imgutils.h"
  30. #include "libavutil/opt.h"
  31. #include "libavutil/stereo3d.h"
  32. #include "libavutil/timer.h"
  33. #include "internal.h"
  34. #include "bytestream.h"
  35. #include "cabac.h"
  36. #include "cabac_functions.h"
  37. #include "error_resilience.h"
  38. #include "avcodec.h"
  39. #include "h264.h"
  40. #include "h264dec.h"
  41. #include "h2645_parse.h"
  42. #include "h264data.h"
  43. #include "h264chroma.h"
  44. #include "h264_mvpred.h"
  45. #include "h264_ps.h"
  46. #include "golomb.h"
  47. #include "mathops.h"
  48. #include "me_cmp.h"
  49. #include "mpegutils.h"
  50. #include "profiles.h"
  51. #include "rectangle.h"
  52. #include "thread.h"
  53. #include "vdpau_compat.h"
  54. static int h264_decode_end(AVCodecContext *avctx);
  55. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  56. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  57. {
  58. H264Context *h = avctx->priv_data;
  59. return h && h->ps.sps ? h->ps.sps->num_reorder_frames : 0;
  60. }
  61. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  62. int (*mv)[2][4][2],
  63. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  64. {
  65. H264Context *h = opaque;
  66. H264SliceContext *sl = &h->slice_ctx[0];
  67. sl->mb_x = mb_x;
  68. sl->mb_y = mb_y;
  69. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  70. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  71. av_assert1(ref >= 0);
  72. /* FIXME: It is possible albeit uncommon that slice references
  73. * differ between slices. We take the easy approach and ignore
  74. * it for now. If this turns out to have any relevance in
  75. * practice then correct remapping should be added. */
  76. if (ref >= sl->ref_count[0])
  77. ref = 0;
  78. if (!sl->ref_list[0][ref].data[0]) {
  79. av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
  80. ref = 0;
  81. }
  82. if ((sl->ref_list[0][ref].reference&3) != 3) {
  83. av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
  84. return;
  85. }
  86. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  87. 2, 2, 2, ref, 1);
  88. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  89. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  90. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  91. sl->mb_mbaff =
  92. sl->mb_field_decoding_flag = 0;
  93. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  94. }
  95. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  96. int y, int height)
  97. {
  98. AVCodecContext *avctx = h->avctx;
  99. const AVFrame *src = h->cur_pic.f;
  100. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  101. int vshift = desc->log2_chroma_h;
  102. const int field_pic = h->picture_structure != PICT_FRAME;
  103. if (field_pic) {
  104. height <<= 1;
  105. y <<= 1;
  106. }
  107. height = FFMIN(height, avctx->height - y);
  108. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  109. return;
  110. if (avctx->draw_horiz_band) {
  111. int offset[AV_NUM_DATA_POINTERS];
  112. int i;
  113. offset[0] = y * src->linesize[0];
  114. offset[1] =
  115. offset[2] = (y >> vshift) * src->linesize[1];
  116. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  117. offset[i] = 0;
  118. emms_c();
  119. avctx->draw_horiz_band(avctx, src, offset,
  120. y, h->picture_structure, height);
  121. }
  122. }
  123. void ff_h264_free_tables(H264Context *h)
  124. {
  125. int i;
  126. av_freep(&h->intra4x4_pred_mode);
  127. av_freep(&h->chroma_pred_mode_table);
  128. av_freep(&h->cbp_table);
  129. av_freep(&h->mvd_table[0]);
  130. av_freep(&h->mvd_table[1]);
  131. av_freep(&h->direct_table);
  132. av_freep(&h->non_zero_count);
  133. av_freep(&h->slice_table_base);
  134. h->slice_table = NULL;
  135. av_freep(&h->list_counts);
  136. av_freep(&h->mb2b_xy);
  137. av_freep(&h->mb2br_xy);
  138. av_buffer_pool_uninit(&h->qscale_table_pool);
  139. av_buffer_pool_uninit(&h->mb_type_pool);
  140. av_buffer_pool_uninit(&h->motion_val_pool);
  141. av_buffer_pool_uninit(&h->ref_index_pool);
  142. for (i = 0; i < h->nb_slice_ctx; i++) {
  143. H264SliceContext *sl = &h->slice_ctx[i];
  144. av_freep(&sl->dc_val_base);
  145. av_freep(&sl->er.mb_index2xy);
  146. av_freep(&sl->er.error_status_table);
  147. av_freep(&sl->er.er_temp_buffer);
  148. av_freep(&sl->bipred_scratchpad);
  149. av_freep(&sl->edge_emu_buffer);
  150. av_freep(&sl->top_borders[0]);
  151. av_freep(&sl->top_borders[1]);
  152. sl->bipred_scratchpad_allocated = 0;
  153. sl->edge_emu_buffer_allocated = 0;
  154. sl->top_borders_allocated[0] = 0;
  155. sl->top_borders_allocated[1] = 0;
  156. }
  157. }
  158. int ff_h264_alloc_tables(H264Context *h)
  159. {
  160. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  161. const int row_mb_num = 2*h->mb_stride*FFMAX(h->nb_slice_ctx, 1);
  162. int x, y;
  163. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  164. row_mb_num, 8 * sizeof(uint8_t), fail)
  165. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  166. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  167. big_mb_num * 48 * sizeof(uint8_t), fail)
  168. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  169. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  170. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  171. big_mb_num * sizeof(uint16_t), fail)
  172. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  173. big_mb_num * sizeof(uint8_t), fail)
  174. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
  175. row_mb_num, 16 * sizeof(uint8_t), fail);
  176. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
  177. row_mb_num, 16 * sizeof(uint8_t), fail);
  178. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  179. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  180. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  181. 4 * big_mb_num * sizeof(uint8_t), fail);
  182. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  183. big_mb_num * sizeof(uint8_t), fail)
  184. memset(h->slice_table_base, -1,
  185. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  186. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  187. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  188. big_mb_num * sizeof(uint32_t), fail);
  189. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  190. big_mb_num * sizeof(uint32_t), fail);
  191. for (y = 0; y < h->mb_height; y++)
  192. for (x = 0; x < h->mb_width; x++) {
  193. const int mb_xy = x + y * h->mb_stride;
  194. const int b_xy = 4 * x + 4 * y * h->b_stride;
  195. h->mb2b_xy[mb_xy] = b_xy;
  196. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  197. }
  198. return 0;
  199. fail:
  200. ff_h264_free_tables(h);
  201. return AVERROR(ENOMEM);
  202. }
  203. /**
  204. * Init context
  205. * Allocate buffers which are not shared amongst multiple threads.
  206. */
  207. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  208. {
  209. ERContext *er = &sl->er;
  210. int mb_array_size = h->mb_height * h->mb_stride;
  211. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  212. int c_size = h->mb_stride * (h->mb_height + 1);
  213. int yc_size = y_size + 2 * c_size;
  214. int x, y, i;
  215. sl->ref_cache[0][scan8[5] + 1] =
  216. sl->ref_cache[0][scan8[7] + 1] =
  217. sl->ref_cache[0][scan8[13] + 1] =
  218. sl->ref_cache[1][scan8[5] + 1] =
  219. sl->ref_cache[1][scan8[7] + 1] =
  220. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  221. if (sl != h->slice_ctx) {
  222. memset(er, 0, sizeof(*er));
  223. } else
  224. if (CONFIG_ERROR_RESILIENCE) {
  225. /* init ER */
  226. er->avctx = h->avctx;
  227. er->decode_mb = h264_er_decode_mb;
  228. er->opaque = h;
  229. er->quarter_sample = 1;
  230. er->mb_num = h->mb_num;
  231. er->mb_width = h->mb_width;
  232. er->mb_height = h->mb_height;
  233. er->mb_stride = h->mb_stride;
  234. er->b8_stride = h->mb_width * 2 + 1;
  235. // error resilience code looks cleaner with this
  236. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  237. (h->mb_num + 1) * sizeof(int), fail);
  238. for (y = 0; y < h->mb_height; y++)
  239. for (x = 0; x < h->mb_width; x++)
  240. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  241. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  242. h->mb_stride + h->mb_width;
  243. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  244. mb_array_size * sizeof(uint8_t), fail);
  245. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  246. h->mb_height * h->mb_stride, fail);
  247. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  248. yc_size * sizeof(int16_t), fail);
  249. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  250. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  251. er->dc_val[2] = er->dc_val[1] + c_size;
  252. for (i = 0; i < yc_size; i++)
  253. sl->dc_val_base[i] = 1024;
  254. }
  255. return 0;
  256. fail:
  257. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  258. }
  259. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  260. {
  261. int i;
  262. h->avctx = avctx;
  263. h->backup_width = -1;
  264. h->backup_height = -1;
  265. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  266. h->cur_chroma_format_idc = -1;
  267. h->picture_structure = PICT_FRAME;
  268. h->workaround_bugs = avctx->workaround_bugs;
  269. h->flags = avctx->flags;
  270. h->poc.prev_poc_msb = 1 << 16;
  271. h->recovery_frame = -1;
  272. h->frame_recovered = 0;
  273. h->poc.prev_frame_num = -1;
  274. h->sei.frame_packing.frame_packing_arrangement_cancel_flag = -1;
  275. h->sei.unregistered.x264_build = -1;
  276. h->next_outputed_poc = INT_MIN;
  277. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  278. h->last_pocs[i] = INT_MIN;
  279. ff_h264_sei_uninit(&h->sei);
  280. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  281. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
  282. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  283. if (!h->slice_ctx) {
  284. h->nb_slice_ctx = 0;
  285. return AVERROR(ENOMEM);
  286. }
  287. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  288. h->DPB[i].f = av_frame_alloc();
  289. if (!h->DPB[i].f)
  290. return AVERROR(ENOMEM);
  291. }
  292. h->cur_pic.f = av_frame_alloc();
  293. if (!h->cur_pic.f)
  294. return AVERROR(ENOMEM);
  295. h->last_pic_for_ec.f = av_frame_alloc();
  296. if (!h->last_pic_for_ec.f)
  297. return AVERROR(ENOMEM);
  298. for (i = 0; i < h->nb_slice_ctx; i++)
  299. h->slice_ctx[i].h264 = h;
  300. return 0;
  301. }
  302. static av_cold int h264_decode_end(AVCodecContext *avctx)
  303. {
  304. H264Context *h = avctx->priv_data;
  305. int i;
  306. ff_h264_remove_all_refs(h);
  307. ff_h264_free_tables(h);
  308. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  309. ff_h264_unref_picture(h, &h->DPB[i]);
  310. av_frame_free(&h->DPB[i].f);
  311. }
  312. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  313. h->cur_pic_ptr = NULL;
  314. av_freep(&h->slice_ctx);
  315. h->nb_slice_ctx = 0;
  316. ff_h264_sei_uninit(&h->sei);
  317. ff_h264_ps_uninit(&h->ps);
  318. ff_h2645_packet_uninit(&h->pkt);
  319. ff_h264_unref_picture(h, &h->cur_pic);
  320. av_frame_free(&h->cur_pic.f);
  321. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  322. av_frame_free(&h->last_pic_for_ec.f);
  323. return 0;
  324. }
  325. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  326. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  327. {
  328. H264Context *h = avctx->priv_data;
  329. int ret;
  330. ret = h264_init_context(avctx, h);
  331. if (ret < 0)
  332. return ret;
  333. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  334. if (ret != 0) {
  335. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  336. return AVERROR_UNKNOWN;
  337. }
  338. if (avctx->ticks_per_frame == 1) {
  339. if(h->avctx->time_base.den < INT_MAX/2) {
  340. h->avctx->time_base.den *= 2;
  341. } else
  342. h->avctx->time_base.num /= 2;
  343. }
  344. avctx->ticks_per_frame = 2;
  345. if (avctx->extradata_size > 0 && avctx->extradata) {
  346. ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
  347. &h->ps, &h->is_avc, &h->nal_length_size,
  348. avctx->err_recognition, avctx);
  349. if (ret < 0) {
  350. h264_decode_end(avctx);
  351. return ret;
  352. }
  353. }
  354. if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
  355. h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
  356. h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
  357. }
  358. avctx->internal->allocate_progress = 1;
  359. ff_h264_flush_change(h);
  360. if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
  361. h->enable_er = 0;
  362. if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  363. av_log(avctx, AV_LOG_WARNING,
  364. "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
  365. "Use it at your own risk\n");
  366. }
  367. return 0;
  368. }
  369. #if HAVE_THREADS
  370. static int decode_init_thread_copy(AVCodecContext *avctx)
  371. {
  372. H264Context *h = avctx->priv_data;
  373. int ret;
  374. if (!avctx->internal->is_copy)
  375. return 0;
  376. memset(h, 0, sizeof(*h));
  377. ret = h264_init_context(avctx, h);
  378. if (ret < 0)
  379. return ret;
  380. h->context_initialized = 0;
  381. return 0;
  382. }
  383. #endif
  384. /**
  385. * instantaneous decoder refresh.
  386. */
  387. static void idr(H264Context *h)
  388. {
  389. int i;
  390. ff_h264_remove_all_refs(h);
  391. h->poc.prev_frame_num =
  392. h->poc.prev_frame_num_offset = 0;
  393. h->poc.prev_poc_msb = 1<<16;
  394. h->poc.prev_poc_lsb = 0;
  395. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  396. h->last_pocs[i] = INT_MIN;
  397. }
  398. /* forget old pics after a seek */
  399. void ff_h264_flush_change(H264Context *h)
  400. {
  401. int i, j;
  402. h->next_outputed_poc = INT_MIN;
  403. h->prev_interlaced_frame = 1;
  404. idr(h);
  405. h->poc.prev_frame_num = -1;
  406. if (h->cur_pic_ptr) {
  407. h->cur_pic_ptr->reference = 0;
  408. for (j=i=0; h->delayed_pic[i]; i++)
  409. if (h->delayed_pic[i] != h->cur_pic_ptr)
  410. h->delayed_pic[j++] = h->delayed_pic[i];
  411. h->delayed_pic[j] = NULL;
  412. }
  413. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  414. h->first_field = 0;
  415. ff_h264_sei_uninit(&h->sei);
  416. h->recovery_frame = -1;
  417. h->frame_recovered = 0;
  418. h->current_slice = 0;
  419. h->mmco_reset = 1;
  420. }
  421. /* forget old pics after a seek */
  422. static void flush_dpb(AVCodecContext *avctx)
  423. {
  424. H264Context *h = avctx->priv_data;
  425. int i;
  426. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  427. ff_h264_flush_change(h);
  428. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  429. ff_h264_unref_picture(h, &h->DPB[i]);
  430. h->cur_pic_ptr = NULL;
  431. ff_h264_unref_picture(h, &h->cur_pic);
  432. h->mb_y = 0;
  433. ff_h264_free_tables(h);
  434. h->context_initialized = 0;
  435. }
  436. #if FF_API_CAP_VDPAU
  437. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  438. #endif
  439. static int get_last_needed_nal(H264Context *h)
  440. {
  441. int nals_needed = 0;
  442. int first_slice = 0;
  443. int i;
  444. int ret;
  445. for (i = 0; i < h->pkt.nb_nals; i++) {
  446. H2645NAL *nal = &h->pkt.nals[i];
  447. GetBitContext gb;
  448. /* packets can sometimes contain multiple PPS/SPS,
  449. * e.g. two PAFF field pictures in one packet, or a demuxer
  450. * which splits NALs strangely if so, when frame threading we
  451. * can't start the next thread until we've read all of them */
  452. switch (nal->type) {
  453. case H264_NAL_SPS:
  454. case H264_NAL_PPS:
  455. nals_needed = i;
  456. break;
  457. case H264_NAL_DPA:
  458. case H264_NAL_IDR_SLICE:
  459. case H264_NAL_SLICE:
  460. ret = init_get_bits8(&gb, nal->data + 1, (nal->size - 1));
  461. if (ret < 0)
  462. return ret;
  463. if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
  464. !first_slice ||
  465. first_slice != nal->type)
  466. nals_needed = i;
  467. if (!first_slice)
  468. first_slice = nal->type;
  469. }
  470. }
  471. return nals_needed;
  472. }
  473. static void debug_green_metadata(const H264SEIGreenMetaData *gm, void *logctx)
  474. {
  475. av_log(logctx, AV_LOG_DEBUG, "Green Metadata Info SEI message\n");
  476. av_log(logctx, AV_LOG_DEBUG, " green_metadata_type: %d\n", gm->green_metadata_type);
  477. if (gm->green_metadata_type == 0) {
  478. av_log(logctx, AV_LOG_DEBUG, " green_metadata_period_type: %d\n", gm->period_type);
  479. if (gm->period_type == 2)
  480. av_log(logctx, AV_LOG_DEBUG, " green_metadata_num_seconds: %d\n", gm->num_seconds);
  481. else if (gm->period_type == 3)
  482. av_log(logctx, AV_LOG_DEBUG, " green_metadata_num_pictures: %d\n", gm->num_pictures);
  483. av_log(logctx, AV_LOG_DEBUG, " SEI GREEN Complexity Metrics: %f %f %f %f\n",
  484. (float)gm->percent_non_zero_macroblocks/255,
  485. (float)gm->percent_intra_coded_macroblocks/255,
  486. (float)gm->percent_six_tap_filtering/255,
  487. (float)gm->percent_alpha_point_deblocking_instance/255);
  488. } else if (gm->green_metadata_type == 1) {
  489. av_log(logctx, AV_LOG_DEBUG, " xsd_metric_type: %d\n", gm->xsd_metric_type);
  490. if (gm->xsd_metric_type == 0)
  491. av_log(logctx, AV_LOG_DEBUG, " xsd_metric_value: %f\n",
  492. (float)gm->xsd_metric_value/100);
  493. }
  494. }
  495. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  496. {
  497. AVCodecContext *const avctx = h->avctx;
  498. unsigned context_count = 0;
  499. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  500. int idr_cleared=0;
  501. int i, ret = 0;
  502. h->nal_unit_type= 0;
  503. h->max_contexts = h->nb_slice_ctx;
  504. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  505. h->current_slice = 0;
  506. if (!h->first_field)
  507. h->cur_pic_ptr = NULL;
  508. ff_h264_sei_uninit(&h->sei);
  509. }
  510. if (h->nal_length_size == 4) {
  511. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  512. h->is_avc = 0;
  513. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  514. h->is_avc = 1;
  515. }
  516. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  517. h->nal_length_size, avctx->codec_id, avctx->flags2 & AV_CODEC_FLAG2_FAST);
  518. if (ret < 0) {
  519. av_log(avctx, AV_LOG_ERROR,
  520. "Error splitting the input into NAL units.\n");
  521. return ret;
  522. }
  523. if (avctx->active_thread_type & FF_THREAD_FRAME)
  524. nals_needed = get_last_needed_nal(h);
  525. if (nals_needed < 0)
  526. return nals_needed;
  527. for (i = 0; i < h->pkt.nb_nals; i++) {
  528. H2645NAL *nal = &h->pkt.nals[i];
  529. H264SliceContext *sl = &h->slice_ctx[context_count];
  530. int err;
  531. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  532. nal->ref_idc == 0 && nal->type != H264_NAL_SEI)
  533. continue;
  534. again:
  535. // FIXME these should stop being context-global variables
  536. h->nal_ref_idc = nal->ref_idc;
  537. h->nal_unit_type = nal->type;
  538. err = 0;
  539. switch (nal->type) {
  540. case H264_NAL_IDR_SLICE:
  541. if ((nal->data[1] & 0xFC) == 0x98) {
  542. av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
  543. h->next_outputed_poc = INT_MIN;
  544. ret = -1;
  545. goto end;
  546. }
  547. if(!idr_cleared) {
  548. if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  549. av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
  550. ret = AVERROR_INVALIDDATA;
  551. goto end;
  552. }
  553. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  554. }
  555. idr_cleared = 1;
  556. h->has_recovery_point = 1;
  557. case H264_NAL_SLICE:
  558. sl->gb = nal->gb;
  559. if ((err = ff_h264_decode_slice_header(h, sl, nal)))
  560. break;
  561. if (sl->redundant_pic_count > 0)
  562. break;
  563. if (h->current_slice == 1) {
  564. if (avctx->active_thread_type & FF_THREAD_FRAME && !h->avctx->hwaccel &&
  565. i >= nals_needed && !h->setup_finished && h->cur_pic_ptr) {
  566. ff_thread_finish_setup(avctx);
  567. h->setup_finished = 1;
  568. }
  569. if (h->avctx->hwaccel &&
  570. (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
  571. goto end;
  572. #if FF_API_CAP_VDPAU
  573. if (CONFIG_H264_VDPAU_DECODER &&
  574. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
  575. ff_vdpau_h264_picture_start(h);
  576. #endif
  577. }
  578. if (avctx->hwaccel) {
  579. ret = avctx->hwaccel->decode_slice(avctx,
  580. nal->raw_data,
  581. nal->raw_size);
  582. if (ret < 0)
  583. goto end;
  584. #if FF_API_CAP_VDPAU
  585. } else if (CONFIG_H264_VDPAU_DECODER &&
  586. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
  587. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  588. start_code,
  589. sizeof(start_code));
  590. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  591. nal->raw_data,
  592. nal->raw_size);
  593. #endif
  594. } else
  595. context_count++;
  596. break;
  597. case H264_NAL_DPA:
  598. case H264_NAL_DPB:
  599. case H264_NAL_DPC:
  600. avpriv_request_sample(avctx, "data partitioning");
  601. break;
  602. case H264_NAL_SEI:
  603. ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
  604. h->has_recovery_point = h->has_recovery_point || h->sei.recovery_point.recovery_frame_cnt != -1;
  605. if (avctx->debug & FF_DEBUG_GREEN_MD)
  606. debug_green_metadata(&h->sei.green_metadata, h->avctx);
  607. #if FF_API_AFD
  608. FF_DISABLE_DEPRECATION_WARNINGS
  609. h->avctx->dtg_active_format = h->sei.afd.active_format_description;
  610. FF_ENABLE_DEPRECATION_WARNINGS
  611. #endif /* FF_API_AFD */
  612. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  613. goto end;
  614. break;
  615. case H264_NAL_SPS: {
  616. GetBitContext tmp_gb = nal->gb;
  617. if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
  618. break;
  619. av_log(h->avctx, AV_LOG_DEBUG,
  620. "SPS decoding failure, trying again with the complete NAL\n");
  621. init_get_bits8(&tmp_gb, nal->raw_data + 1, nal->raw_size - 1);
  622. if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
  623. break;
  624. ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps, 1);
  625. break;
  626. }
  627. case H264_NAL_PPS:
  628. ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
  629. nal->size_bits);
  630. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  631. goto end;
  632. break;
  633. case H264_NAL_AUD:
  634. case H264_NAL_END_SEQUENCE:
  635. case H264_NAL_END_STREAM:
  636. case H264_NAL_FILLER_DATA:
  637. case H264_NAL_SPS_EXT:
  638. case H264_NAL_AUXILIARY_SLICE:
  639. break;
  640. default:
  641. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  642. nal->type, nal->size_bits);
  643. }
  644. if (context_count == h->max_contexts) {
  645. ret = ff_h264_execute_decode_slices(h, context_count);
  646. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  647. goto end;
  648. context_count = 0;
  649. }
  650. if (err < 0 || err == SLICE_SKIPED) {
  651. if (err < 0)
  652. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  653. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  654. } else if (err == SLICE_SINGLETHREAD) {
  655. if (context_count > 0) {
  656. ret = ff_h264_execute_decode_slices(h, context_count);
  657. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  658. goto end;
  659. context_count = 0;
  660. }
  661. /* Slice could not be decoded in parallel mode, restart. */
  662. sl = &h->slice_ctx[0];
  663. goto again;
  664. }
  665. }
  666. if (context_count) {
  667. ret = ff_h264_execute_decode_slices(h, context_count);
  668. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  669. goto end;
  670. }
  671. ret = 0;
  672. end:
  673. #if CONFIG_ERROR_RESILIENCE
  674. /*
  675. * FIXME: Error handling code does not seem to support interlaced
  676. * when slices span multiple rows
  677. * The ff_er_add_slice calls don't work right for bottom
  678. * fields; they cause massive erroneous error concealing
  679. * Error marking covers both fields (top and bottom).
  680. * This causes a mismatched s->error_count
  681. * and a bad error table. Further, the error count goes to
  682. * INT_MAX when called for bottom field, because mb_y is
  683. * past end by one (callers fault) and resync_mb_y != 0
  684. * causes problems for the first MB line, too.
  685. */
  686. if (!FIELD_PICTURE(h) && h->current_slice &&
  687. h->ps.sps == (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data &&
  688. h->enable_er) {
  689. H264SliceContext *sl = h->slice_ctx;
  690. int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
  691. ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
  692. if (use_last_pic) {
  693. ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
  694. sl->ref_list[0][0].parent = &h->last_pic_for_ec;
  695. memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
  696. memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
  697. sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
  698. } else if (sl->ref_count[0]) {
  699. ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
  700. } else
  701. ff_h264_set_erpic(&sl->er.last_pic, NULL);
  702. if (sl->ref_count[1])
  703. ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
  704. sl->er.ref_count = sl->ref_count[0];
  705. ff_er_frame_end(&sl->er);
  706. if (use_last_pic)
  707. memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
  708. }
  709. #endif /* CONFIG_ERROR_RESILIENCE */
  710. /* clean up */
  711. if (h->cur_pic_ptr && !h->droppable) {
  712. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  713. h->picture_structure == PICT_BOTTOM_FIELD);
  714. }
  715. return (ret < 0) ? ret : buf_size;
  716. }
  717. /**
  718. * Return the number of bytes consumed for building the current frame.
  719. */
  720. static int get_consumed_bytes(int pos, int buf_size)
  721. {
  722. if (pos == 0)
  723. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  724. if (pos + 10 > buf_size)
  725. pos = buf_size; // oops ;)
  726. return pos;
  727. }
  728. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  729. {
  730. AVFrame *src = srcp->f;
  731. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  732. int i;
  733. int ret = av_frame_ref(dst, src);
  734. if (ret < 0)
  735. return ret;
  736. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(&h->sei.frame_packing), 0);
  737. h->backup_width = h->avctx->width;
  738. h->backup_height = h->avctx->height;
  739. h->backup_pix_fmt = h->avctx->pix_fmt;
  740. h->avctx->width = dst->width;
  741. h->avctx->height = dst->height;
  742. h->avctx->pix_fmt = dst->format;
  743. if (srcp->sei_recovery_frame_cnt == 0)
  744. dst->key_frame = 1;
  745. if (!srcp->crop)
  746. return 0;
  747. for (i = 0; i < desc->nb_components; i++) {
  748. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  749. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  750. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  751. (srcp->crop_top >> vshift) * dst->linesize[i];
  752. dst->data[i] += off;
  753. }
  754. return 0;
  755. }
  756. static int is_extra(const uint8_t *buf, int buf_size)
  757. {
  758. int cnt= buf[5]&0x1f;
  759. const uint8_t *p= buf+6;
  760. while(cnt--){
  761. int nalsize= AV_RB16(p) + 2;
  762. if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
  763. return 0;
  764. p += nalsize;
  765. }
  766. cnt = *(p++);
  767. if(!cnt)
  768. return 0;
  769. while(cnt--){
  770. int nalsize= AV_RB16(p) + 2;
  771. if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
  772. return 0;
  773. p += nalsize;
  774. }
  775. return 1;
  776. }
  777. static int finalize_frame(H264Context *h, AVFrame *dst, H264Picture *out, int *got_frame)
  778. {
  779. int ret;
  780. if (((h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  781. (h->avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
  782. out->recovered)) {
  783. if (!h->avctx->hwaccel &&
  784. (out->field_poc[0] == INT_MAX ||
  785. out->field_poc[1] == INT_MAX)
  786. ) {
  787. int p;
  788. AVFrame *f = out->f;
  789. int field = out->field_poc[0] == INT_MAX;
  790. uint8_t *dst_data[4];
  791. int linesizes[4];
  792. const uint8_t *src_data[4];
  793. av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
  794. for (p = 0; p<4; p++) {
  795. dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
  796. src_data[p] = f->data[p] + field *f->linesize[p];
  797. linesizes[p] = 2*f->linesize[p];
  798. }
  799. av_image_copy(dst_data, linesizes, src_data, linesizes,
  800. f->format, f->width, f->height>>1);
  801. }
  802. ret = output_frame(h, dst, out);
  803. if (ret < 0)
  804. return ret;
  805. *got_frame = 1;
  806. if (CONFIG_MPEGVIDEO) {
  807. ff_print_debug_info2(h->avctx, dst, NULL,
  808. out->mb_type,
  809. out->qscale_table,
  810. out->motion_val,
  811. NULL,
  812. h->mb_width, h->mb_height, h->mb_stride, 1);
  813. }
  814. }
  815. return 0;
  816. }
  817. static int send_next_delayed_frame(H264Context *h, AVFrame *dst_frame,
  818. int *got_frame, int buf_index)
  819. {
  820. int ret, i, out_idx;
  821. H264Picture *out = h->delayed_pic[0];
  822. h->cur_pic_ptr = NULL;
  823. h->first_field = 0;
  824. out_idx = 0;
  825. for (i = 1;
  826. h->delayed_pic[i] &&
  827. !h->delayed_pic[i]->f->key_frame &&
  828. !h->delayed_pic[i]->mmco_reset;
  829. i++)
  830. if (h->delayed_pic[i]->poc < out->poc) {
  831. out = h->delayed_pic[i];
  832. out_idx = i;
  833. }
  834. for (i = out_idx; h->delayed_pic[i]; i++)
  835. h->delayed_pic[i] = h->delayed_pic[i + 1];
  836. if (out) {
  837. out->reference &= ~DELAYED_PIC_REF;
  838. ret = finalize_frame(h, dst_frame, out, got_frame);
  839. if (ret < 0)
  840. return ret;
  841. }
  842. return buf_index;
  843. }
  844. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  845. int *got_frame, AVPacket *avpkt)
  846. {
  847. const uint8_t *buf = avpkt->data;
  848. int buf_size = avpkt->size;
  849. H264Context *h = avctx->priv_data;
  850. AVFrame *pict = data;
  851. int buf_index;
  852. int ret;
  853. h->flags = avctx->flags;
  854. h->setup_finished = 0;
  855. if (h->backup_width != -1) {
  856. avctx->width = h->backup_width;
  857. h->backup_width = -1;
  858. }
  859. if (h->backup_height != -1) {
  860. avctx->height = h->backup_height;
  861. h->backup_height = -1;
  862. }
  863. if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
  864. avctx->pix_fmt = h->backup_pix_fmt;
  865. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  866. }
  867. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  868. /* end of stream, output what is still in the buffers */
  869. if (buf_size == 0)
  870. return send_next_delayed_frame(h, pict, got_frame, 0);
  871. if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
  872. int side_size;
  873. uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  874. if (is_extra(side, side_size))
  875. ff_h264_decode_extradata(side, side_size,
  876. &h->ps, &h->is_avc, &h->nal_length_size,
  877. avctx->err_recognition, avctx);
  878. }
  879. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  880. if (is_extra(buf, buf_size))
  881. return ff_h264_decode_extradata(buf, buf_size,
  882. &h->ps, &h->is_avc, &h->nal_length_size,
  883. avctx->err_recognition, avctx);
  884. }
  885. buf_index = decode_nal_units(h, buf, buf_size);
  886. if (buf_index < 0)
  887. return AVERROR_INVALIDDATA;
  888. if (!h->cur_pic_ptr && h->nal_unit_type == H264_NAL_END_SEQUENCE) {
  889. av_assert0(buf_index <= buf_size);
  890. return send_next_delayed_frame(h, pict, got_frame, buf_index);
  891. }
  892. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  893. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  894. buf_size >= 4 && !memcmp("Q264", buf, 4))
  895. return buf_size;
  896. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  897. return AVERROR_INVALIDDATA;
  898. }
  899. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  900. (h->mb_y >= h->mb_height && h->mb_height)) {
  901. if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
  902. return ret;
  903. /* Wait for second field. */
  904. if (h->next_output_pic) {
  905. ret = finalize_frame(h, pict, h->next_output_pic, got_frame);
  906. if (ret < 0)
  907. return ret;
  908. }
  909. }
  910. av_assert0(pict->buf[0] || !*got_frame);
  911. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  912. return get_consumed_bytes(buf_index, buf_size);
  913. }
  914. #define OFFSET(x) offsetof(H264Context, x)
  915. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  916. static const AVOption h264_options[] = {
  917. {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
  918. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  919. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
  920. { NULL },
  921. };
  922. static const AVClass h264_class = {
  923. .class_name = "H264 Decoder",
  924. .item_name = av_default_item_name,
  925. .option = h264_options,
  926. .version = LIBAVUTIL_VERSION_INT,
  927. };
  928. AVCodec ff_h264_decoder = {
  929. .name = "h264",
  930. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  931. .type = AVMEDIA_TYPE_VIDEO,
  932. .id = AV_CODEC_ID_H264,
  933. .priv_data_size = sizeof(H264Context),
  934. .init = ff_h264_decode_init,
  935. .close = h264_decode_end,
  936. .decode = h264_decode_frame,
  937. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  938. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  939. AV_CODEC_CAP_FRAME_THREADS,
  940. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  941. .flush = flush_dpb,
  942. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  943. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  944. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  945. .priv_class = &h264_class,
  946. };
  947. #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
  948. static const AVClass h264_vdpau_class = {
  949. .class_name = "H264 VDPAU Decoder",
  950. .item_name = av_default_item_name,
  951. .option = h264_options,
  952. .version = LIBAVUTIL_VERSION_INT,
  953. };
  954. AVCodec ff_h264_vdpau_decoder = {
  955. .name = "h264_vdpau",
  956. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  957. .type = AVMEDIA_TYPE_VIDEO,
  958. .id = AV_CODEC_ID_H264,
  959. .priv_data_size = sizeof(H264Context),
  960. .init = ff_h264_decode_init,
  961. .close = h264_decode_end,
  962. .decode = h264_decode_frame,
  963. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
  964. .flush = flush_dpb,
  965. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  966. AV_PIX_FMT_NONE},
  967. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  968. .priv_class = &h264_vdpau_class,
  969. };
  970. #endif