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 h264_init_context(AVCodecContext *avctx, H264Context *h)
287 h->picture_structure = PICT_FRAME;
288 h->slice_context_count = 1;
289 h->workaround_bugs = avctx->workaround_bugs;
290 h->flags = avctx->flags;
291 h->poc.prev_poc_msb = 1 << 16;
292 h->recovery_frame = -1;
293 h->frame_recovered = 0;
295 h->next_outputed_poc = INT_MIN;
296 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
297 h->last_pocs[i] = INT_MIN;
299 ff_h264_sei_uninit(&h->sei);
301 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
303 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
304 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
307 return AVERROR(ENOMEM);
310 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
311 h->DPB[i].f = av_frame_alloc();
313 return AVERROR(ENOMEM);
316 h->cur_pic.f = av_frame_alloc();
318 return AVERROR(ENOMEM);
320 for (i = 0; i < h->nb_slice_ctx; i++)
321 h->slice_ctx[i].h264 = h;
326 static AVOnce h264_vlc_init = AV_ONCE_INIT;
328 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
330 H264Context *h = avctx->priv_data;
333 ret = h264_init_context(avctx, h);
338 if (!avctx->has_b_frames)
341 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
343 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
344 return AVERROR_UNKNOWN;
347 if (avctx->codec_id == AV_CODEC_ID_H264) {
348 if (avctx->ticks_per_frame == 1)
349 h->avctx->framerate.num *= 2;
350 avctx->ticks_per_frame = 2;
353 if (avctx->extradata_size > 0 && avctx->extradata) {
354 ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
355 &h->ps, &h->is_avc, &h->nal_length_size,
356 avctx->err_recognition, avctx);
358 ff_h264_free_context(h);
363 if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
364 h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
365 h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
369 avctx->internal->allocate_progress = 1;
372 av_log(avctx, AV_LOG_WARNING,
373 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
374 "Use it at your own risk\n");
380 static int decode_init_thread_copy(AVCodecContext *avctx)
382 H264Context *h = avctx->priv_data;
385 if (!avctx->internal->is_copy)
388 memset(h, 0, sizeof(*h));
390 ret = h264_init_context(avctx, h);
394 h->context_initialized = 0;
400 * Run setup operations that must be run after slice header decoding.
401 * This includes finding the next displayed frame.
403 * @param h h264 master context
404 * @param setup_finished enough NALs have been read that we can call
405 * ff_thread_finish_setup()
407 static void decode_postinit(H264Context *h, int setup_finished)
409 const SPS *sps = h->ps.sps;
410 H264Picture *out = h->cur_pic_ptr;
411 H264Picture *cur = h->cur_pic_ptr;
412 int i, pics, out_of_order, out_idx;
413 int invalid = 0, cnt = 0;
415 h->cur_pic_ptr->f->pict_type = h->pict_type;
417 if (h->next_output_pic)
420 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
421 /* FIXME: if we have two PAFF fields in one packet, we can't start
422 * the next thread here. If we have one field per packet, we can.
423 * The check in decode_nal_units() is not good enough to find this
424 * yet, so we assume the worst for now. */
425 // if (setup_finished)
426 // ff_thread_finish_setup(h->avctx);
430 cur->f->interlaced_frame = 0;
431 cur->f->repeat_pict = 0;
433 /* Signal interlacing information externally. */
434 /* Prioritize picture timing SEI information over used
435 * decoding process if it exists. */
437 if (sps->pic_struct_present_flag) {
438 H264SEIPictureTiming *pt = &h->sei.picture_timing;
439 switch (pt->pic_struct) {
440 case SEI_PIC_STRUCT_FRAME:
442 case SEI_PIC_STRUCT_TOP_FIELD:
443 case SEI_PIC_STRUCT_BOTTOM_FIELD:
444 cur->f->interlaced_frame = 1;
446 case SEI_PIC_STRUCT_TOP_BOTTOM:
447 case SEI_PIC_STRUCT_BOTTOM_TOP:
448 if (FIELD_OR_MBAFF_PICTURE(h))
449 cur->f->interlaced_frame = 1;
451 // try to flag soft telecine progressive
452 cur->f->interlaced_frame = h->prev_interlaced_frame;
454 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
455 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
456 /* Signal the possibility of telecined film externally
457 * (pic_struct 5,6). From these hints, let the applications
458 * decide if they apply deinterlacing. */
459 cur->f->repeat_pict = 1;
461 case SEI_PIC_STRUCT_FRAME_DOUBLING:
462 cur->f->repeat_pict = 2;
464 case SEI_PIC_STRUCT_FRAME_TRIPLING:
465 cur->f->repeat_pict = 4;
469 if ((pt->ct_type & 3) &&
470 pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
471 cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
473 /* Derive interlacing flag from used decoding process. */
474 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
476 h->prev_interlaced_frame = cur->f->interlaced_frame;
478 if (cur->field_poc[0] != cur->field_poc[1]) {
479 /* Derive top_field_first from field pocs. */
480 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
482 if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
483 /* Use picture timing SEI information. Even if it is a
484 * information of a past frame, better than nothing. */
485 if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
486 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
487 cur->f->top_field_first = 1;
489 cur->f->top_field_first = 0;
491 /* Most likely progressive */
492 cur->f->top_field_first = 0;
496 if (h->sei.frame_packing.present &&
497 h->sei.frame_packing.arrangement_type >= 0 &&
498 h->sei.frame_packing.arrangement_type <= 6 &&
499 h->sei.frame_packing.content_interpretation_type > 0 &&
500 h->sei.frame_packing.content_interpretation_type < 3) {
501 H264SEIFramePacking *fp = &h->sei.frame_packing;
502 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
506 switch (fp->arrangement_type) {
508 stereo->type = AV_STEREO3D_CHECKERBOARD;
511 stereo->type = AV_STEREO3D_COLUMNS;
514 stereo->type = AV_STEREO3D_LINES;
517 if (fp->quincunx_subsampling)
518 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
520 stereo->type = AV_STEREO3D_SIDEBYSIDE;
523 stereo->type = AV_STEREO3D_TOPBOTTOM;
526 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
529 stereo->type = AV_STEREO3D_2D;
533 if (fp->content_interpretation_type == 2)
534 stereo->flags = AV_STEREO3D_FLAG_INVERT;
537 if (h->sei.display_orientation.present &&
538 (h->sei.display_orientation.anticlockwise_rotation ||
539 h->sei.display_orientation.hflip ||
540 h->sei.display_orientation.vflip)) {
541 H264SEIDisplayOrientation *o = &h->sei.display_orientation;
542 double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
543 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
544 AV_FRAME_DATA_DISPLAYMATRIX,
545 sizeof(int32_t) * 9);
549 av_display_rotation_set((int32_t *)rotation->data, angle);
550 av_display_matrix_flip((int32_t *)rotation->data,
554 if (h->sei.afd.present) {
555 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
560 *sd->data = h->sei.afd.active_format_description;
561 h->sei.afd.present = 0;
564 if (h->sei.a53_caption.a53_caption) {
565 H264SEIA53Caption *a53 = &h->sei.a53_caption;
566 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
567 AV_FRAME_DATA_A53_CC,
568 a53->a53_caption_size);
572 memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
573 av_freep(&a53->a53_caption);
574 a53->a53_caption_size = 0;
577 // FIXME do something with unavailable reference frames
579 /* Sort B-frames into display order */
580 if (sps->bitstream_restriction_flag ||
581 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
582 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
584 h->low_delay = !h->avctx->has_b_frames;
587 while (h->delayed_pic[pics])
590 assert(pics <= MAX_DELAYED_PIC_COUNT);
592 h->delayed_pic[pics++] = cur;
593 if (cur->reference == 0)
594 cur->reference = DELAYED_PIC_REF;
596 /* Frame reordering. This code takes pictures from coding order and sorts
597 * them by their incremental POC value into display order. It supports POC
598 * gaps, MMCO reset codes and random resets.
599 * A "display group" can start either with a IDR frame (f.key_frame = 1),
600 * and/or can be closed down with a MMCO reset code. In sequences where
601 * there is no delay, we can't detect that (since the frame was already
602 * output to the user), so we also set h->mmco_reset to detect the MMCO
604 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
605 * we increase the delay between input and output. All frames affected by
606 * the lag (e.g. those that should have been output before another frame
607 * that we already returned to the user) will be dropped. This is a bug
608 * that we will fix later. */
609 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
610 cnt += out->poc < h->last_pocs[i];
611 invalid += out->poc == INT_MIN;
613 if (!h->mmco_reset && !cur->f->key_frame &&
614 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
617 h->delayed_pic[pics - 2]->mmco_reset = 2;
619 if (h->mmco_reset || cur->f->key_frame) {
620 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
621 h->last_pocs[i] = INT_MIN;
623 invalid = MAX_DELAYED_PIC_COUNT;
625 out = h->delayed_pic[0];
627 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
629 !h->delayed_pic[i - 1]->mmco_reset &&
630 !h->delayed_pic[i]->f->key_frame;
632 if (h->delayed_pic[i]->poc < out->poc) {
633 out = h->delayed_pic[i];
636 if (h->avctx->has_b_frames == 0 &&
637 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
638 h->next_outputed_poc = INT_MIN;
639 out_of_order = !out->f->key_frame && !h->mmco_reset &&
640 (out->poc < h->next_outputed_poc);
642 if (sps->bitstream_restriction_flag &&
643 h->avctx->has_b_frames >= sps->num_reorder_frames) {
644 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
645 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
646 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
647 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
650 } else if (h->low_delay &&
651 ((h->next_outputed_poc != INT_MIN &&
652 out->poc > h->next_outputed_poc + 2) ||
653 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
655 h->avctx->has_b_frames++;
658 if (pics > h->avctx->has_b_frames) {
659 out->reference &= ~DELAYED_PIC_REF;
660 // for frame threading, the owner must be the second field's thread or
661 // else the first thread can release the picture and reuse it unsafely
662 for (i = out_idx; h->delayed_pic[i]; i++)
663 h->delayed_pic[i] = h->delayed_pic[i + 1];
665 memmove(h->last_pocs, &h->last_pocs[1],
666 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
667 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
668 if (!out_of_order && pics > h->avctx->has_b_frames) {
669 h->next_output_pic = out;
670 if (out->mmco_reset) {
672 h->next_outputed_poc = out->poc;
673 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
675 h->next_outputed_poc = INT_MIN;
678 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
679 h->next_outputed_poc = INT_MIN;
681 h->next_outputed_poc = out->poc;
686 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
689 if (h->next_output_pic) {
690 if (h->next_output_pic->recovered) {
691 // We have reached an recovery point and all frames after it in
692 // display order are "recovered".
693 h->frame_recovered |= FRAME_RECOVERED_SEI;
695 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
698 if (setup_finished && !h->avctx->hwaccel) {
699 ff_thread_finish_setup(h->avctx);
701 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
702 h->setup_finished = 1;
707 * instantaneous decoder refresh.
709 static void idr(H264Context *h)
711 ff_h264_remove_all_refs(h);
712 h->poc.prev_frame_num =
713 h->poc.prev_frame_num_offset =
714 h->poc.prev_poc_msb =
715 h->poc.prev_poc_lsb = 0;
718 /* forget old pics after a seek */
719 void ff_h264_flush_change(H264Context *h)
722 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
723 h->last_pocs[i] = INT_MIN;
724 h->next_outputed_poc = INT_MIN;
725 h->prev_interlaced_frame = 1;
728 h->cur_pic_ptr->reference = 0;
730 ff_h264_sei_uninit(&h->sei);
731 h->recovery_frame = -1;
732 h->frame_recovered = 0;
735 /* forget old pics after a seek */
736 static void flush_dpb(AVCodecContext *avctx)
738 H264Context *h = avctx->priv_data;
741 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
743 ff_h264_flush_change(h);
745 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
746 ff_h264_unref_picture(h, &h->DPB[i]);
747 h->cur_pic_ptr = NULL;
748 ff_h264_unref_picture(h, &h->cur_pic);
752 ff_h264_free_tables(h);
753 h->context_initialized = 0;
757 * Compute profile from profile_idc and constraint_set?_flags.
761 * @return profile as defined by FF_PROFILE_H264_*
763 int ff_h264_get_profile(const SPS *sps)
765 int profile = sps->profile_idc;
767 switch (sps->profile_idc) {
768 case FF_PROFILE_H264_BASELINE:
769 // constraint_set1_flag set to 1
770 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
772 case FF_PROFILE_H264_HIGH_10:
773 case FF_PROFILE_H264_HIGH_422:
774 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
775 // constraint_set3_flag set to 1
776 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
783 static int get_last_needed_nal(H264Context *h)
788 for (i = 0; i < h->pkt.nb_nals; i++) {
789 H2645NAL *nal = &h->pkt.nals[i];
792 /* packets can sometimes contain multiple PPS/SPS,
793 * e.g. two PAFF field pictures in one packet, or a demuxer
794 * which splits NALs strangely if so, when frame threading we
795 * can't start the next thread until we've read all of them */
804 init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
805 if (!get_ue_golomb(&gb))
813 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
815 AVCodecContext *const avctx = h->avctx;
816 unsigned context_count = 0;
817 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
820 h->max_contexts = h->slice_context_count;
821 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
822 h->current_slice = 0;
824 h->cur_pic_ptr = NULL;
825 ff_h264_sei_uninit(&h->sei);
828 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
829 h->nal_length_size, avctx->codec_id);
831 av_log(avctx, AV_LOG_ERROR,
832 "Error splitting the input into NAL units.\n");
836 if (avctx->active_thread_type & FF_THREAD_FRAME)
837 nals_needed = get_last_needed_nal(h);
839 for (i = 0; i < h->pkt.nb_nals; i++) {
840 H2645NAL *nal = &h->pkt.nals[i];
841 H264SliceContext *sl = &h->slice_ctx[context_count];
844 if (avctx->skip_frame >= AVDISCARD_NONREF &&
845 nal->ref_idc == 0 && nal->type != NAL_SEI)
849 // FIXME these should stop being context-global variables
850 h->nal_ref_idc = nal->ref_idc;
851 h->nal_unit_type = nal->type;
856 if (nal->type != NAL_IDR_SLICE) {
857 av_log(h->avctx, AV_LOG_ERROR,
858 "Invalid mix of idr and non-idr slices\n");
862 idr(h); // FIXME ensure we don't lose some frames if there is reordering
866 if ((err = ff_h264_decode_slice_header(h, sl)))
869 if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
870 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
871 ((1 << h->ps.sps->log2_max_frame_num) - 1);
874 h->cur_pic_ptr->f->key_frame |=
875 (nal->type == NAL_IDR_SLICE) || (h->sei.recovery_point.recovery_frame_cnt >= 0);
877 if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
878 h->recovery_frame = -1;
879 h->cur_pic_ptr->recovered = 1;
881 // If we have an IDR, all frames after it in decoded order are
883 if (nal->type == NAL_IDR_SLICE)
884 h->frame_recovered |= FRAME_RECOVERED_IDR;
885 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
887 if (h->current_slice == 1) {
888 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
889 decode_postinit(h, i >= nals_needed);
891 if (h->avctx->hwaccel &&
892 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
896 if (sl->redundant_pic_count == 0 &&
897 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
898 (avctx->skip_frame < AVDISCARD_BIDIR ||
899 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
900 (avctx->skip_frame < AVDISCARD_NONKEY ||
901 h->cur_pic_ptr->f->key_frame) &&
902 avctx->skip_frame < AVDISCARD_ALL) {
903 if (avctx->hwaccel) {
904 ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
914 avpriv_request_sample(avctx, "data partitioning");
915 ret = AVERROR(ENOSYS);
919 ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
920 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
924 ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
925 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
929 ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
931 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
935 case NAL_END_SEQUENCE:
937 case NAL_FILLER_DATA:
939 case NAL_AUXILIARY_SLICE:
944 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
945 nal->type, nal->size_bits);
948 if (context_count == h->max_contexts) {
949 ret = ff_h264_execute_decode_slices(h, context_count);
950 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
956 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
957 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
958 } else if (err == 1) {
959 /* Slice could not be decoded in parallel mode, restart. Note
960 * that rbsp_buffer is not transferred, but since we no longer
961 * run in parallel mode this should not be an issue. */
962 sl = &h->slice_ctx[0];
967 ret = ff_h264_execute_decode_slices(h, context_count);
968 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
975 if (h->cur_pic_ptr && !h->droppable) {
976 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
977 h->picture_structure == PICT_BOTTOM_FIELD);
980 return (ret < 0) ? ret : buf_size;
984 * Return the number of bytes consumed for building the current frame.
986 static int get_consumed_bytes(int pos, int buf_size)
989 pos = 1; // avoid infinite loops (I doubt that is needed but...)
990 if (pos + 10 > buf_size)
991 pos = buf_size; // oops ;)
996 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
999 int ret = av_frame_ref(dst, src);
1003 if (!h->ps.sps || !h->ps.sps->crop)
1006 for (i = 0; i < 3; i++) {
1007 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1008 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1009 int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
1010 (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
1011 dst->data[i] += off;
1016 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1017 int *got_frame, AVPacket *avpkt)
1019 const uint8_t *buf = avpkt->data;
1020 int buf_size = avpkt->size;
1021 H264Context *h = avctx->priv_data;
1022 AVFrame *pict = data;
1026 h->flags = avctx->flags;
1027 h->setup_finished = 0;
1029 /* end of stream, output what is still in the buffers */
1031 if (buf_size == 0) {
1035 h->cur_pic_ptr = NULL;
1037 // FIXME factorize this with the output code below
1038 out = h->delayed_pic[0];
1041 h->delayed_pic[i] &&
1042 !h->delayed_pic[i]->f->key_frame &&
1043 !h->delayed_pic[i]->mmco_reset;
1045 if (h->delayed_pic[i]->poc < out->poc) {
1046 out = h->delayed_pic[i];
1050 for (i = out_idx; h->delayed_pic[i]; i++)
1051 h->delayed_pic[i] = h->delayed_pic[i + 1];
1054 ret = output_frame(h, pict, out->f);
1063 buf_index = decode_nal_units(h, buf, buf_size);
1065 return AVERROR_INVALIDDATA;
1067 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1072 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1073 if (avctx->skip_frame >= AVDISCARD_NONREF)
1075 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1076 return AVERROR_INVALIDDATA;
1079 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1080 (h->mb_y >= h->mb_height && h->mb_height)) {
1081 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1082 decode_postinit(h, 1);
1084 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1087 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1088 h->next_output_pic->recovered)) {
1089 if (!h->next_output_pic->recovered)
1090 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1092 ret = output_frame(h, pict, h->next_output_pic->f);
1099 assert(pict->buf[0] || !*got_frame);
1101 return get_consumed_bytes(buf_index, buf_size);
1104 av_cold void ff_h264_free_context(H264Context *h)
1108 ff_h264_free_tables(h);
1110 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1111 ff_h264_unref_picture(h, &h->DPB[i]);
1112 av_frame_free(&h->DPB[i].f);
1115 h->cur_pic_ptr = NULL;
1117 for (i = 0; i < h->nb_slice_ctx; i++)
1118 av_freep(&h->slice_ctx[i].rbsp_buffer);
1119 av_freep(&h->slice_ctx);
1120 h->nb_slice_ctx = 0;
1122 for (i = 0; i < MAX_SPS_COUNT; i++)
1123 av_buffer_unref(&h->ps.sps_list[i]);
1125 for (i = 0; i < MAX_PPS_COUNT; i++)
1126 av_buffer_unref(&h->ps.pps_list[i]);
1128 ff_h2645_packet_uninit(&h->pkt);
1131 static av_cold int h264_decode_end(AVCodecContext *avctx)
1133 H264Context *h = avctx->priv_data;
1135 ff_h264_free_context(h);
1137 ff_h264_unref_picture(h, &h->cur_pic);
1138 av_frame_free(&h->cur_pic.f);
1143 #define OFFSET(x) offsetof(H264Context, x)
1144 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1145 static const AVOption h264_options[] = {
1146 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1150 static const AVClass h264_class = {
1151 .class_name = "h264",
1152 .item_name = av_default_item_name,
1153 .option = h264_options,
1154 .version = LIBAVUTIL_VERSION_INT,
1157 AVCodec ff_h264_decoder = {
1159 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1160 .type = AVMEDIA_TYPE_VIDEO,
1161 .id = AV_CODEC_ID_H264,
1162 .priv_data_size = sizeof(H264Context),
1163 .init = ff_h264_decode_init,
1164 .close = h264_decode_end,
1165 .decode = h264_decode_frame,
1166 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1167 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1168 AV_CODEC_CAP_FRAME_THREADS,
1169 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1171 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1172 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1173 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1174 .priv_class = &h264_class,