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)));
212 ff_h264_free_tables(h);
213 return AVERROR(ENOMEM);
218 * Allocate buffers which are not shared amongst multiple threads.
220 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
222 ERContext *er = &sl->er;
223 int mb_array_size = h->mb_height * h->mb_stride;
224 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
225 int c_size = h->mb_stride * (h->mb_height + 1);
226 int yc_size = y_size + 2 * c_size;
229 sl->ref_cache[0][scan8[5] + 1] =
230 sl->ref_cache[0][scan8[7] + 1] =
231 sl->ref_cache[0][scan8[13] + 1] =
232 sl->ref_cache[1][scan8[5] + 1] =
233 sl->ref_cache[1][scan8[7] + 1] =
234 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
236 if (CONFIG_ERROR_RESILIENCE) {
238 er->avctx = h->avctx;
239 er->decode_mb = h264_er_decode_mb;
241 er->quarter_sample = 1;
243 er->mb_num = h->mb_num;
244 er->mb_width = h->mb_width;
245 er->mb_height = h->mb_height;
246 er->mb_stride = h->mb_stride;
247 er->b8_stride = h->mb_width * 2 + 1;
249 // error resilience code looks cleaner with this
250 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
251 (h->mb_num + 1) * sizeof(int), fail);
253 for (y = 0; y < h->mb_height; y++)
254 for (x = 0; x < h->mb_width; x++)
255 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
257 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
258 h->mb_stride + h->mb_width;
260 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
261 mb_array_size * sizeof(uint8_t), fail);
263 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
264 h->mb_height * h->mb_stride, fail);
266 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
267 yc_size * sizeof(int16_t), fail);
268 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
269 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
270 er->dc_val[2] = er->dc_val[1] + c_size;
271 for (i = 0; i < yc_size; i++)
272 sl->dc_val_base[i] = 1024;
278 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
281 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
282 int parse_extradata);
284 /* There are (invalid) samples in the wild with mp4-style extradata, where the
285 * parameter sets are stored unescaped (i.e. as RBSP).
286 * This function catches the parameter set decoding failure and tries again
287 * after escaping it */
288 static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
292 ret = decode_nal_units(h, buf, buf_size, 1);
293 if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
296 uint8_t *escaped_buf;
297 int escaped_buf_size;
299 av_log(h->avctx, AV_LOG_WARNING,
300 "SPS decoding failure, trying again after escaping the NAL\n");
302 if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
303 return AVERROR(ERANGE);
304 escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
305 escaped_buf = av_mallocz(escaped_buf_size);
307 return AVERROR(ENOMEM);
309 bytestream2_init(&gbc, buf, buf_size);
310 bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
312 while (bytestream2_get_bytes_left(&gbc)) {
313 if (bytestream2_get_bytes_left(&gbc) >= 3 &&
314 bytestream2_peek_be24(&gbc) <= 3) {
315 bytestream2_put_be24(&pbc, 3);
316 bytestream2_skip(&gbc, 2);
318 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
321 escaped_buf_size = bytestream2_tell_p(&pbc);
322 AV_WB16(escaped_buf, escaped_buf_size - 2);
324 ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
325 av_freep(&escaped_buf);
333 int ff_h264_decode_extradata(H264Context *h)
335 AVCodecContext *avctx = h->avctx;
338 if (avctx->extradata[0] == 1) {
340 unsigned char *p = avctx->extradata;
344 if (avctx->extradata_size < 7) {
345 av_log(avctx, AV_LOG_ERROR,
346 "avcC %d too short\n", avctx->extradata_size);
347 return AVERROR_INVALIDDATA;
349 /* sps and pps in the avcC always have length coded with 2 bytes,
350 * so put a fake nal_length_size = 2 while parsing them */
351 h->nal_length_size = 2;
352 // Decode sps from avcC
353 cnt = *(p + 5) & 0x1f; // Number of sps
355 for (i = 0; i < cnt; i++) {
356 nalsize = AV_RB16(p) + 2;
357 if (p - avctx->extradata + nalsize > avctx->extradata_size)
358 return AVERROR_INVALIDDATA;
359 ret = decode_extradata_ps_mp4(h, p, nalsize);
361 av_log(avctx, AV_LOG_ERROR,
362 "Decoding sps %d from avcC failed\n", i);
367 // Decode pps from avcC
368 cnt = *(p++); // Number of pps
369 for (i = 0; i < cnt; i++) {
370 nalsize = AV_RB16(p) + 2;
371 if (p - avctx->extradata + nalsize > avctx->extradata_size)
372 return AVERROR_INVALIDDATA;
373 ret = decode_extradata_ps_mp4(h, p, nalsize);
375 av_log(avctx, AV_LOG_ERROR,
376 "Decoding pps %d from avcC failed\n", i);
381 // Store right nal length size that will be used to parse all other nals
382 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
385 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
392 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
398 h->picture_structure = PICT_FRAME;
399 h->slice_context_count = 1;
400 h->workaround_bugs = avctx->workaround_bugs;
401 h->flags = avctx->flags;
402 h->poc.prev_poc_msb = 1 << 16;
404 h->recovery_frame = -1;
405 h->frame_recovered = 0;
407 h->next_outputed_poc = INT_MIN;
408 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
409 h->last_pocs[i] = INT_MIN;
411 ff_h264_reset_sei(h);
413 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
415 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
416 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
419 return AVERROR(ENOMEM);
422 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
423 h->DPB[i].f = av_frame_alloc();
425 return AVERROR(ENOMEM);
428 h->cur_pic.f = av_frame_alloc();
430 return AVERROR(ENOMEM);
432 for (i = 0; i < h->nb_slice_ctx; i++)
433 h->slice_ctx[i].h264 = h;
438 static AVOnce h264_vlc_init = AV_ONCE_INIT;
440 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
442 H264Context *h = avctx->priv_data;
445 ret = h264_init_context(avctx, h);
450 if (!avctx->has_b_frames)
453 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
455 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
456 return AVERROR_UNKNOWN;
459 if (avctx->codec_id == AV_CODEC_ID_H264) {
460 if (avctx->ticks_per_frame == 1)
461 h->avctx->framerate.num *= 2;
462 avctx->ticks_per_frame = 2;
465 if (avctx->extradata_size > 0 && avctx->extradata) {
466 ret = ff_h264_decode_extradata(h);
468 ff_h264_free_context(h);
473 if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
474 h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
475 h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
479 avctx->internal->allocate_progress = 1;
482 av_log(avctx, AV_LOG_WARNING,
483 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
484 "Use it at your own risk\n");
490 static int decode_init_thread_copy(AVCodecContext *avctx)
492 H264Context *h = avctx->priv_data;
495 if (!avctx->internal->is_copy)
498 memset(h, 0, sizeof(*h));
500 ret = h264_init_context(avctx, h);
504 h->context_initialized = 0;
510 * Run setup operations that must be run after slice header decoding.
511 * This includes finding the next displayed frame.
513 * @param h h264 master context
514 * @param setup_finished enough NALs have been read that we can call
515 * ff_thread_finish_setup()
517 static void decode_postinit(H264Context *h, int setup_finished)
519 const SPS *sps = h->ps.sps;
520 H264Picture *out = h->cur_pic_ptr;
521 H264Picture *cur = h->cur_pic_ptr;
522 int i, pics, out_of_order, out_idx;
523 int invalid = 0, cnt = 0;
525 h->cur_pic_ptr->f->pict_type = h->pict_type;
527 if (h->next_output_pic)
530 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
531 /* FIXME: if we have two PAFF fields in one packet, we can't start
532 * the next thread here. If we have one field per packet, we can.
533 * The check in decode_nal_units() is not good enough to find this
534 * yet, so we assume the worst for now. */
535 // if (setup_finished)
536 // ff_thread_finish_setup(h->avctx);
540 cur->f->interlaced_frame = 0;
541 cur->f->repeat_pict = 0;
543 /* Signal interlacing information externally. */
544 /* Prioritize picture timing SEI information over used
545 * decoding process if it exists. */
547 if (sps->pic_struct_present_flag) {
548 switch (h->sei_pic_struct) {
549 case SEI_PIC_STRUCT_FRAME:
551 case SEI_PIC_STRUCT_TOP_FIELD:
552 case SEI_PIC_STRUCT_BOTTOM_FIELD:
553 cur->f->interlaced_frame = 1;
555 case SEI_PIC_STRUCT_TOP_BOTTOM:
556 case SEI_PIC_STRUCT_BOTTOM_TOP:
557 if (FIELD_OR_MBAFF_PICTURE(h))
558 cur->f->interlaced_frame = 1;
560 // try to flag soft telecine progressive
561 cur->f->interlaced_frame = h->prev_interlaced_frame;
563 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
564 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
565 /* Signal the possibility of telecined film externally
566 * (pic_struct 5,6). From these hints, let the applications
567 * decide if they apply deinterlacing. */
568 cur->f->repeat_pict = 1;
570 case SEI_PIC_STRUCT_FRAME_DOUBLING:
571 cur->f->repeat_pict = 2;
573 case SEI_PIC_STRUCT_FRAME_TRIPLING:
574 cur->f->repeat_pict = 4;
578 if ((h->sei_ct_type & 3) &&
579 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
580 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
582 /* Derive interlacing flag from used decoding process. */
583 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
585 h->prev_interlaced_frame = cur->f->interlaced_frame;
587 if (cur->field_poc[0] != cur->field_poc[1]) {
588 /* Derive top_field_first from field pocs. */
589 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
591 if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
592 /* Use picture timing SEI information. Even if it is a
593 * information of a past frame, better than nothing. */
594 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
595 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
596 cur->f->top_field_first = 1;
598 cur->f->top_field_first = 0;
600 /* Most likely progressive */
601 cur->f->top_field_first = 0;
605 if (h->sei_frame_packing_present &&
606 h->frame_packing_arrangement_type >= 0 &&
607 h->frame_packing_arrangement_type <= 6 &&
608 h->content_interpretation_type > 0 &&
609 h->content_interpretation_type < 3) {
610 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
614 switch (h->frame_packing_arrangement_type) {
616 stereo->type = AV_STEREO3D_CHECKERBOARD;
619 stereo->type = AV_STEREO3D_COLUMNS;
622 stereo->type = AV_STEREO3D_LINES;
625 if (h->quincunx_subsampling)
626 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
628 stereo->type = AV_STEREO3D_SIDEBYSIDE;
631 stereo->type = AV_STEREO3D_TOPBOTTOM;
634 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
637 stereo->type = AV_STEREO3D_2D;
641 if (h->content_interpretation_type == 2)
642 stereo->flags = AV_STEREO3D_FLAG_INVERT;
645 if (h->sei_display_orientation_present &&
646 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
647 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
648 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
649 AV_FRAME_DATA_DISPLAYMATRIX,
650 sizeof(int32_t) * 9);
654 av_display_rotation_set((int32_t *)rotation->data, angle);
655 av_display_matrix_flip((int32_t *)rotation->data,
656 h->sei_hflip, h->sei_vflip);
659 if (h->sei_reguserdata_afd_present) {
660 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
665 *sd->data = h->active_format_description;
666 h->sei_reguserdata_afd_present = 0;
669 if (h->a53_caption) {
670 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
671 AV_FRAME_DATA_A53_CC,
672 h->a53_caption_size);
676 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
677 av_freep(&h->a53_caption);
678 h->a53_caption_size = 0;
681 // FIXME do something with unavailable reference frames
683 /* Sort B-frames into display order */
684 if (sps->bitstream_restriction_flag ||
685 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
686 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
688 h->low_delay = !h->avctx->has_b_frames;
691 while (h->delayed_pic[pics])
694 assert(pics <= MAX_DELAYED_PIC_COUNT);
696 h->delayed_pic[pics++] = cur;
697 if (cur->reference == 0)
698 cur->reference = DELAYED_PIC_REF;
700 /* Frame reordering. This code takes pictures from coding order and sorts
701 * them by their incremental POC value into display order. It supports POC
702 * gaps, MMCO reset codes and random resets.
703 * A "display group" can start either with a IDR frame (f.key_frame = 1),
704 * and/or can be closed down with a MMCO reset code. In sequences where
705 * there is no delay, we can't detect that (since the frame was already
706 * output to the user), so we also set h->mmco_reset to detect the MMCO
708 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
709 * we increase the delay between input and output. All frames affected by
710 * the lag (e.g. those that should have been output before another frame
711 * that we already returned to the user) will be dropped. This is a bug
712 * that we will fix later. */
713 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
714 cnt += out->poc < h->last_pocs[i];
715 invalid += out->poc == INT_MIN;
717 if (!h->mmco_reset && !cur->f->key_frame &&
718 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
721 h->delayed_pic[pics - 2]->mmco_reset = 2;
723 if (h->mmco_reset || cur->f->key_frame) {
724 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
725 h->last_pocs[i] = INT_MIN;
727 invalid = MAX_DELAYED_PIC_COUNT;
729 out = h->delayed_pic[0];
731 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
733 !h->delayed_pic[i - 1]->mmco_reset &&
734 !h->delayed_pic[i]->f->key_frame;
736 if (h->delayed_pic[i]->poc < out->poc) {
737 out = h->delayed_pic[i];
740 if (h->avctx->has_b_frames == 0 &&
741 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
742 h->next_outputed_poc = INT_MIN;
743 out_of_order = !out->f->key_frame && !h->mmco_reset &&
744 (out->poc < h->next_outputed_poc);
746 if (sps->bitstream_restriction_flag &&
747 h->avctx->has_b_frames >= sps->num_reorder_frames) {
748 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
749 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
750 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
751 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
754 } else if (h->low_delay &&
755 ((h->next_outputed_poc != INT_MIN &&
756 out->poc > h->next_outputed_poc + 2) ||
757 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
759 h->avctx->has_b_frames++;
762 if (pics > h->avctx->has_b_frames) {
763 out->reference &= ~DELAYED_PIC_REF;
764 // for frame threading, the owner must be the second field's thread or
765 // else the first thread can release the picture and reuse it unsafely
766 for (i = out_idx; h->delayed_pic[i]; i++)
767 h->delayed_pic[i] = h->delayed_pic[i + 1];
769 memmove(h->last_pocs, &h->last_pocs[1],
770 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
771 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
772 if (!out_of_order && pics > h->avctx->has_b_frames) {
773 h->next_output_pic = out;
774 if (out->mmco_reset) {
776 h->next_outputed_poc = out->poc;
777 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
779 h->next_outputed_poc = INT_MIN;
782 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
783 h->next_outputed_poc = INT_MIN;
785 h->next_outputed_poc = out->poc;
790 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
793 if (h->next_output_pic) {
794 if (h->next_output_pic->recovered) {
795 // We have reached an recovery point and all frames after it in
796 // display order are "recovered".
797 h->frame_recovered |= FRAME_RECOVERED_SEI;
799 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
802 if (setup_finished && !h->avctx->hwaccel) {
803 ff_thread_finish_setup(h->avctx);
805 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
806 h->setup_finished = 1;
811 * instantaneous decoder refresh.
813 static void idr(H264Context *h)
815 ff_h264_remove_all_refs(h);
816 h->poc.prev_frame_num =
817 h->poc.prev_frame_num_offset =
818 h->poc.prev_poc_msb =
819 h->poc.prev_poc_lsb = 0;
822 /* forget old pics after a seek */
823 void ff_h264_flush_change(H264Context *h)
826 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
827 h->last_pocs[i] = INT_MIN;
828 h->next_outputed_poc = INT_MIN;
829 h->prev_interlaced_frame = 1;
832 h->cur_pic_ptr->reference = 0;
834 ff_h264_reset_sei(h);
835 h->recovery_frame = -1;
836 h->frame_recovered = 0;
839 /* forget old pics after a seek */
840 static void flush_dpb(AVCodecContext *avctx)
842 H264Context *h = avctx->priv_data;
845 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
847 ff_h264_flush_change(h);
849 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
850 ff_h264_unref_picture(h, &h->DPB[i]);
851 h->cur_pic_ptr = NULL;
852 ff_h264_unref_picture(h, &h->cur_pic);
856 ff_h264_free_tables(h);
857 h->context_initialized = 0;
861 * Compute profile from profile_idc and constraint_set?_flags.
865 * @return profile as defined by FF_PROFILE_H264_*
867 int ff_h264_get_profile(const SPS *sps)
869 int profile = sps->profile_idc;
871 switch (sps->profile_idc) {
872 case FF_PROFILE_H264_BASELINE:
873 // constraint_set1_flag set to 1
874 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
876 case FF_PROFILE_H264_HIGH_10:
877 case FF_PROFILE_H264_HIGH_422:
878 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
879 // constraint_set3_flag set to 1
880 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
887 static int get_last_needed_nal(H264Context *h)
892 for (i = 0; i < h->pkt.nb_nals; i++) {
893 H2645NAL *nal = &h->pkt.nals[i];
896 /* packets can sometimes contain multiple PPS/SPS,
897 * e.g. two PAFF field pictures in one packet, or a demuxer
898 * which splits NALs strangely if so, when frame threading we
899 * can't start the next thread until we've read all of them */
908 init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
909 if (!get_ue_golomb(&gb))
917 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
920 AVCodecContext *const avctx = h->avctx;
921 unsigned context_count = 0;
922 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
925 h->max_contexts = h->slice_context_count;
926 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
927 h->current_slice = 0;
929 h->cur_pic_ptr = NULL;
930 ff_h264_reset_sei(h);
933 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
934 h->nal_length_size, avctx->codec_id);
936 av_log(avctx, AV_LOG_ERROR,
937 "Error splitting the input into NAL units.\n");
941 if (avctx->active_thread_type & FF_THREAD_FRAME)
942 nals_needed = get_last_needed_nal(h);
944 for (i = 0; i < h->pkt.nb_nals; i++) {
945 H2645NAL *nal = &h->pkt.nals[i];
946 H264SliceContext *sl = &h->slice_ctx[context_count];
949 if (avctx->skip_frame >= AVDISCARD_NONREF &&
950 nal->ref_idc == 0 && nal->type != NAL_SEI)
954 /* Ignore every NAL unit type except PPS and SPS during extradata
955 * parsing. Decoding slices is not possible in codec init
957 if (parse_extradata && HAVE_THREADS &&
958 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
959 (nal->type != NAL_PPS && nal->type != NAL_SPS)) {
960 if (nal->type < NAL_AUD || nal->type > NAL_AUXILIARY_SLICE)
961 av_log(avctx, AV_LOG_INFO,
962 "Ignoring NAL unit %d during extradata parsing\n",
964 nal->type = NAL_FF_IGNORE;
967 // FIXME these should stop being context-global variables
968 h->nal_ref_idc = nal->ref_idc;
969 h->nal_unit_type = nal->type;
974 if (nal->type != NAL_IDR_SLICE) {
975 av_log(h->avctx, AV_LOG_ERROR,
976 "Invalid mix of idr and non-idr slices\n");
980 idr(h); // FIXME ensure we don't lose some frames if there is reordering
984 if ((err = ff_h264_decode_slice_header(h, sl)))
987 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
988 h->recovery_frame = (h->poc.frame_num + h->sei_recovery_frame_cnt) &
989 ((1 << h->ps.sps->log2_max_frame_num) - 1);
992 h->cur_pic_ptr->f->key_frame |=
993 (nal->type == NAL_IDR_SLICE) || (h->sei_recovery_frame_cnt >= 0);
995 if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
996 h->recovery_frame = -1;
997 h->cur_pic_ptr->recovered = 1;
999 // If we have an IDR, all frames after it in decoded order are
1001 if (nal->type == NAL_IDR_SLICE)
1002 h->frame_recovered |= FRAME_RECOVERED_IDR;
1003 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1005 if (h->current_slice == 1) {
1006 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1007 decode_postinit(h, i >= nals_needed);
1009 if (h->avctx->hwaccel &&
1010 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1014 if (sl->redundant_pic_count == 0 &&
1015 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1016 (avctx->skip_frame < AVDISCARD_BIDIR ||
1017 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1018 (avctx->skip_frame < AVDISCARD_NONKEY ||
1019 h->cur_pic_ptr->f->key_frame) &&
1020 avctx->skip_frame < AVDISCARD_ALL) {
1021 if (avctx->hwaccel) {
1022 ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
1032 avpriv_request_sample(avctx, "data partitioning");
1033 ret = AVERROR(ENOSYS);
1038 ret = ff_h264_decode_sei(h);
1039 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1043 ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
1044 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1048 ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
1050 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1054 case NAL_END_SEQUENCE:
1055 case NAL_END_STREAM:
1056 case NAL_FILLER_DATA:
1058 case NAL_AUXILIARY_SLICE:
1063 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1064 nal->type, nal->size_bits);
1067 if (context_count == h->max_contexts) {
1068 ret = ff_h264_execute_decode_slices(h, context_count);
1069 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1075 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1076 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1077 } else if (err == 1) {
1078 /* Slice could not be decoded in parallel mode, restart. Note
1079 * that rbsp_buffer is not transferred, but since we no longer
1080 * run in parallel mode this should not be an issue. */
1081 sl = &h->slice_ctx[0];
1085 if (context_count) {
1086 ret = ff_h264_execute_decode_slices(h, context_count);
1087 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1094 if (h->cur_pic_ptr && !h->droppable) {
1095 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1096 h->picture_structure == PICT_BOTTOM_FIELD);
1099 return (ret < 0) ? ret : buf_size;
1103 * Return the number of bytes consumed for building the current frame.
1105 static int get_consumed_bytes(int pos, int buf_size)
1108 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1109 if (pos + 10 > buf_size)
1110 pos = buf_size; // oops ;)
1115 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1118 int ret = av_frame_ref(dst, src);
1122 if (!h->ps.sps || !h->ps.sps->crop)
1125 for (i = 0; i < 3; i++) {
1126 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1127 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1128 int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
1129 (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
1130 dst->data[i] += off;
1135 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1136 int *got_frame, AVPacket *avpkt)
1138 const uint8_t *buf = avpkt->data;
1139 int buf_size = avpkt->size;
1140 H264Context *h = avctx->priv_data;
1141 AVFrame *pict = data;
1145 h->flags = avctx->flags;
1146 h->setup_finished = 0;
1148 /* end of stream, output what is still in the buffers */
1150 if (buf_size == 0) {
1154 h->cur_pic_ptr = NULL;
1156 // FIXME factorize this with the output code below
1157 out = h->delayed_pic[0];
1160 h->delayed_pic[i] &&
1161 !h->delayed_pic[i]->f->key_frame &&
1162 !h->delayed_pic[i]->mmco_reset;
1164 if (h->delayed_pic[i]->poc < out->poc) {
1165 out = h->delayed_pic[i];
1169 for (i = out_idx; h->delayed_pic[i]; i++)
1170 h->delayed_pic[i] = h->delayed_pic[i + 1];
1173 ret = output_frame(h, pict, out->f);
1182 buf_index = decode_nal_units(h, buf, buf_size, 0);
1184 return AVERROR_INVALIDDATA;
1186 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1191 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1192 if (avctx->skip_frame >= AVDISCARD_NONREF)
1194 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1195 return AVERROR_INVALIDDATA;
1198 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1199 (h->mb_y >= h->mb_height && h->mb_height)) {
1200 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1201 decode_postinit(h, 1);
1203 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1206 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1207 h->next_output_pic->recovered)) {
1208 if (!h->next_output_pic->recovered)
1209 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1211 ret = output_frame(h, pict, h->next_output_pic->f);
1218 assert(pict->buf[0] || !*got_frame);
1220 return get_consumed_bytes(buf_index, buf_size);
1223 av_cold void ff_h264_free_context(H264Context *h)
1227 ff_h264_free_tables(h);
1229 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1230 ff_h264_unref_picture(h, &h->DPB[i]);
1231 av_frame_free(&h->DPB[i].f);
1234 h->cur_pic_ptr = NULL;
1236 for (i = 0; i < h->nb_slice_ctx; i++)
1237 av_freep(&h->slice_ctx[i].rbsp_buffer);
1238 av_freep(&h->slice_ctx);
1239 h->nb_slice_ctx = 0;
1241 for (i = 0; i < MAX_SPS_COUNT; i++)
1242 av_buffer_unref(&h->ps.sps_list[i]);
1244 for (i = 0; i < MAX_PPS_COUNT; i++)
1245 av_buffer_unref(&h->ps.pps_list[i]);
1247 ff_h2645_packet_uninit(&h->pkt);
1250 static av_cold int h264_decode_end(AVCodecContext *avctx)
1252 H264Context *h = avctx->priv_data;
1254 ff_h264_free_context(h);
1256 ff_h264_unref_picture(h, &h->cur_pic);
1257 av_frame_free(&h->cur_pic.f);
1262 #define OFFSET(x) offsetof(H264Context, x)
1263 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1264 static const AVOption h264_options[] = {
1265 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1269 static const AVClass h264_class = {
1270 .class_name = "h264",
1271 .item_name = av_default_item_name,
1272 .option = h264_options,
1273 .version = LIBAVUTIL_VERSION_INT,
1276 AVCodec ff_h264_decoder = {
1278 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1279 .type = AVMEDIA_TYPE_VIDEO,
1280 .id = AV_CODEC_ID_H264,
1281 .priv_data_size = sizeof(H264Context),
1282 .init = ff_h264_decode_init,
1283 .close = h264_decode_end,
1284 .decode = h264_decode_frame,
1285 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1286 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1287 AV_CODEC_CAP_FRAME_THREADS,
1288 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1290 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1291 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1292 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1293 .priv_class = &h264_class,