2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of Libav.
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.
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.
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
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/stereo3d.h"
33 #include "libavutil/timer.h"
35 #include "bytestream.h"
37 #include "cabac_functions.h"
38 #include "error_resilience.h"
41 #include "h2645_parse.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
48 #include "mpegutils.h"
50 #include "rectangle.h"
55 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
57 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
59 int mb_x, int mb_y, int mb_intra, int mb_skipped)
61 H264Context *h = opaque;
62 H264SliceContext *sl = &h->slice_ctx[0];
66 sl->mb_xy = mb_x + mb_y * h->mb_stride;
67 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
69 /* FIXME: It is possible albeit uncommon that slice references
70 * differ between slices. We take the easy approach and ignore
71 * it for now. If this turns out to have any relevance in
72 * practice then correct remapping should be added. */
73 if (ref >= sl->ref_count[0])
75 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
77 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
78 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
79 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
80 assert(!FRAME_MBAFF(h));
81 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
84 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
87 AVCodecContext *avctx = h->avctx;
88 const AVFrame *src = h->cur_pic.f;
89 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
90 int vshift = desc->log2_chroma_h;
91 const int field_pic = h->picture_structure != PICT_FRAME;
97 height = FFMIN(height, avctx->height - y);
99 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
102 if (avctx->draw_horiz_band) {
103 int offset[AV_NUM_DATA_POINTERS];
106 offset[0] = y * src->linesize[0];
108 offset[2] = (y >> vshift) * src->linesize[1];
109 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
114 avctx->draw_horiz_band(avctx, src, offset,
115 y, h->picture_structure, height);
119 void ff_h264_free_tables(H264Context *h)
123 av_freep(&h->intra4x4_pred_mode);
124 av_freep(&h->chroma_pred_mode_table);
125 av_freep(&h->cbp_table);
126 av_freep(&h->mvd_table[0]);
127 av_freep(&h->mvd_table[1]);
128 av_freep(&h->direct_table);
129 av_freep(&h->non_zero_count);
130 av_freep(&h->slice_table_base);
131 h->slice_table = NULL;
132 av_freep(&h->list_counts);
134 av_freep(&h->mb2b_xy);
135 av_freep(&h->mb2br_xy);
137 av_buffer_pool_uninit(&h->qscale_table_pool);
138 av_buffer_pool_uninit(&h->mb_type_pool);
139 av_buffer_pool_uninit(&h->motion_val_pool);
140 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];
145 av_freep(&sl->dc_val_base);
146 av_freep(&sl->er.mb_index2xy);
147 av_freep(&sl->er.error_status_table);
148 av_freep(&sl->er.er_temp_buffer);
150 av_freep(&sl->bipred_scratchpad);
151 av_freep(&sl->edge_emu_buffer);
152 av_freep(&sl->top_borders[0]);
153 av_freep(&sl->top_borders[1]);
155 sl->bipred_scratchpad_allocated = 0;
156 sl->edge_emu_buffer_allocated = 0;
157 sl->top_borders_allocated[0] = 0;
158 sl->top_borders_allocated[1] = 0;
162 int ff_h264_alloc_tables(H264Context *h)
164 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
165 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
168 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
169 row_mb_num * 8 * sizeof(uint8_t), fail)
170 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
172 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
173 big_mb_num * 48 * sizeof(uint8_t), fail)
174 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
175 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
176 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
177 big_mb_num * sizeof(uint16_t), fail)
178 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
179 big_mb_num * sizeof(uint8_t), fail)
180 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
181 16 * row_mb_num * sizeof(uint8_t), fail);
182 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
183 16 * row_mb_num * sizeof(uint8_t), fail);
184 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
185 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
187 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
188 4 * big_mb_num * sizeof(uint8_t), fail);
189 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
190 big_mb_num * sizeof(uint8_t), fail)
192 memset(h->slice_table_base, -1,
193 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
194 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
196 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
197 big_mb_num * sizeof(uint32_t), fail);
198 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
199 big_mb_num * sizeof(uint32_t), fail);
200 for (y = 0; y < h->mb_height; y++)
201 for (x = 0; x < h->mb_width; x++) {
202 const int mb_xy = x + y * h->mb_stride;
203 const int b_xy = 4 * x + 4 * y * h->b_stride;
205 h->mb2b_xy[mb_xy] = b_xy;
206 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
209 if (!h->dequant4_coeff[0])
210 ff_h264_init_dequant_tables(h);
215 ff_h264_free_tables(h);
216 return AVERROR(ENOMEM);
221 * Allocate buffers which are not shared amongst multiple threads.
223 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
225 ERContext *er = &sl->er;
226 int mb_array_size = h->mb_height * h->mb_stride;
227 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
228 int c_size = h->mb_stride * (h->mb_height + 1);
229 int yc_size = y_size + 2 * c_size;
232 sl->ref_cache[0][scan8[5] + 1] =
233 sl->ref_cache[0][scan8[7] + 1] =
234 sl->ref_cache[0][scan8[13] + 1] =
235 sl->ref_cache[1][scan8[5] + 1] =
236 sl->ref_cache[1][scan8[7] + 1] =
237 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
239 if (CONFIG_ERROR_RESILIENCE) {
241 er->avctx = h->avctx;
242 er->decode_mb = h264_er_decode_mb;
244 er->quarter_sample = 1;
246 er->mb_num = h->mb_num;
247 er->mb_width = h->mb_width;
248 er->mb_height = h->mb_height;
249 er->mb_stride = h->mb_stride;
250 er->b8_stride = h->mb_width * 2 + 1;
252 // error resilience code looks cleaner with this
253 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
254 (h->mb_num + 1) * sizeof(int), fail);
256 for (y = 0; y < h->mb_height; y++)
257 for (x = 0; x < h->mb_width; x++)
258 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
260 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
261 h->mb_stride + h->mb_width;
263 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
264 mb_array_size * sizeof(uint8_t), fail);
266 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
267 h->mb_height * h->mb_stride, fail);
269 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
270 yc_size * sizeof(int16_t), fail);
271 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
272 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
273 er->dc_val[2] = er->dc_val[1] + c_size;
274 for (i = 0; i < yc_size; i++)
275 sl->dc_val_base[i] = 1024;
281 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
284 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
285 int parse_extradata);
287 /* There are (invalid) samples in the wild with mp4-style extradata, where the
288 * parameter sets are stored unescaped (i.e. as RBSP).
289 * This function catches the parameter set decoding failure and tries again
290 * after escaping it */
291 static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
295 ret = decode_nal_units(h, buf, buf_size, 1);
296 if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
299 uint8_t *escaped_buf;
300 int escaped_buf_size;
302 av_log(h->avctx, AV_LOG_WARNING,
303 "SPS decoding failure, trying again after escaping the NAL\n");
305 if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
306 return AVERROR(ERANGE);
307 escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
308 escaped_buf = av_mallocz(escaped_buf_size);
310 return AVERROR(ENOMEM);
312 bytestream2_init(&gbc, buf, buf_size);
313 bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
315 while (bytestream2_get_bytes_left(&gbc)) {
316 if (bytestream2_get_bytes_left(&gbc) >= 3 &&
317 bytestream2_peek_be24(&gbc) <= 3) {
318 bytestream2_put_be24(&pbc, 3);
319 bytestream2_skip(&gbc, 2);
321 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
324 escaped_buf_size = bytestream2_tell_p(&pbc);
325 AV_WB16(escaped_buf, escaped_buf_size - 2);
327 ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
328 av_freep(&escaped_buf);
336 int ff_h264_decode_extradata(H264Context *h)
338 AVCodecContext *avctx = h->avctx;
341 if (avctx->extradata[0] == 1) {
343 unsigned char *p = avctx->extradata;
347 if (avctx->extradata_size < 7) {
348 av_log(avctx, AV_LOG_ERROR,
349 "avcC %d too short\n", avctx->extradata_size);
350 return AVERROR_INVALIDDATA;
352 /* sps and pps in the avcC always have length coded with 2 bytes,
353 * so put a fake nal_length_size = 2 while parsing them */
354 h->nal_length_size = 2;
355 // Decode sps from avcC
356 cnt = *(p + 5) & 0x1f; // Number of sps
358 for (i = 0; i < cnt; i++) {
359 nalsize = AV_RB16(p) + 2;
360 if (p - avctx->extradata + nalsize > avctx->extradata_size)
361 return AVERROR_INVALIDDATA;
362 ret = decode_extradata_ps_mp4(h, p, nalsize);
364 av_log(avctx, AV_LOG_ERROR,
365 "Decoding sps %d from avcC failed\n", i);
370 // Decode pps from avcC
371 cnt = *(p++); // Number of pps
372 for (i = 0; i < cnt; i++) {
373 nalsize = AV_RB16(p) + 2;
374 if (p - avctx->extradata + nalsize > avctx->extradata_size)
375 return AVERROR_INVALIDDATA;
376 ret = decode_extradata_ps_mp4(h, p, nalsize);
378 av_log(avctx, AV_LOG_ERROR,
379 "Decoding pps %d from avcC failed\n", i);
384 // Store right nal length size that will be used to parse all other nals
385 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
388 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
395 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
400 h->dequant_coeff_pps = -1;
402 h->picture_structure = PICT_FRAME;
403 h->slice_context_count = 1;
404 h->workaround_bugs = avctx->workaround_bugs;
405 h->flags = avctx->flags;
406 h->prev_poc_msb = 1 << 16;
408 h->recovery_frame = -1;
409 h->frame_recovered = 0;
411 h->next_outputed_poc = INT_MIN;
412 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
413 h->last_pocs[i] = INT_MIN;
415 ff_h264_reset_sei(h);
417 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
419 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
420 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
423 return AVERROR(ENOMEM);
426 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
427 h->DPB[i].f = av_frame_alloc();
429 return AVERROR(ENOMEM);
432 h->cur_pic.f = av_frame_alloc();
434 return AVERROR(ENOMEM);
436 for (i = 0; i < h->nb_slice_ctx; i++)
437 h->slice_ctx[i].h264 = h;
442 static AVOnce h264_vlc_init = AV_ONCE_INIT;
444 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
446 H264Context *h = avctx->priv_data;
449 ret = h264_init_context(avctx, h);
454 if (!avctx->has_b_frames)
457 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
459 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
460 return AVERROR_UNKNOWN;
463 if (avctx->codec_id == AV_CODEC_ID_H264) {
464 if (avctx->ticks_per_frame == 1)
465 h->avctx->framerate.num *= 2;
466 avctx->ticks_per_frame = 2;
469 if (avctx->extradata_size > 0 && avctx->extradata) {
470 ret = ff_h264_decode_extradata(h);
472 ff_h264_free_context(h);
477 if (h->sps.bitstream_restriction_flag &&
478 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
479 h->avctx->has_b_frames = h->sps.num_reorder_frames;
483 avctx->internal->allocate_progress = 1;
486 av_log(avctx, AV_LOG_WARNING,
487 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
488 "Use it at your own risk\n");
494 static int decode_init_thread_copy(AVCodecContext *avctx)
496 H264Context *h = avctx->priv_data;
499 if (!avctx->internal->is_copy)
502 memset(h, 0, sizeof(*h));
504 ret = h264_init_context(avctx, h);
508 h->context_initialized = 0;
514 * Run setup operations that must be run after slice header decoding.
515 * This includes finding the next displayed frame.
517 * @param h h264 master context
518 * @param setup_finished enough NALs have been read that we can call
519 * ff_thread_finish_setup()
521 static void decode_postinit(H264Context *h, int setup_finished)
523 H264Picture *out = h->cur_pic_ptr;
524 H264Picture *cur = h->cur_pic_ptr;
525 int i, pics, out_of_order, out_idx;
526 int invalid = 0, cnt = 0;
528 h->cur_pic_ptr->f->pict_type = h->pict_type;
530 if (h->next_output_pic)
533 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
534 /* FIXME: if we have two PAFF fields in one packet, we can't start
535 * the next thread here. If we have one field per packet, we can.
536 * The check in decode_nal_units() is not good enough to find this
537 * yet, so we assume the worst for now. */
538 // if (setup_finished)
539 // ff_thread_finish_setup(h->avctx);
543 cur->f->interlaced_frame = 0;
544 cur->f->repeat_pict = 0;
546 /* Signal interlacing information externally. */
547 /* Prioritize picture timing SEI information over used
548 * decoding process if it exists. */
550 if (h->sps.pic_struct_present_flag) {
551 switch (h->sei_pic_struct) {
552 case SEI_PIC_STRUCT_FRAME:
554 case SEI_PIC_STRUCT_TOP_FIELD:
555 case SEI_PIC_STRUCT_BOTTOM_FIELD:
556 cur->f->interlaced_frame = 1;
558 case SEI_PIC_STRUCT_TOP_BOTTOM:
559 case SEI_PIC_STRUCT_BOTTOM_TOP:
560 if (FIELD_OR_MBAFF_PICTURE(h))
561 cur->f->interlaced_frame = 1;
563 // try to flag soft telecine progressive
564 cur->f->interlaced_frame = h->prev_interlaced_frame;
566 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
567 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
568 /* Signal the possibility of telecined film externally
569 * (pic_struct 5,6). From these hints, let the applications
570 * decide if they apply deinterlacing. */
571 cur->f->repeat_pict = 1;
573 case SEI_PIC_STRUCT_FRAME_DOUBLING:
574 cur->f->repeat_pict = 2;
576 case SEI_PIC_STRUCT_FRAME_TRIPLING:
577 cur->f->repeat_pict = 4;
581 if ((h->sei_ct_type & 3) &&
582 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
583 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
585 /* Derive interlacing flag from used decoding process. */
586 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
588 h->prev_interlaced_frame = cur->f->interlaced_frame;
590 if (cur->field_poc[0] != cur->field_poc[1]) {
591 /* Derive top_field_first from field pocs. */
592 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
594 if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
595 /* Use picture timing SEI information. Even if it is a
596 * information of a past frame, better than nothing. */
597 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
598 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
599 cur->f->top_field_first = 1;
601 cur->f->top_field_first = 0;
603 /* Most likely progressive */
604 cur->f->top_field_first = 0;
608 if (h->sei_frame_packing_present &&
609 h->frame_packing_arrangement_type >= 0 &&
610 h->frame_packing_arrangement_type <= 6 &&
611 h->content_interpretation_type > 0 &&
612 h->content_interpretation_type < 3) {
613 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
617 switch (h->frame_packing_arrangement_type) {
619 stereo->type = AV_STEREO3D_CHECKERBOARD;
622 stereo->type = AV_STEREO3D_COLUMNS;
625 stereo->type = AV_STEREO3D_LINES;
628 if (h->quincunx_subsampling)
629 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
631 stereo->type = AV_STEREO3D_SIDEBYSIDE;
634 stereo->type = AV_STEREO3D_TOPBOTTOM;
637 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
640 stereo->type = AV_STEREO3D_2D;
644 if (h->content_interpretation_type == 2)
645 stereo->flags = AV_STEREO3D_FLAG_INVERT;
648 if (h->sei_display_orientation_present &&
649 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
650 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
651 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
652 AV_FRAME_DATA_DISPLAYMATRIX,
653 sizeof(int32_t) * 9);
657 av_display_rotation_set((int32_t *)rotation->data, angle);
658 av_display_matrix_flip((int32_t *)rotation->data,
659 h->sei_hflip, h->sei_vflip);
662 if (h->sei_reguserdata_afd_present) {
663 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
668 *sd->data = h->active_format_description;
669 h->sei_reguserdata_afd_present = 0;
672 if (h->a53_caption) {
673 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
674 AV_FRAME_DATA_A53_CC,
675 h->a53_caption_size);
679 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
680 av_freep(&h->a53_caption);
681 h->a53_caption_size = 0;
684 // FIXME do something with unavailable reference frames
686 /* Sort B-frames into display order */
687 if (h->sps.bitstream_restriction_flag ||
688 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
689 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
691 h->low_delay = !h->avctx->has_b_frames;
694 while (h->delayed_pic[pics])
697 assert(pics <= MAX_DELAYED_PIC_COUNT);
699 h->delayed_pic[pics++] = cur;
700 if (cur->reference == 0)
701 cur->reference = DELAYED_PIC_REF;
703 /* Frame reordering. This code takes pictures from coding order and sorts
704 * them by their incremental POC value into display order. It supports POC
705 * gaps, MMCO reset codes and random resets.
706 * A "display group" can start either with a IDR frame (f.key_frame = 1),
707 * and/or can be closed down with a MMCO reset code. In sequences where
708 * there is no delay, we can't detect that (since the frame was already
709 * output to the user), so we also set h->mmco_reset to detect the MMCO
711 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
712 * we increase the delay between input and output. All frames affected by
713 * the lag (e.g. those that should have been output before another frame
714 * that we already returned to the user) will be dropped. This is a bug
715 * that we will fix later. */
716 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
717 cnt += out->poc < h->last_pocs[i];
718 invalid += out->poc == INT_MIN;
720 if (!h->mmco_reset && !cur->f->key_frame &&
721 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
724 h->delayed_pic[pics - 2]->mmco_reset = 2;
726 if (h->mmco_reset || cur->f->key_frame) {
727 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
728 h->last_pocs[i] = INT_MIN;
730 invalid = MAX_DELAYED_PIC_COUNT;
732 out = h->delayed_pic[0];
734 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
736 !h->delayed_pic[i - 1]->mmco_reset &&
737 !h->delayed_pic[i]->f->key_frame;
739 if (h->delayed_pic[i]->poc < out->poc) {
740 out = h->delayed_pic[i];
743 if (h->avctx->has_b_frames == 0 &&
744 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
745 h->next_outputed_poc = INT_MIN;
746 out_of_order = !out->f->key_frame && !h->mmco_reset &&
747 (out->poc < h->next_outputed_poc);
749 if (h->sps.bitstream_restriction_flag &&
750 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
751 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
752 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
753 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
754 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
757 } else if (h->low_delay &&
758 ((h->next_outputed_poc != INT_MIN &&
759 out->poc > h->next_outputed_poc + 2) ||
760 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
762 h->avctx->has_b_frames++;
765 if (pics > h->avctx->has_b_frames) {
766 out->reference &= ~DELAYED_PIC_REF;
767 // for frame threading, the owner must be the second field's thread or
768 // else the first thread can release the picture and reuse it unsafely
769 for (i = out_idx; h->delayed_pic[i]; i++)
770 h->delayed_pic[i] = h->delayed_pic[i + 1];
772 memmove(h->last_pocs, &h->last_pocs[1],
773 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
774 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
775 if (!out_of_order && pics > h->avctx->has_b_frames) {
776 h->next_output_pic = out;
777 if (out->mmco_reset) {
779 h->next_outputed_poc = out->poc;
780 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
782 h->next_outputed_poc = INT_MIN;
785 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
786 h->next_outputed_poc = INT_MIN;
788 h->next_outputed_poc = out->poc;
793 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
796 if (h->next_output_pic) {
797 if (h->next_output_pic->recovered) {
798 // We have reached an recovery point and all frames after it in
799 // display order are "recovered".
800 h->frame_recovered |= FRAME_RECOVERED_SEI;
802 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
805 if (setup_finished && !h->avctx->hwaccel) {
806 ff_thread_finish_setup(h->avctx);
808 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
809 h->setup_finished = 1;
814 * instantaneous decoder refresh.
816 static void idr(H264Context *h)
818 ff_h264_remove_all_refs(h);
820 h->prev_frame_num_offset =
825 /* forget old pics after a seek */
826 void ff_h264_flush_change(H264Context *h)
829 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
830 h->last_pocs[i] = INT_MIN;
831 h->next_outputed_poc = INT_MIN;
832 h->prev_interlaced_frame = 1;
835 h->cur_pic_ptr->reference = 0;
837 ff_h264_reset_sei(h);
838 h->recovery_frame = -1;
839 h->frame_recovered = 0;
842 /* forget old pics after a seek */
843 static void flush_dpb(AVCodecContext *avctx)
845 H264Context *h = avctx->priv_data;
848 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
850 ff_h264_flush_change(h);
852 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
853 ff_h264_unref_picture(h, &h->DPB[i]);
854 h->cur_pic_ptr = NULL;
855 ff_h264_unref_picture(h, &h->cur_pic);
859 ff_h264_free_tables(h);
860 h->context_initialized = 0;
863 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
865 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
868 h->frame_num_offset = h->prev_frame_num_offset;
869 if (h->frame_num < h->prev_frame_num)
870 h->frame_num_offset += max_frame_num;
872 if (h->sps.poc_type == 0) {
873 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
875 if (h->poc_lsb < h->prev_poc_lsb &&
876 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
877 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
878 else if (h->poc_lsb > h->prev_poc_lsb &&
879 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
880 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
882 h->poc_msb = h->prev_poc_msb;
884 field_poc[1] = h->poc_msb + h->poc_lsb;
885 if (h->picture_structure == PICT_FRAME)
886 field_poc[1] += h->delta_poc_bottom;
887 } else if (h->sps.poc_type == 1) {
888 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
891 if (h->sps.poc_cycle_length != 0)
892 abs_frame_num = h->frame_num_offset + h->frame_num;
896 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
899 expected_delta_per_poc_cycle = 0;
900 for (i = 0; i < h->sps.poc_cycle_length; i++)
901 // FIXME integrate during sps parse
902 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
904 if (abs_frame_num > 0) {
905 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
906 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
908 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
909 for (i = 0; i <= frame_num_in_poc_cycle; i++)
910 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
914 if (h->nal_ref_idc == 0)
915 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
917 field_poc[0] = expectedpoc + h->delta_poc[0];
918 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
920 if (h->picture_structure == PICT_FRAME)
921 field_poc[1] += h->delta_poc[1];
923 int poc = 2 * (h->frame_num_offset + h->frame_num);
932 if (h->picture_structure != PICT_BOTTOM_FIELD)
933 pic_field_poc[0] = field_poc[0];
934 if (h->picture_structure != PICT_TOP_FIELD)
935 pic_field_poc[1] = field_poc[1];
936 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
942 * Compute profile from profile_idc and constraint_set?_flags.
946 * @return profile as defined by FF_PROFILE_H264_*
948 int ff_h264_get_profile(SPS *sps)
950 int profile = sps->profile_idc;
952 switch (sps->profile_idc) {
953 case FF_PROFILE_H264_BASELINE:
954 // constraint_set1_flag set to 1
955 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
957 case FF_PROFILE_H264_HIGH_10:
958 case FF_PROFILE_H264_HIGH_422:
959 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
960 // constraint_set3_flag set to 1
961 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
968 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
970 int ref_count[2], list_count;
971 int num_ref_idx_active_override_flag, max_refs;
973 // set defaults, might be overridden a few lines later
974 ref_count[0] = h->pps.ref_count[0];
975 ref_count[1] = h->pps.ref_count[1];
977 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
978 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
980 if (num_ref_idx_active_override_flag) {
981 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
982 if (ref_count[0] < 1)
983 return AVERROR_INVALIDDATA;
984 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
985 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
986 if (ref_count[1] < 1)
987 return AVERROR_INVALIDDATA;
991 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
997 ref_count[0] = ref_count[1] = 0;
1000 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1002 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1003 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1004 sl->ref_count[0] = sl->ref_count[1] = 0;
1005 return AVERROR_INVALIDDATA;
1008 if (list_count != sl->list_count ||
1009 ref_count[0] != sl->ref_count[0] ||
1010 ref_count[1] != sl->ref_count[1]) {
1011 sl->ref_count[0] = ref_count[0];
1012 sl->ref_count[1] = ref_count[1];
1013 sl->list_count = list_count;
1020 static int get_last_needed_nal(H264Context *h)
1022 int nals_needed = 0;
1025 for (i = 0; i < h->pkt.nb_nals; i++) {
1026 H2645NAL *nal = &h->pkt.nals[i];
1029 /* packets can sometimes contain multiple PPS/SPS,
1030 * e.g. two PAFF field pictures in one packet, or a demuxer
1031 * which splits NALs strangely if so, when frame threading we
1032 * can't start the next thread until we've read all of them */
1033 switch (nal->type) {
1041 init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
1042 if (!get_ue_golomb(&gb))
1050 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1051 int parse_extradata)
1053 AVCodecContext *const avctx = h->avctx;
1054 unsigned context_count = 0;
1055 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1058 h->max_contexts = h->slice_context_count;
1059 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1060 h->current_slice = 0;
1061 if (!h->first_field)
1062 h->cur_pic_ptr = NULL;
1063 ff_h264_reset_sei(h);
1066 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
1067 h->nal_length_size, avctx->codec_id);
1069 av_log(avctx, AV_LOG_ERROR,
1070 "Error splitting the input into NAL units.\n");
1074 if (avctx->active_thread_type & FF_THREAD_FRAME)
1075 nals_needed = get_last_needed_nal(h);
1077 for (i = 0; i < h->pkt.nb_nals; i++) {
1078 H2645NAL *nal = &h->pkt.nals[i];
1079 H264SliceContext *sl = &h->slice_ctx[context_count];
1082 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1083 nal->ref_idc == 0 && nal->type != NAL_SEI)
1087 /* Ignore every NAL unit type except PPS and SPS during extradata
1088 * parsing. Decoding slices is not possible in codec init
1090 if (parse_extradata && HAVE_THREADS &&
1091 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1092 (nal->type != NAL_PPS && nal->type != NAL_SPS)) {
1093 if (nal->type < NAL_AUD || nal->type > NAL_AUXILIARY_SLICE)
1094 av_log(avctx, AV_LOG_INFO,
1095 "Ignoring NAL unit %d during extradata parsing\n",
1097 nal->type = NAL_FF_IGNORE;
1100 // FIXME these should stop being context-global variables
1101 h->nal_ref_idc = nal->ref_idc;
1102 h->nal_unit_type = nal->type;
1105 switch (nal->type) {
1107 if (nal->type != NAL_IDR_SLICE) {
1108 av_log(h->avctx, AV_LOG_ERROR,
1109 "Invalid mix of idr and non-idr slices\n");
1113 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1117 if ((err = ff_h264_decode_slice_header(h, sl)))
1120 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1121 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1122 ((1 << h->sps.log2_max_frame_num) - 1);
1125 h->cur_pic_ptr->f->key_frame |=
1126 (nal->type == NAL_IDR_SLICE) || (h->sei_recovery_frame_cnt >= 0);
1128 if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->frame_num) {
1129 h->recovery_frame = -1;
1130 h->cur_pic_ptr->recovered = 1;
1132 // If we have an IDR, all frames after it in decoded order are
1134 if (nal->type == NAL_IDR_SLICE)
1135 h->frame_recovered |= FRAME_RECOVERED_IDR;
1136 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1138 if (h->current_slice == 1) {
1139 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1140 decode_postinit(h, i >= nals_needed);
1142 if (h->avctx->hwaccel &&
1143 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1147 if (sl->redundant_pic_count == 0 &&
1148 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1149 (avctx->skip_frame < AVDISCARD_BIDIR ||
1150 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1151 (avctx->skip_frame < AVDISCARD_NONKEY ||
1152 h->cur_pic_ptr->f->key_frame) &&
1153 avctx->skip_frame < AVDISCARD_ALL) {
1154 if (avctx->hwaccel) {
1155 ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
1165 avpriv_request_sample(avctx, "data partitioning");
1166 ret = AVERROR(ENOSYS);
1171 ret = ff_h264_decode_sei(h);
1172 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1177 ret = ff_h264_decode_seq_parameter_set(h);
1178 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1183 ret = ff_h264_decode_picture_parameter_set(h, nal->size_bits);
1184 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1188 case NAL_END_SEQUENCE:
1189 case NAL_END_STREAM:
1190 case NAL_FILLER_DATA:
1192 case NAL_AUXILIARY_SLICE:
1197 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1198 nal->type, nal->size_bits);
1201 if (context_count == h->max_contexts) {
1202 ret = ff_h264_execute_decode_slices(h, context_count);
1203 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1209 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1210 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1211 } else if (err == 1) {
1212 /* Slice could not be decoded in parallel mode, restart. Note
1213 * that rbsp_buffer is not transferred, but since we no longer
1214 * run in parallel mode this should not be an issue. */
1215 sl = &h->slice_ctx[0];
1219 if (context_count) {
1220 ret = ff_h264_execute_decode_slices(h, context_count);
1221 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1228 if (h->cur_pic_ptr && !h->droppable) {
1229 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1230 h->picture_structure == PICT_BOTTOM_FIELD);
1233 return (ret < 0) ? ret : buf_size;
1237 * Return the number of bytes consumed for building the current frame.
1239 static int get_consumed_bytes(int pos, int buf_size)
1242 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1243 if (pos + 10 > buf_size)
1244 pos = buf_size; // oops ;)
1249 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1252 int ret = av_frame_ref(dst, src);
1259 for (i = 0; i < 3; i++) {
1260 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1261 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1262 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1263 (h->sps.crop_top >> vshift) * dst->linesize[i];
1264 dst->data[i] += off;
1269 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1270 int *got_frame, AVPacket *avpkt)
1272 const uint8_t *buf = avpkt->data;
1273 int buf_size = avpkt->size;
1274 H264Context *h = avctx->priv_data;
1275 AVFrame *pict = data;
1279 h->flags = avctx->flags;
1280 h->setup_finished = 0;
1282 /* end of stream, output what is still in the buffers */
1284 if (buf_size == 0) {
1288 h->cur_pic_ptr = NULL;
1290 // FIXME factorize this with the output code below
1291 out = h->delayed_pic[0];
1294 h->delayed_pic[i] &&
1295 !h->delayed_pic[i]->f->key_frame &&
1296 !h->delayed_pic[i]->mmco_reset;
1298 if (h->delayed_pic[i]->poc < out->poc) {
1299 out = h->delayed_pic[i];
1303 for (i = out_idx; h->delayed_pic[i]; i++)
1304 h->delayed_pic[i] = h->delayed_pic[i + 1];
1307 ret = output_frame(h, pict, out->f);
1316 buf_index = decode_nal_units(h, buf, buf_size, 0);
1318 return AVERROR_INVALIDDATA;
1320 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1325 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1326 if (avctx->skip_frame >= AVDISCARD_NONREF)
1328 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1329 return AVERROR_INVALIDDATA;
1332 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1333 (h->mb_y >= h->mb_height && h->mb_height)) {
1334 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1335 decode_postinit(h, 1);
1337 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1340 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1341 h->next_output_pic->recovered)) {
1342 if (!h->next_output_pic->recovered)
1343 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1345 ret = output_frame(h, pict, h->next_output_pic->f);
1352 assert(pict->buf[0] || !*got_frame);
1354 return get_consumed_bytes(buf_index, buf_size);
1357 av_cold void ff_h264_free_context(H264Context *h)
1361 ff_h264_free_tables(h);
1363 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1364 ff_h264_unref_picture(h, &h->DPB[i]);
1365 av_frame_free(&h->DPB[i].f);
1368 h->cur_pic_ptr = NULL;
1370 for (i = 0; i < h->nb_slice_ctx; i++)
1371 av_freep(&h->slice_ctx[i].rbsp_buffer);
1372 av_freep(&h->slice_ctx);
1373 h->nb_slice_ctx = 0;
1375 for (i = 0; i < MAX_SPS_COUNT; i++)
1376 av_freep(h->sps_buffers + i);
1378 for (i = 0; i < MAX_PPS_COUNT; i++)
1379 av_freep(h->pps_buffers + i);
1381 ff_h2645_packet_uninit(&h->pkt);
1384 static av_cold int h264_decode_end(AVCodecContext *avctx)
1386 H264Context *h = avctx->priv_data;
1388 ff_h264_free_context(h);
1390 ff_h264_unref_picture(h, &h->cur_pic);
1391 av_frame_free(&h->cur_pic.f);
1396 #define OFFSET(x) offsetof(H264Context, x)
1397 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1398 static const AVOption h264_options[] = {
1399 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1403 static const AVClass h264_class = {
1404 .class_name = "h264",
1405 .item_name = av_default_item_name,
1406 .option = h264_options,
1407 .version = LIBAVUTIL_VERSION_INT,
1410 AVCodec ff_h264_decoder = {
1412 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1413 .type = AVMEDIA_TYPE_VIDEO,
1414 .id = AV_CODEC_ID_H264,
1415 .priv_data_size = sizeof(H264Context),
1416 .init = ff_h264_decode_init,
1417 .close = h264_decode_end,
1418 .decode = h264_decode_frame,
1419 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1420 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1421 AV_CODEC_CAP_FRAME_THREADS,
1422 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1424 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1425 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1426 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1427 .priv_class = &h264_class,