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 / MPEG-4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/display.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/stereo3d.h"
32 #include "libavutil/timer.h"
34 #include "bytestream.h"
36 #include "cabac_functions.h"
37 #include "error_resilience.h"
40 #include "h2645_parse.h"
42 #include "h264chroma.h"
43 #include "h264_mvpred.h"
47 #include "mpegutils.h"
49 #include "rectangle.h"
54 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
58 int mb_x, int mb_y, int mb_intra, int mb_skipped)
60 H264Context *h = opaque;
61 H264SliceContext *sl = &h->slice_ctx[0];
65 sl->mb_xy = mb_x + mb_y * h->mb_stride;
66 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
68 /* FIXME: It is possible albeit uncommon that slice references
69 * differ between slices. We take the easy approach and ignore
70 * it for now. If this turns out to have any relevance in
71 * practice then correct remapping should be added. */
72 if (ref >= sl->ref_count[0])
74 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
76 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
77 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
78 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
79 assert(!FRAME_MBAFF(h));
80 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
83 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
86 AVCodecContext *avctx = h->avctx;
87 const AVFrame *src = h->cur_pic.f;
88 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
89 int vshift = desc->log2_chroma_h;
90 const int field_pic = h->picture_structure != PICT_FRAME;
96 height = FFMIN(height, avctx->height - y);
98 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
101 if (avctx->draw_horiz_band) {
102 int offset[AV_NUM_DATA_POINTERS];
105 offset[0] = y * src->linesize[0];
107 offset[2] = (y >> vshift) * src->linesize[1];
108 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
113 avctx->draw_horiz_band(avctx, src, offset,
114 y, h->picture_structure, height);
118 void ff_h264_free_tables(H264Context *h)
122 av_freep(&h->intra4x4_pred_mode);
123 av_freep(&h->chroma_pred_mode_table);
124 av_freep(&h->cbp_table);
125 av_freep(&h->mvd_table[0]);
126 av_freep(&h->mvd_table[1]);
127 av_freep(&h->direct_table);
128 av_freep(&h->non_zero_count);
129 av_freep(&h->slice_table_base);
130 h->slice_table = NULL;
131 av_freep(&h->list_counts);
133 av_freep(&h->mb2b_xy);
134 av_freep(&h->mb2br_xy);
136 av_buffer_pool_uninit(&h->qscale_table_pool);
137 av_buffer_pool_uninit(&h->mb_type_pool);
138 av_buffer_pool_uninit(&h->motion_val_pool);
139 av_buffer_pool_uninit(&h->ref_index_pool);
141 for (i = 0; i < h->nb_slice_ctx; i++) {
142 H264SliceContext *sl = &h->slice_ctx[i];
144 av_freep(&sl->dc_val_base);
145 av_freep(&sl->er.mb_index2xy);
146 av_freep(&sl->er.error_status_table);
147 av_freep(&sl->er.er_temp_buffer);
149 av_freep(&sl->bipred_scratchpad);
150 av_freep(&sl->edge_emu_buffer);
151 av_freep(&sl->top_borders[0]);
152 av_freep(&sl->top_borders[1]);
154 sl->bipred_scratchpad_allocated = 0;
155 sl->edge_emu_buffer_allocated = 0;
156 sl->top_borders_allocated[0] = 0;
157 sl->top_borders_allocated[1] = 0;
161 int ff_h264_alloc_tables(H264Context *h)
163 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
164 const int row_mb_num = h->mb_stride * 2 * h->nb_slice_ctx;
167 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
168 row_mb_num * 8 * sizeof(uint8_t), fail)
169 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
171 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
172 big_mb_num * 48 * sizeof(uint8_t), fail)
173 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
174 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
175 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
176 big_mb_num * sizeof(uint16_t), fail)
177 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
178 big_mb_num * sizeof(uint8_t), fail)
179 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
180 16 * row_mb_num * sizeof(uint8_t), fail);
181 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
182 16 * row_mb_num * sizeof(uint8_t), fail);
183 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
184 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
186 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
187 4 * big_mb_num * sizeof(uint8_t), fail);
188 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
189 big_mb_num * sizeof(uint8_t), fail)
191 memset(h->slice_table_base, -1,
192 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
193 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
195 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
196 big_mb_num * sizeof(uint32_t), fail);
197 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
198 big_mb_num * sizeof(uint32_t), fail);
199 for (y = 0; y < h->mb_height; y++)
200 for (x = 0; x < h->mb_width; x++) {
201 const int mb_xy = x + y * h->mb_stride;
202 const int b_xy = 4 * x + 4 * y * h->b_stride;
204 h->mb2b_xy[mb_xy] = b_xy;
205 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
211 ff_h264_free_tables(h);
212 return AVERROR(ENOMEM);
217 * Allocate buffers which are not shared amongst multiple threads.
219 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
221 ERContext *er = &sl->er;
222 int mb_array_size = h->mb_height * h->mb_stride;
223 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
224 int c_size = h->mb_stride * (h->mb_height + 1);
225 int yc_size = y_size + 2 * c_size;
228 sl->ref_cache[0][scan8[5] + 1] =
229 sl->ref_cache[0][scan8[7] + 1] =
230 sl->ref_cache[0][scan8[13] + 1] =
231 sl->ref_cache[1][scan8[5] + 1] =
232 sl->ref_cache[1][scan8[7] + 1] =
233 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
235 if (CONFIG_ERROR_RESILIENCE) {
237 er->avctx = h->avctx;
238 er->decode_mb = h264_er_decode_mb;
240 er->quarter_sample = 1;
242 er->mb_num = h->mb_num;
243 er->mb_width = h->mb_width;
244 er->mb_height = h->mb_height;
245 er->mb_stride = h->mb_stride;
246 er->b8_stride = h->mb_width * 2 + 1;
248 // error resilience code looks cleaner with this
249 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
250 (h->mb_num + 1) * sizeof(int), fail);
252 for (y = 0; y < h->mb_height; y++)
253 for (x = 0; x < h->mb_width; x++)
254 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
256 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
257 h->mb_stride + h->mb_width;
259 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
260 mb_array_size * sizeof(uint8_t), fail);
262 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
263 h->mb_height * h->mb_stride, fail);
265 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
266 yc_size * sizeof(int16_t), fail);
267 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
268 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
269 er->dc_val[2] = er->dc_val[1] + c_size;
270 for (i = 0; i < yc_size; i++)
271 sl->dc_val_base[i] = 1024;
277 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
280 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
286 h->picture_structure = PICT_FRAME;
287 h->workaround_bugs = avctx->workaround_bugs;
288 h->flags = avctx->flags;
289 h->poc.prev_poc_msb = 1 << 16;
290 h->recovery_frame = -1;
291 h->frame_recovered = 0;
293 h->next_outputed_poc = INT_MIN;
294 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
295 h->last_pocs[i] = INT_MIN;
297 ff_h264_sei_uninit(&h->sei);
299 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
301 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
302 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
305 return AVERROR(ENOMEM);
308 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
309 h->DPB[i].f = av_frame_alloc();
311 return AVERROR(ENOMEM);
314 h->cur_pic.f = av_frame_alloc();
316 return AVERROR(ENOMEM);
318 for (i = 0; i < h->nb_slice_ctx; i++)
319 h->slice_ctx[i].h264 = h;
324 static av_cold int h264_decode_end(AVCodecContext *avctx)
326 H264Context *h = avctx->priv_data;
329 ff_h264_free_tables(h);
331 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
332 ff_h264_unref_picture(h, &h->DPB[i]);
333 av_frame_free(&h->DPB[i].f);
336 h->cur_pic_ptr = NULL;
338 av_freep(&h->slice_ctx);
341 for (i = 0; i < MAX_SPS_COUNT; i++)
342 av_buffer_unref(&h->ps.sps_list[i]);
344 for (i = 0; i < MAX_PPS_COUNT; i++)
345 av_buffer_unref(&h->ps.pps_list[i]);
347 ff_h2645_packet_uninit(&h->pkt);
349 ff_h264_unref_picture(h, &h->cur_pic);
350 av_frame_free(&h->cur_pic.f);
355 static AVOnce h264_vlc_init = AV_ONCE_INIT;
357 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
359 H264Context *h = avctx->priv_data;
362 ret = h264_init_context(avctx, h);
366 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
368 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
369 return AVERROR_UNKNOWN;
372 if (avctx->codec_id == AV_CODEC_ID_H264) {
373 if (avctx->ticks_per_frame == 1)
374 h->avctx->framerate.num *= 2;
375 avctx->ticks_per_frame = 2;
378 if (avctx->extradata_size > 0 && avctx->extradata) {
379 ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
380 &h->ps, &h->is_avc, &h->nal_length_size,
381 avctx->err_recognition, avctx);
383 h264_decode_end(avctx);
388 if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
389 h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
390 h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
393 avctx->internal->allocate_progress = 1;
396 av_log(avctx, AV_LOG_WARNING,
397 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
398 "Use it at your own risk\n");
404 static int decode_init_thread_copy(AVCodecContext *avctx)
406 H264Context *h = avctx->priv_data;
409 if (!avctx->internal->is_copy)
412 memset(h, 0, sizeof(*h));
414 ret = h264_init_context(avctx, h);
418 h->context_initialized = 0;
424 * Run setup operations that must be run after slice header decoding.
425 * This includes finding the next displayed frame.
427 * @param h h264 master context
428 * @param setup_finished enough NALs have been read that we can call
429 * ff_thread_finish_setup()
431 static void decode_postinit(H264Context *h, int setup_finished)
433 const SPS *sps = h->ps.sps;
434 H264Picture *out = h->cur_pic_ptr;
435 H264Picture *cur = h->cur_pic_ptr;
436 int i, pics, out_of_order, out_idx;
437 int invalid = 0, cnt = 0;
439 if (h->next_output_pic)
442 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
443 /* FIXME: if we have two PAFF fields in one packet, we can't start
444 * the next thread here. If we have one field per packet, we can.
445 * The check in decode_nal_units() is not good enough to find this
446 * yet, so we assume the worst for now. */
447 // if (setup_finished)
448 // ff_thread_finish_setup(h->avctx);
452 cur->f->interlaced_frame = 0;
453 cur->f->repeat_pict = 0;
455 /* Signal interlacing information externally. */
456 /* Prioritize picture timing SEI information over used
457 * decoding process if it exists. */
459 if (sps->pic_struct_present_flag) {
460 H264SEIPictureTiming *pt = &h->sei.picture_timing;
461 switch (pt->pic_struct) {
462 case SEI_PIC_STRUCT_FRAME:
464 case SEI_PIC_STRUCT_TOP_FIELD:
465 case SEI_PIC_STRUCT_BOTTOM_FIELD:
466 cur->f->interlaced_frame = 1;
468 case SEI_PIC_STRUCT_TOP_BOTTOM:
469 case SEI_PIC_STRUCT_BOTTOM_TOP:
470 if (FIELD_OR_MBAFF_PICTURE(h))
471 cur->f->interlaced_frame = 1;
473 // try to flag soft telecine progressive
474 cur->f->interlaced_frame = h->prev_interlaced_frame;
476 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
477 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
478 /* Signal the possibility of telecined film externally
479 * (pic_struct 5,6). From these hints, let the applications
480 * decide if they apply deinterlacing. */
481 cur->f->repeat_pict = 1;
483 case SEI_PIC_STRUCT_FRAME_DOUBLING:
484 cur->f->repeat_pict = 2;
486 case SEI_PIC_STRUCT_FRAME_TRIPLING:
487 cur->f->repeat_pict = 4;
491 if ((pt->ct_type & 3) &&
492 pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
493 cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
495 /* Derive interlacing flag from used decoding process. */
496 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
498 h->prev_interlaced_frame = cur->f->interlaced_frame;
500 if (cur->field_poc[0] != cur->field_poc[1]) {
501 /* Derive top_field_first from field pocs. */
502 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
504 if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
505 /* Use picture timing SEI information. Even if it is a
506 * information of a past frame, better than nothing. */
507 if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
508 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
509 cur->f->top_field_first = 1;
511 cur->f->top_field_first = 0;
513 /* Most likely progressive */
514 cur->f->top_field_first = 0;
518 if (h->sei.frame_packing.present &&
519 h->sei.frame_packing.arrangement_type >= 0 &&
520 h->sei.frame_packing.arrangement_type <= 6 &&
521 h->sei.frame_packing.content_interpretation_type > 0 &&
522 h->sei.frame_packing.content_interpretation_type < 3) {
523 H264SEIFramePacking *fp = &h->sei.frame_packing;
524 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
528 switch (fp->arrangement_type) {
530 stereo->type = AV_STEREO3D_CHECKERBOARD;
533 stereo->type = AV_STEREO3D_COLUMNS;
536 stereo->type = AV_STEREO3D_LINES;
539 if (fp->quincunx_subsampling)
540 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
542 stereo->type = AV_STEREO3D_SIDEBYSIDE;
545 stereo->type = AV_STEREO3D_TOPBOTTOM;
548 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
551 stereo->type = AV_STEREO3D_2D;
555 if (fp->content_interpretation_type == 2)
556 stereo->flags = AV_STEREO3D_FLAG_INVERT;
559 if (h->sei.display_orientation.present &&
560 (h->sei.display_orientation.anticlockwise_rotation ||
561 h->sei.display_orientation.hflip ||
562 h->sei.display_orientation.vflip)) {
563 H264SEIDisplayOrientation *o = &h->sei.display_orientation;
564 double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
565 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
566 AV_FRAME_DATA_DISPLAYMATRIX,
567 sizeof(int32_t) * 9);
571 av_display_rotation_set((int32_t *)rotation->data, angle);
572 av_display_matrix_flip((int32_t *)rotation->data,
576 if (h->sei.afd.present) {
577 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
582 *sd->data = h->sei.afd.active_format_description;
583 h->sei.afd.present = 0;
586 if (h->sei.a53_caption.a53_caption) {
587 H264SEIA53Caption *a53 = &h->sei.a53_caption;
588 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
589 AV_FRAME_DATA_A53_CC,
590 a53->a53_caption_size);
594 memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
595 av_freep(&a53->a53_caption);
596 a53->a53_caption_size = 0;
599 // FIXME do something with unavailable reference frames
601 /* Sort B-frames into display order */
602 if (sps->bitstream_restriction_flag ||
603 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
604 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
608 while (h->delayed_pic[pics])
611 assert(pics <= MAX_DELAYED_PIC_COUNT);
613 h->delayed_pic[pics++] = cur;
614 if (cur->reference == 0)
615 cur->reference = DELAYED_PIC_REF;
617 /* Frame reordering. This code takes pictures from coding order and sorts
618 * them by their incremental POC value into display order. It supports POC
619 * gaps, MMCO reset codes and random resets.
620 * A "display group" can start either with a IDR frame (f.key_frame = 1),
621 * and/or can be closed down with a MMCO reset code. In sequences where
622 * there is no delay, we can't detect that (since the frame was already
623 * output to the user), so we also set h->mmco_reset to detect the MMCO
625 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
626 * we increase the delay between input and output. All frames affected by
627 * the lag (e.g. those that should have been output before another frame
628 * that we already returned to the user) will be dropped. This is a bug
629 * that we will fix later. */
630 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
631 cnt += out->poc < h->last_pocs[i];
632 invalid += out->poc == INT_MIN;
634 if (!h->mmco_reset && !cur->f->key_frame &&
635 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
638 h->delayed_pic[pics - 2]->mmco_reset = 2;
640 if (h->mmco_reset || cur->f->key_frame) {
641 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
642 h->last_pocs[i] = INT_MIN;
644 invalid = MAX_DELAYED_PIC_COUNT;
646 out = h->delayed_pic[0];
648 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
650 !h->delayed_pic[i - 1]->mmco_reset &&
651 !h->delayed_pic[i]->f->key_frame;
653 if (h->delayed_pic[i]->poc < out->poc) {
654 out = h->delayed_pic[i];
657 if (h->avctx->has_b_frames == 0 &&
658 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
659 h->next_outputed_poc = INT_MIN;
660 out_of_order = !out->f->key_frame && !h->mmco_reset &&
661 (out->poc < h->next_outputed_poc);
663 if (sps->bitstream_restriction_flag &&
664 h->avctx->has_b_frames >= sps->num_reorder_frames) {
665 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
666 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
667 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
668 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
670 } else if (!h->avctx->has_b_frames &&
671 ((h->next_outputed_poc != INT_MIN &&
672 out->poc > h->next_outputed_poc + 2) ||
673 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
674 h->avctx->has_b_frames++;
677 if (pics > h->avctx->has_b_frames) {
678 out->reference &= ~DELAYED_PIC_REF;
679 for (i = out_idx; h->delayed_pic[i]; i++)
680 h->delayed_pic[i] = h->delayed_pic[i + 1];
682 memmove(h->last_pocs, &h->last_pocs[1],
683 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
684 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
685 if (!out_of_order && pics > h->avctx->has_b_frames) {
686 h->next_output_pic = out;
687 if (out->mmco_reset) {
689 h->next_outputed_poc = out->poc;
690 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
692 h->next_outputed_poc = INT_MIN;
695 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
696 h->next_outputed_poc = INT_MIN;
698 h->next_outputed_poc = out->poc;
703 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
706 if (h->next_output_pic) {
707 if (h->next_output_pic->recovered) {
708 // We have reached an recovery point and all frames after it in
709 // display order are "recovered".
710 h->frame_recovered |= FRAME_RECOVERED_SEI;
712 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
715 if (setup_finished && !h->avctx->hwaccel) {
716 ff_thread_finish_setup(h->avctx);
718 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
719 h->setup_finished = 1;
724 * instantaneous decoder refresh.
726 static void idr(H264Context *h)
728 ff_h264_remove_all_refs(h);
729 h->poc.prev_frame_num =
730 h->poc.prev_frame_num_offset =
731 h->poc.prev_poc_msb =
732 h->poc.prev_poc_lsb = 0;
735 /* forget old pics after a seek */
736 void ff_h264_flush_change(H264Context *h)
739 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
740 h->last_pocs[i] = INT_MIN;
741 h->next_outputed_poc = INT_MIN;
742 h->prev_interlaced_frame = 1;
745 h->cur_pic_ptr->reference = 0;
747 ff_h264_sei_uninit(&h->sei);
748 h->recovery_frame = -1;
749 h->frame_recovered = 0;
752 /* forget old pics after a seek */
753 static void flush_dpb(AVCodecContext *avctx)
755 H264Context *h = avctx->priv_data;
758 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
760 ff_h264_flush_change(h);
762 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
763 ff_h264_unref_picture(h, &h->DPB[i]);
764 h->cur_pic_ptr = NULL;
765 ff_h264_unref_picture(h, &h->cur_pic);
769 ff_h264_free_tables(h);
770 h->context_initialized = 0;
773 static int get_last_needed_nal(H264Context *h)
778 for (i = 0; i < h->pkt.nb_nals; i++) {
779 H2645NAL *nal = &h->pkt.nals[i];
782 /* packets can sometimes contain multiple PPS/SPS,
783 * e.g. two PAFF field pictures in one packet, or a demuxer
784 * which splits NALs strangely if so, when frame threading we
785 * can't start the next thread until we've read all of them */
794 init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
795 if (!get_ue_golomb(&gb))
803 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
805 AVCodecContext *const avctx = h->avctx;
806 unsigned context_count = 0;
807 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
810 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
811 h->current_slice = 0;
813 h->cur_pic_ptr = NULL;
814 ff_h264_sei_uninit(&h->sei);
817 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
818 h->nal_length_size, avctx->codec_id);
820 av_log(avctx, AV_LOG_ERROR,
821 "Error splitting the input into NAL units.\n");
825 if (avctx->active_thread_type & FF_THREAD_FRAME)
826 nals_needed = get_last_needed_nal(h);
828 for (i = 0; i < h->pkt.nb_nals; i++) {
829 H2645NAL *nal = &h->pkt.nals[i];
830 H264SliceContext *sl = &h->slice_ctx[context_count];
833 if (avctx->skip_frame >= AVDISCARD_NONREF &&
834 nal->ref_idc == 0 && nal->type != NAL_SEI)
837 // FIXME these should stop being context-global variables
838 h->nal_ref_idc = nal->ref_idc;
839 h->nal_unit_type = nal->type;
844 if (nal->type != NAL_IDR_SLICE) {
845 av_log(h->avctx, AV_LOG_ERROR,
846 "Invalid mix of idr and non-idr slices\n");
850 idr(h); // FIXME ensure we don't lose some frames if there is reordering
854 if ((err = ff_h264_decode_slice_header(h, sl)))
857 if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
858 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
859 ((1 << h->ps.sps->log2_max_frame_num) - 1);
862 h->cur_pic_ptr->f->key_frame |=
863 (nal->type == NAL_IDR_SLICE) || (h->sei.recovery_point.recovery_frame_cnt >= 0);
865 if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
866 h->recovery_frame = -1;
867 h->cur_pic_ptr->recovered = 1;
869 // If we have an IDR, all frames after it in decoded order are
871 if (nal->type == NAL_IDR_SLICE)
872 h->frame_recovered |= FRAME_RECOVERED_IDR;
873 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
875 if (h->current_slice == 1) {
876 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
877 decode_postinit(h, i >= nals_needed);
879 if (h->avctx->hwaccel &&
880 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
884 if (sl->redundant_pic_count == 0 &&
885 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
886 (avctx->skip_frame < AVDISCARD_BIDIR ||
887 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
888 (avctx->skip_frame < AVDISCARD_NONKEY ||
889 h->cur_pic_ptr->f->key_frame) &&
890 avctx->skip_frame < AVDISCARD_ALL) {
891 if (avctx->hwaccel) {
892 ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
902 avpriv_request_sample(avctx, "data partitioning");
903 ret = AVERROR(ENOSYS);
907 ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
908 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
912 ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
913 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
917 ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
919 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
923 case NAL_END_SEQUENCE:
925 case NAL_FILLER_DATA:
927 case NAL_AUXILIARY_SLICE:
932 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
933 nal->type, nal->size_bits);
936 if (context_count == h->nb_slice_ctx) {
937 ret = ff_h264_execute_decode_slices(h, context_count);
938 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
944 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
945 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
949 ret = ff_h264_execute_decode_slices(h, context_count);
950 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
957 if (h->cur_pic_ptr && !h->droppable) {
958 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
959 h->picture_structure == PICT_BOTTOM_FIELD);
962 return (ret < 0) ? ret : buf_size;
966 * Return the number of bytes consumed for building the current frame.
968 static int get_consumed_bytes(int pos, int buf_size)
971 pos = 1; // avoid infinite loops (I doubt that is needed but...)
972 if (pos + 10 > buf_size)
973 pos = buf_size; // oops ;)
978 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
981 int ret = av_frame_ref(dst, src);
985 if (!h->ps.sps || !h->ps.sps->crop)
988 for (i = 0; i < 3; i++) {
989 int hshift = (i > 0) ? h->chroma_x_shift : 0;
990 int vshift = (i > 0) ? h->chroma_y_shift : 0;
991 int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
992 (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
998 static int h264_decode_frame(AVCodecContext *avctx, void *data,
999 int *got_frame, AVPacket *avpkt)
1001 const uint8_t *buf = avpkt->data;
1002 int buf_size = avpkt->size;
1003 H264Context *h = avctx->priv_data;
1004 AVFrame *pict = data;
1008 h->flags = avctx->flags;
1009 h->setup_finished = 0;
1011 /* end of stream, output what is still in the buffers */
1013 if (buf_size == 0) {
1017 h->cur_pic_ptr = NULL;
1019 // FIXME factorize this with the output code below
1020 out = h->delayed_pic[0];
1023 h->delayed_pic[i] &&
1024 !h->delayed_pic[i]->f->key_frame &&
1025 !h->delayed_pic[i]->mmco_reset;
1027 if (h->delayed_pic[i]->poc < out->poc) {
1028 out = h->delayed_pic[i];
1032 for (i = out_idx; h->delayed_pic[i]; i++)
1033 h->delayed_pic[i] = h->delayed_pic[i + 1];
1036 ret = output_frame(h, pict, out->f);
1045 buf_index = decode_nal_units(h, buf, buf_size);
1047 return AVERROR_INVALIDDATA;
1049 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1054 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1055 if (avctx->skip_frame >= AVDISCARD_NONREF)
1057 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1058 return AVERROR_INVALIDDATA;
1061 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1062 (h->mb_y >= h->mb_height && h->mb_height)) {
1063 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1064 decode_postinit(h, 1);
1066 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1069 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1070 h->next_output_pic->recovered)) {
1071 if (!h->next_output_pic->recovered)
1072 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1074 ret = output_frame(h, pict, h->next_output_pic->f);
1081 assert(pict->buf[0] || !*got_frame);
1083 return get_consumed_bytes(buf_index, buf_size);
1086 #define OFFSET(x) offsetof(H264Context, x)
1087 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1088 static const AVOption h264_options[] = {
1089 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1093 static const AVClass h264_class = {
1094 .class_name = "h264",
1095 .item_name = av_default_item_name,
1096 .option = h264_options,
1097 .version = LIBAVUTIL_VERSION_INT,
1100 AVCodec ff_h264_decoder = {
1102 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1103 .type = AVMEDIA_TYPE_VIDEO,
1104 .id = AV_CODEC_ID_H264,
1105 .priv_data_size = sizeof(H264Context),
1106 .init = ff_h264_decode_init,
1107 .close = h264_decode_end,
1108 .decode = h264_decode_frame,
1109 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1110 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1111 AV_CODEC_CAP_FRAME_THREADS,
1112 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1114 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1115 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1116 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1117 .priv_class = &h264_class,