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->nb_slice_ctx;
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->workaround_bugs = avctx->workaround_bugs;
289 h->flags = avctx->flags;
290 h->poc.prev_poc_msb = 1 << 16;
291 h->recovery_frame = -1;
292 h->frame_recovered = 0;
294 h->next_outputed_poc = INT_MIN;
295 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
296 h->last_pocs[i] = INT_MIN;
298 ff_h264_sei_uninit(&h->sei);
300 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
302 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
303 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
306 return AVERROR(ENOMEM);
309 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
310 h->DPB[i].f = av_frame_alloc();
312 return AVERROR(ENOMEM);
315 h->cur_pic.f = av_frame_alloc();
317 return AVERROR(ENOMEM);
319 for (i = 0; i < h->nb_slice_ctx; i++)
320 h->slice_ctx[i].h264 = h;
325 static av_cold int h264_decode_end(AVCodecContext *avctx)
327 H264Context *h = avctx->priv_data;
330 ff_h264_free_tables(h);
332 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
333 ff_h264_unref_picture(h, &h->DPB[i]);
334 av_frame_free(&h->DPB[i].f);
337 h->cur_pic_ptr = NULL;
339 av_freep(&h->slice_ctx);
342 for (i = 0; i < MAX_SPS_COUNT; i++)
343 av_buffer_unref(&h->ps.sps_list[i]);
345 for (i = 0; i < MAX_PPS_COUNT; i++)
346 av_buffer_unref(&h->ps.pps_list[i]);
348 ff_h2645_packet_uninit(&h->pkt);
350 ff_h264_unref_picture(h, &h->cur_pic);
351 av_frame_free(&h->cur_pic.f);
356 static AVOnce h264_vlc_init = AV_ONCE_INIT;
358 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
360 H264Context *h = avctx->priv_data;
363 ret = h264_init_context(avctx, h);
367 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
369 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
370 return AVERROR_UNKNOWN;
373 if (avctx->codec_id == AV_CODEC_ID_H264) {
374 if (avctx->ticks_per_frame == 1)
375 h->avctx->framerate.num *= 2;
376 avctx->ticks_per_frame = 2;
379 if (avctx->extradata_size > 0 && avctx->extradata) {
380 ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
381 &h->ps, &h->is_avc, &h->nal_length_size,
382 avctx->err_recognition, avctx);
384 h264_decode_end(avctx);
389 if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
390 h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
391 h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
394 avctx->internal->allocate_progress = 1;
397 av_log(avctx, AV_LOG_WARNING,
398 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
399 "Use it at your own risk\n");
405 static int decode_init_thread_copy(AVCodecContext *avctx)
407 H264Context *h = avctx->priv_data;
410 if (!avctx->internal->is_copy)
413 memset(h, 0, sizeof(*h));
415 ret = h264_init_context(avctx, h);
419 h->context_initialized = 0;
425 * Run setup operations that must be run after slice header decoding.
426 * This includes finding the next displayed frame.
428 * @param h h264 master context
429 * @param setup_finished enough NALs have been read that we can call
430 * ff_thread_finish_setup()
432 static void decode_postinit(H264Context *h, int setup_finished)
434 const SPS *sps = h->ps.sps;
435 H264Picture *out = h->cur_pic_ptr;
436 H264Picture *cur = h->cur_pic_ptr;
437 int i, pics, out_of_order, out_idx;
438 int invalid = 0, cnt = 0;
440 if (h->next_output_pic)
443 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
444 /* FIXME: if we have two PAFF fields in one packet, we can't start
445 * the next thread here. If we have one field per packet, we can.
446 * The check in decode_nal_units() is not good enough to find this
447 * yet, so we assume the worst for now. */
448 // if (setup_finished)
449 // ff_thread_finish_setup(h->avctx);
453 cur->f->interlaced_frame = 0;
454 cur->f->repeat_pict = 0;
456 /* Signal interlacing information externally. */
457 /* Prioritize picture timing SEI information over used
458 * decoding process if it exists. */
460 if (sps->pic_struct_present_flag) {
461 H264SEIPictureTiming *pt = &h->sei.picture_timing;
462 switch (pt->pic_struct) {
463 case SEI_PIC_STRUCT_FRAME:
465 case SEI_PIC_STRUCT_TOP_FIELD:
466 case SEI_PIC_STRUCT_BOTTOM_FIELD:
467 cur->f->interlaced_frame = 1;
469 case SEI_PIC_STRUCT_TOP_BOTTOM:
470 case SEI_PIC_STRUCT_BOTTOM_TOP:
471 if (FIELD_OR_MBAFF_PICTURE(h))
472 cur->f->interlaced_frame = 1;
474 // try to flag soft telecine progressive
475 cur->f->interlaced_frame = h->prev_interlaced_frame;
477 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
478 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
479 /* Signal the possibility of telecined film externally
480 * (pic_struct 5,6). From these hints, let the applications
481 * decide if they apply deinterlacing. */
482 cur->f->repeat_pict = 1;
484 case SEI_PIC_STRUCT_FRAME_DOUBLING:
485 cur->f->repeat_pict = 2;
487 case SEI_PIC_STRUCT_FRAME_TRIPLING:
488 cur->f->repeat_pict = 4;
492 if ((pt->ct_type & 3) &&
493 pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
494 cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
496 /* Derive interlacing flag from used decoding process. */
497 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
499 h->prev_interlaced_frame = cur->f->interlaced_frame;
501 if (cur->field_poc[0] != cur->field_poc[1]) {
502 /* Derive top_field_first from field pocs. */
503 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
505 if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
506 /* Use picture timing SEI information. Even if it is a
507 * information of a past frame, better than nothing. */
508 if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
509 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
510 cur->f->top_field_first = 1;
512 cur->f->top_field_first = 0;
514 /* Most likely progressive */
515 cur->f->top_field_first = 0;
519 if (h->sei.frame_packing.present &&
520 h->sei.frame_packing.arrangement_type >= 0 &&
521 h->sei.frame_packing.arrangement_type <= 6 &&
522 h->sei.frame_packing.content_interpretation_type > 0 &&
523 h->sei.frame_packing.content_interpretation_type < 3) {
524 H264SEIFramePacking *fp = &h->sei.frame_packing;
525 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
529 switch (fp->arrangement_type) {
531 stereo->type = AV_STEREO3D_CHECKERBOARD;
534 stereo->type = AV_STEREO3D_COLUMNS;
537 stereo->type = AV_STEREO3D_LINES;
540 if (fp->quincunx_subsampling)
541 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
543 stereo->type = AV_STEREO3D_SIDEBYSIDE;
546 stereo->type = AV_STEREO3D_TOPBOTTOM;
549 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
552 stereo->type = AV_STEREO3D_2D;
556 if (fp->content_interpretation_type == 2)
557 stereo->flags = AV_STEREO3D_FLAG_INVERT;
560 if (h->sei.display_orientation.present &&
561 (h->sei.display_orientation.anticlockwise_rotation ||
562 h->sei.display_orientation.hflip ||
563 h->sei.display_orientation.vflip)) {
564 H264SEIDisplayOrientation *o = &h->sei.display_orientation;
565 double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
566 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
567 AV_FRAME_DATA_DISPLAYMATRIX,
568 sizeof(int32_t) * 9);
572 av_display_rotation_set((int32_t *)rotation->data, angle);
573 av_display_matrix_flip((int32_t *)rotation->data,
577 if (h->sei.afd.present) {
578 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
583 *sd->data = h->sei.afd.active_format_description;
584 h->sei.afd.present = 0;
587 if (h->sei.a53_caption.a53_caption) {
588 H264SEIA53Caption *a53 = &h->sei.a53_caption;
589 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
590 AV_FRAME_DATA_A53_CC,
591 a53->a53_caption_size);
595 memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
596 av_freep(&a53->a53_caption);
597 a53->a53_caption_size = 0;
600 // FIXME do something with unavailable reference frames
602 /* Sort B-frames into display order */
603 if (sps->bitstream_restriction_flag ||
604 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
605 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
609 while (h->delayed_pic[pics])
612 assert(pics <= MAX_DELAYED_PIC_COUNT);
614 h->delayed_pic[pics++] = cur;
615 if (cur->reference == 0)
616 cur->reference = DELAYED_PIC_REF;
618 /* Frame reordering. This code takes pictures from coding order and sorts
619 * them by their incremental POC value into display order. It supports POC
620 * gaps, MMCO reset codes and random resets.
621 * A "display group" can start either with a IDR frame (f.key_frame = 1),
622 * and/or can be closed down with a MMCO reset code. In sequences where
623 * there is no delay, we can't detect that (since the frame was already
624 * output to the user), so we also set h->mmco_reset to detect the MMCO
626 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
627 * we increase the delay between input and output. All frames affected by
628 * the lag (e.g. those that should have been output before another frame
629 * that we already returned to the user) will be dropped. This is a bug
630 * that we will fix later. */
631 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
632 cnt += out->poc < h->last_pocs[i];
633 invalid += out->poc == INT_MIN;
635 if (!h->mmco_reset && !cur->f->key_frame &&
636 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
639 h->delayed_pic[pics - 2]->mmco_reset = 2;
641 if (h->mmco_reset || cur->f->key_frame) {
642 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
643 h->last_pocs[i] = INT_MIN;
645 invalid = MAX_DELAYED_PIC_COUNT;
647 out = h->delayed_pic[0];
649 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
651 !h->delayed_pic[i - 1]->mmco_reset &&
652 !h->delayed_pic[i]->f->key_frame;
654 if (h->delayed_pic[i]->poc < out->poc) {
655 out = h->delayed_pic[i];
658 if (h->avctx->has_b_frames == 0 &&
659 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
660 h->next_outputed_poc = INT_MIN;
661 out_of_order = !out->f->key_frame && !h->mmco_reset &&
662 (out->poc < h->next_outputed_poc);
664 if (sps->bitstream_restriction_flag &&
665 h->avctx->has_b_frames >= sps->num_reorder_frames) {
666 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
667 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
668 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
669 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
671 } else if (!h->avctx->has_b_frames &&
672 ((h->next_outputed_poc != INT_MIN &&
673 out->poc > h->next_outputed_poc + 2) ||
674 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
675 h->avctx->has_b_frames++;
678 if (pics > h->avctx->has_b_frames) {
679 out->reference &= ~DELAYED_PIC_REF;
680 for (i = out_idx; h->delayed_pic[i]; i++)
681 h->delayed_pic[i] = h->delayed_pic[i + 1];
683 memmove(h->last_pocs, &h->last_pocs[1],
684 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
685 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
686 if (!out_of_order && pics > h->avctx->has_b_frames) {
687 h->next_output_pic = out;
688 if (out->mmco_reset) {
690 h->next_outputed_poc = out->poc;
691 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
693 h->next_outputed_poc = INT_MIN;
696 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
697 h->next_outputed_poc = INT_MIN;
699 h->next_outputed_poc = out->poc;
704 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
707 if (h->next_output_pic) {
708 if (h->next_output_pic->recovered) {
709 // We have reached an recovery point and all frames after it in
710 // display order are "recovered".
711 h->frame_recovered |= FRAME_RECOVERED_SEI;
713 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
716 if (setup_finished && !h->avctx->hwaccel) {
717 ff_thread_finish_setup(h->avctx);
719 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
720 h->setup_finished = 1;
725 * instantaneous decoder refresh.
727 static void idr(H264Context *h)
729 ff_h264_remove_all_refs(h);
730 h->poc.prev_frame_num =
731 h->poc.prev_frame_num_offset =
732 h->poc.prev_poc_msb =
733 h->poc.prev_poc_lsb = 0;
736 /* forget old pics after a seek */
737 void ff_h264_flush_change(H264Context *h)
740 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
741 h->last_pocs[i] = INT_MIN;
742 h->next_outputed_poc = INT_MIN;
743 h->prev_interlaced_frame = 1;
746 h->cur_pic_ptr->reference = 0;
748 ff_h264_sei_uninit(&h->sei);
749 h->recovery_frame = -1;
750 h->frame_recovered = 0;
753 /* forget old pics after a seek */
754 static void flush_dpb(AVCodecContext *avctx)
756 H264Context *h = avctx->priv_data;
759 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
761 ff_h264_flush_change(h);
763 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
764 ff_h264_unref_picture(h, &h->DPB[i]);
765 h->cur_pic_ptr = NULL;
766 ff_h264_unref_picture(h, &h->cur_pic);
770 ff_h264_free_tables(h);
771 h->context_initialized = 0;
774 static int get_last_needed_nal(H264Context *h)
779 for (i = 0; i < h->pkt.nb_nals; i++) {
780 H2645NAL *nal = &h->pkt.nals[i];
783 /* packets can sometimes contain multiple PPS/SPS,
784 * e.g. two PAFF field pictures in one packet, or a demuxer
785 * which splits NALs strangely if so, when frame threading we
786 * can't start the next thread until we've read all of them */
795 init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
796 if (!get_ue_golomb(&gb))
804 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
806 AVCodecContext *const avctx = h->avctx;
807 unsigned context_count = 0;
808 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
811 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
812 h->current_slice = 0;
814 h->cur_pic_ptr = NULL;
815 ff_h264_sei_uninit(&h->sei);
818 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
819 h->nal_length_size, avctx->codec_id);
821 av_log(avctx, AV_LOG_ERROR,
822 "Error splitting the input into NAL units.\n");
826 if (avctx->active_thread_type & FF_THREAD_FRAME)
827 nals_needed = get_last_needed_nal(h);
829 for (i = 0; i < h->pkt.nb_nals; i++) {
830 H2645NAL *nal = &h->pkt.nals[i];
831 H264SliceContext *sl = &h->slice_ctx[context_count];
834 if (avctx->skip_frame >= AVDISCARD_NONREF &&
835 nal->ref_idc == 0 && nal->type != NAL_SEI)
838 // FIXME these should stop being context-global variables
839 h->nal_ref_idc = nal->ref_idc;
840 h->nal_unit_type = nal->type;
845 if (nal->type != NAL_IDR_SLICE) {
846 av_log(h->avctx, AV_LOG_ERROR,
847 "Invalid mix of idr and non-idr slices\n");
851 idr(h); // FIXME ensure we don't lose some frames if there is reordering
855 if ((err = ff_h264_decode_slice_header(h, sl)))
858 if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
859 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
860 ((1 << h->ps.sps->log2_max_frame_num) - 1);
863 h->cur_pic_ptr->f->key_frame |=
864 (nal->type == NAL_IDR_SLICE) || (h->sei.recovery_point.recovery_frame_cnt >= 0);
866 if (nal->type == NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
867 h->recovery_frame = -1;
868 h->cur_pic_ptr->recovered = 1;
870 // If we have an IDR, all frames after it in decoded order are
872 if (nal->type == NAL_IDR_SLICE)
873 h->frame_recovered |= FRAME_RECOVERED_IDR;
874 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
876 if (h->current_slice == 1) {
877 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
878 decode_postinit(h, i >= nals_needed);
880 if (h->avctx->hwaccel &&
881 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
885 if (sl->redundant_pic_count == 0 &&
886 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
887 (avctx->skip_frame < AVDISCARD_BIDIR ||
888 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
889 (avctx->skip_frame < AVDISCARD_NONKEY ||
890 h->cur_pic_ptr->f->key_frame) &&
891 avctx->skip_frame < AVDISCARD_ALL) {
892 if (avctx->hwaccel) {
893 ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
903 avpriv_request_sample(avctx, "data partitioning");
904 ret = AVERROR(ENOSYS);
908 ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
909 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
913 ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
914 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
918 ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
920 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
924 case NAL_END_SEQUENCE:
926 case NAL_FILLER_DATA:
928 case NAL_AUXILIARY_SLICE:
933 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
934 nal->type, nal->size_bits);
937 if (context_count == h->nb_slice_ctx) {
938 ret = ff_h264_execute_decode_slices(h, context_count);
939 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
945 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
946 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
950 ret = ff_h264_execute_decode_slices(h, context_count);
951 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
958 if (h->cur_pic_ptr && !h->droppable) {
959 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
960 h->picture_structure == PICT_BOTTOM_FIELD);
963 return (ret < 0) ? ret : buf_size;
967 * Return the number of bytes consumed for building the current frame.
969 static int get_consumed_bytes(int pos, int buf_size)
972 pos = 1; // avoid infinite loops (I doubt that is needed but...)
973 if (pos + 10 > buf_size)
974 pos = buf_size; // oops ;)
979 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
982 int ret = av_frame_ref(dst, src);
986 if (!h->ps.sps || !h->ps.sps->crop)
989 for (i = 0; i < 3; i++) {
990 int hshift = (i > 0) ? h->chroma_x_shift : 0;
991 int vshift = (i > 0) ? h->chroma_y_shift : 0;
992 int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
993 (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
999 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1000 int *got_frame, AVPacket *avpkt)
1002 const uint8_t *buf = avpkt->data;
1003 int buf_size = avpkt->size;
1004 H264Context *h = avctx->priv_data;
1005 AVFrame *pict = data;
1009 h->flags = avctx->flags;
1010 h->setup_finished = 0;
1012 /* end of stream, output what is still in the buffers */
1014 if (buf_size == 0) {
1018 h->cur_pic_ptr = NULL;
1020 // FIXME factorize this with the output code below
1021 out = h->delayed_pic[0];
1024 h->delayed_pic[i] &&
1025 !h->delayed_pic[i]->f->key_frame &&
1026 !h->delayed_pic[i]->mmco_reset;
1028 if (h->delayed_pic[i]->poc < out->poc) {
1029 out = h->delayed_pic[i];
1033 for (i = out_idx; h->delayed_pic[i]; i++)
1034 h->delayed_pic[i] = h->delayed_pic[i + 1];
1037 ret = output_frame(h, pict, out->f);
1046 buf_index = decode_nal_units(h, buf, buf_size);
1048 return AVERROR_INVALIDDATA;
1050 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1055 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1056 if (avctx->skip_frame >= AVDISCARD_NONREF)
1058 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1059 return AVERROR_INVALIDDATA;
1062 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1063 (h->mb_y >= h->mb_height && h->mb_height)) {
1064 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1065 decode_postinit(h, 1);
1067 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1070 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1071 h->next_output_pic->recovered)) {
1072 if (!h->next_output_pic->recovered)
1073 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1075 ret = output_frame(h, pict, h->next_output_pic->f);
1082 assert(pict->buf[0] || !*got_frame);
1084 return get_consumed_bytes(buf_index, buf_size);
1087 #define OFFSET(x) offsetof(H264Context, x)
1088 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1089 static const AVOption h264_options[] = {
1090 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1094 static const AVClass h264_class = {
1095 .class_name = "h264",
1096 .item_name = av_default_item_name,
1097 .option = h264_options,
1098 .version = LIBAVUTIL_VERSION_INT,
1101 AVCodec ff_h264_decoder = {
1103 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1104 .type = AVMEDIA_TYPE_VIDEO,
1105 .id = AV_CODEC_ID_H264,
1106 .priv_data_size = sizeof(H264Context),
1107 .init = ff_h264_decode_init,
1108 .close = h264_decode_end,
1109 .decode = h264_decode_frame,
1110 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1111 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1112 AV_CODEC_CAP_FRAME_THREADS,
1113 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1115 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1116 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1117 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1118 .priv_class = &h264_class,