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"
41 #include "h2645_parse.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
49 #include "mpegutils.h"
51 #include "rectangle.h"
56 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
58 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
60 int mb_x, int mb_y, int mb_intra, int mb_skipped)
62 H264Context *h = opaque;
63 H264SliceContext *sl = &h->slice_ctx[0];
67 sl->mb_xy = mb_x + mb_y * h->mb_stride;
68 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
70 /* FIXME: It is possible albeit uncommon that slice references
71 * differ between slices. We take the easy approach and ignore
72 * it for now. If this turns out to have any relevance in
73 * practice then correct remapping should be added. */
74 if (ref >= sl->ref_count[0])
76 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
78 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
79 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
80 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
81 assert(!FRAME_MBAFF(h));
82 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
85 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
88 AVCodecContext *avctx = h->avctx;
89 const AVFrame *src = h->cur_pic.f;
90 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
91 int vshift = desc->log2_chroma_h;
92 const int field_pic = h->picture_structure != PICT_FRAME;
98 height = FFMIN(height, avctx->height - y);
100 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
103 if (avctx->draw_horiz_band) {
104 int offset[AV_NUM_DATA_POINTERS];
107 offset[0] = y * src->linesize[0];
109 offset[2] = (y >> vshift) * src->linesize[1];
110 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
115 avctx->draw_horiz_band(avctx, src, offset,
116 y, h->picture_structure, height);
120 void ff_h264_free_tables(H264Context *h)
124 av_freep(&h->intra4x4_pred_mode);
125 av_freep(&h->chroma_pred_mode_table);
126 av_freep(&h->cbp_table);
127 av_freep(&h->mvd_table[0]);
128 av_freep(&h->mvd_table[1]);
129 av_freep(&h->direct_table);
130 av_freep(&h->non_zero_count);
131 av_freep(&h->slice_table_base);
132 h->slice_table = NULL;
133 av_freep(&h->list_counts);
135 av_freep(&h->mb2b_xy);
136 av_freep(&h->mb2br_xy);
138 av_buffer_pool_uninit(&h->qscale_table_pool);
139 av_buffer_pool_uninit(&h->mb_type_pool);
140 av_buffer_pool_uninit(&h->motion_val_pool);
141 av_buffer_pool_uninit(&h->ref_index_pool);
143 for (i = 0; i < h->nb_slice_ctx; i++) {
144 H264SliceContext *sl = &h->slice_ctx[i];
146 av_freep(&sl->dc_val_base);
147 av_freep(&sl->er.mb_index2xy);
148 av_freep(&sl->er.error_status_table);
149 av_freep(&sl->er.er_temp_buffer);
151 av_freep(&sl->bipred_scratchpad);
152 av_freep(&sl->edge_emu_buffer);
153 av_freep(&sl->top_borders[0]);
154 av_freep(&sl->top_borders[1]);
156 sl->bipred_scratchpad_allocated = 0;
157 sl->edge_emu_buffer_allocated = 0;
158 sl->top_borders_allocated[0] = 0;
159 sl->top_borders_allocated[1] = 0;
163 int ff_h264_alloc_tables(H264Context *h)
165 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
166 const int row_mb_num = h->mb_stride * 2 * h->nb_slice_ctx;
169 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
170 row_mb_num * 8 * sizeof(uint8_t), fail)
171 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
173 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
174 big_mb_num * 48 * sizeof(uint8_t), fail)
175 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
176 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
177 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
178 big_mb_num * sizeof(uint16_t), fail)
179 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
180 big_mb_num * sizeof(uint8_t), fail)
181 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
182 16 * row_mb_num * sizeof(uint8_t), fail);
183 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
184 16 * row_mb_num * sizeof(uint8_t), fail);
185 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
186 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
188 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
189 4 * big_mb_num * sizeof(uint8_t), fail);
190 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
191 big_mb_num * sizeof(uint8_t), fail)
193 memset(h->slice_table_base, -1,
194 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
195 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
197 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
198 big_mb_num * sizeof(uint32_t), fail);
199 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
200 big_mb_num * sizeof(uint32_t), fail);
201 for (y = 0; y < h->mb_height; y++)
202 for (x = 0; x < h->mb_width; x++) {
203 const int mb_xy = x + y * h->mb_stride;
204 const int b_xy = 4 * x + 4 * y * h->b_stride;
206 h->mb2b_xy[mb_xy] = b_xy;
207 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
213 ff_h264_free_tables(h);
214 return AVERROR(ENOMEM);
219 * Allocate buffers which are not shared amongst multiple threads.
221 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
223 ERContext *er = &sl->er;
224 int mb_array_size = h->mb_height * h->mb_stride;
225 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
226 int c_size = h->mb_stride * (h->mb_height + 1);
227 int yc_size = y_size + 2 * c_size;
230 sl->ref_cache[0][scan8[5] + 1] =
231 sl->ref_cache[0][scan8[7] + 1] =
232 sl->ref_cache[0][scan8[13] + 1] =
233 sl->ref_cache[1][scan8[5] + 1] =
234 sl->ref_cache[1][scan8[7] + 1] =
235 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
237 if (CONFIG_ERROR_RESILIENCE) {
239 er->avctx = h->avctx;
240 er->decode_mb = h264_er_decode_mb;
242 er->quarter_sample = 1;
244 er->mb_num = h->mb_num;
245 er->mb_width = h->mb_width;
246 er->mb_height = h->mb_height;
247 er->mb_stride = h->mb_stride;
248 er->b8_stride = h->mb_width * 2 + 1;
250 // error resilience code looks cleaner with this
251 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
252 (h->mb_num + 1) * sizeof(int), fail);
254 for (y = 0; y < h->mb_height; y++)
255 for (x = 0; x < h->mb_width; x++)
256 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
258 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
259 h->mb_stride + h->mb_width;
261 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
262 mb_array_size * sizeof(uint8_t), fail);
264 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
265 h->mb_height * h->mb_stride, fail);
267 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
268 yc_size * sizeof(int16_t), fail);
269 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
270 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
271 er->dc_val[2] = er->dc_val[1] + c_size;
272 for (i = 0; i < yc_size; i++)
273 sl->dc_val_base[i] = 1024;
279 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
282 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
288 h->picture_structure = PICT_FRAME;
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) ? avctx->thread_count : 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 av_cold int h264_decode_end(AVCodecContext *avctx)
328 H264Context *h = avctx->priv_data;
331 ff_h264_free_tables(h);
333 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
334 ff_h264_unref_picture(h, &h->DPB[i]);
335 av_frame_free(&h->DPB[i].f);
338 h->cur_pic_ptr = NULL;
340 av_freep(&h->slice_ctx);
343 for (i = 0; i < MAX_SPS_COUNT; i++)
344 av_buffer_unref(&h->ps.sps_list[i]);
346 for (i = 0; i < MAX_PPS_COUNT; i++)
347 av_buffer_unref(&h->ps.pps_list[i]);
349 ff_h2645_packet_uninit(&h->pkt);
351 ff_h264_unref_picture(h, &h->cur_pic);
352 av_frame_free(&h->cur_pic.f);
357 static AVOnce h264_vlc_init = AV_ONCE_INIT;
359 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
361 H264Context *h = avctx->priv_data;
364 ret = h264_init_context(avctx, h);
368 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
370 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
371 return AVERROR_UNKNOWN;
374 if (avctx->codec_id == AV_CODEC_ID_H264) {
375 if (avctx->ticks_per_frame == 1)
376 h->avctx->framerate.num *= 2;
377 avctx->ticks_per_frame = 2;
380 if (avctx->extradata_size > 0 && avctx->extradata) {
381 ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
382 &h->ps, &h->is_avc, &h->nal_length_size,
383 avctx->err_recognition, avctx);
385 h264_decode_end(avctx);
390 if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
391 h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
392 h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
395 avctx->internal->allocate_progress = 1;
398 av_log(avctx, AV_LOG_WARNING,
399 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
400 "Use it at your own risk\n");
406 static int decode_init_thread_copy(AVCodecContext *avctx)
408 H264Context *h = avctx->priv_data;
411 if (!avctx->internal->is_copy)
414 memset(h, 0, sizeof(*h));
416 ret = h264_init_context(avctx, h);
420 h->context_initialized = 0;
426 * Run setup operations that must be run after slice header decoding.
427 * This includes finding the next displayed frame.
429 * @param h h264 master context
430 * @param setup_finished enough NALs have been read that we can call
431 * ff_thread_finish_setup()
433 static void decode_postinit(H264Context *h, int setup_finished)
435 const SPS *sps = h->ps.sps;
436 H264Picture *out = h->cur_pic_ptr;
437 H264Picture *cur = h->cur_pic_ptr;
438 int i, pics, out_of_order, out_idx;
439 int invalid = 0, cnt = 0;
441 if (h->next_output_pic)
444 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
445 /* FIXME: if we have two PAFF fields in one packet, we can't start
446 * the next thread here. If we have one field per packet, we can.
447 * The check in decode_nal_units() is not good enough to find this
448 * yet, so we assume the worst for now. */
449 // if (setup_finished)
450 // ff_thread_finish_setup(h->avctx);
454 // FIXME do something with unavailable reference frames
456 /* Sort B-frames into display order */
457 if (sps->bitstream_restriction_flag ||
458 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
459 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
463 while (h->delayed_pic[pics])
466 assert(pics <= MAX_DELAYED_PIC_COUNT);
468 h->delayed_pic[pics++] = cur;
469 if (cur->reference == 0)
470 cur->reference = DELAYED_PIC_REF;
472 /* Frame reordering. This code takes pictures from coding order and sorts
473 * them by their incremental POC value into display order. It supports POC
474 * gaps, MMCO reset codes and random resets.
475 * A "display group" can start either with a IDR frame (f.key_frame = 1),
476 * and/or can be closed down with a MMCO reset code. In sequences where
477 * there is no delay, we can't detect that (since the frame was already
478 * output to the user), so we also set h->mmco_reset to detect the MMCO
480 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
481 * we increase the delay between input and output. All frames affected by
482 * the lag (e.g. those that should have been output before another frame
483 * that we already returned to the user) will be dropped. This is a bug
484 * that we will fix later. */
485 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
486 cnt += out->poc < h->last_pocs[i];
487 invalid += out->poc == INT_MIN;
489 if (!h->mmco_reset && !cur->f->key_frame &&
490 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
493 h->delayed_pic[pics - 2]->mmco_reset = 2;
495 if (h->mmco_reset || cur->f->key_frame) {
496 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
497 h->last_pocs[i] = INT_MIN;
499 invalid = MAX_DELAYED_PIC_COUNT;
501 out = h->delayed_pic[0];
503 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
505 !h->delayed_pic[i - 1]->mmco_reset &&
506 !h->delayed_pic[i]->f->key_frame;
508 if (h->delayed_pic[i]->poc < out->poc) {
509 out = h->delayed_pic[i];
512 if (h->avctx->has_b_frames == 0 &&
513 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
514 h->next_outputed_poc = INT_MIN;
515 out_of_order = !out->f->key_frame && !h->mmco_reset &&
516 (out->poc < h->next_outputed_poc);
518 if (sps->bitstream_restriction_flag &&
519 h->avctx->has_b_frames >= sps->num_reorder_frames) {
520 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
521 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
522 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
523 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
525 } else if (!h->avctx->has_b_frames &&
526 ((h->next_outputed_poc != INT_MIN &&
527 out->poc > h->next_outputed_poc + 2) ||
528 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
529 h->avctx->has_b_frames++;
532 if (pics > h->avctx->has_b_frames) {
533 out->reference &= ~DELAYED_PIC_REF;
534 for (i = out_idx; h->delayed_pic[i]; i++)
535 h->delayed_pic[i] = h->delayed_pic[i + 1];
537 memmove(h->last_pocs, &h->last_pocs[1],
538 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
539 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
540 if (!out_of_order && pics > h->avctx->has_b_frames) {
541 h->next_output_pic = out;
542 if (out->mmco_reset) {
544 h->next_outputed_poc = out->poc;
545 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
547 h->next_outputed_poc = INT_MIN;
550 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
551 h->next_outputed_poc = INT_MIN;
553 h->next_outputed_poc = out->poc;
558 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
561 if (h->next_output_pic) {
562 if (h->next_output_pic->recovered) {
563 // We have reached an recovery point and all frames after it in
564 // display order are "recovered".
565 h->frame_recovered |= FRAME_RECOVERED_SEI;
567 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
570 if (setup_finished && !h->avctx->hwaccel) {
571 ff_thread_finish_setup(h->avctx);
573 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
574 h->setup_finished = 1;
579 * instantaneous decoder refresh.
581 static void idr(H264Context *h)
583 ff_h264_remove_all_refs(h);
584 h->poc.prev_frame_num =
585 h->poc.prev_frame_num_offset =
586 h->poc.prev_poc_msb =
587 h->poc.prev_poc_lsb = 0;
590 /* forget old pics after a seek */
591 void ff_h264_flush_change(H264Context *h)
594 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
595 h->last_pocs[i] = INT_MIN;
596 h->next_outputed_poc = INT_MIN;
597 h->prev_interlaced_frame = 1;
600 h->cur_pic_ptr->reference = 0;
602 ff_h264_sei_uninit(&h->sei);
603 h->recovery_frame = -1;
604 h->frame_recovered = 0;
607 /* forget old pics after a seek */
608 static void flush_dpb(AVCodecContext *avctx)
610 H264Context *h = avctx->priv_data;
613 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
615 ff_h264_flush_change(h);
617 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
618 ff_h264_unref_picture(h, &h->DPB[i]);
619 h->cur_pic_ptr = NULL;
620 ff_h264_unref_picture(h, &h->cur_pic);
624 ff_h264_free_tables(h);
625 h->context_initialized = 0;
628 static int get_last_needed_nal(H264Context *h)
633 for (i = 0; i < h->pkt.nb_nals; i++) {
634 H2645NAL *nal = &h->pkt.nals[i];
637 /* packets can sometimes contain multiple PPS/SPS,
638 * e.g. two PAFF field pictures in one packet, or a demuxer
639 * which splits NALs strangely if so, when frame threading we
640 * can't start the next thread until we've read all of them */
647 case H264_NAL_IDR_SLICE:
649 init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
650 if (!get_ue_golomb(&gb))
658 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
660 AVCodecContext *const avctx = h->avctx;
661 unsigned context_count = 0;
662 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
665 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
666 h->current_slice = 0;
668 h->cur_pic_ptr = NULL;
669 ff_h264_sei_uninit(&h->sei);
672 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
673 h->nal_length_size, avctx->codec_id);
675 av_log(avctx, AV_LOG_ERROR,
676 "Error splitting the input into NAL units.\n");
680 if (avctx->active_thread_type & FF_THREAD_FRAME)
681 nals_needed = get_last_needed_nal(h);
683 for (i = 0; i < h->pkt.nb_nals; i++) {
684 H2645NAL *nal = &h->pkt.nals[i];
685 H264SliceContext *sl = &h->slice_ctx[context_count];
688 if (avctx->skip_frame >= AVDISCARD_NONREF &&
689 nal->ref_idc == 0 && nal->type != H264_NAL_SEI)
692 // FIXME these should stop being context-global variables
693 h->nal_ref_idc = nal->ref_idc;
694 h->nal_unit_type = nal->type;
698 case H264_NAL_IDR_SLICE:
699 if (nal->type != H264_NAL_IDR_SLICE) {
700 av_log(h->avctx, AV_LOG_ERROR,
701 "Invalid mix of idr and non-idr slices\n");
705 idr(h); // FIXME ensure we don't lose some frames if there is reordering
709 if ((err = ff_h264_decode_slice_header(h, sl, nal)))
712 if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
713 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
714 ((1 << h->ps.sps->log2_max_frame_num) - 1);
717 h->cur_pic_ptr->f->key_frame |=
718 (nal->type == H264_NAL_IDR_SLICE) || (h->sei.recovery_point.recovery_frame_cnt >= 0);
720 if (nal->type == H264_NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
721 h->recovery_frame = -1;
722 h->cur_pic_ptr->recovered = 1;
724 // If we have an IDR, all frames after it in decoded order are
726 if (nal->type == H264_NAL_IDR_SLICE)
727 h->frame_recovered |= FRAME_RECOVERED_IDR;
728 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
730 if (h->current_slice == 1) {
731 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
732 decode_postinit(h, i >= nals_needed);
734 if (h->avctx->hwaccel &&
735 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
739 if (sl->redundant_pic_count == 0 &&
740 (avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
741 (avctx->skip_frame < AVDISCARD_BIDIR ||
742 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
743 (avctx->skip_frame < AVDISCARD_NONKEY ||
744 h->cur_pic_ptr->f->key_frame) &&
745 avctx->skip_frame < AVDISCARD_ALL) {
746 if (avctx->hwaccel) {
747 ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
757 avpriv_request_sample(avctx, "data partitioning");
758 ret = AVERROR(ENOSYS);
762 ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
763 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
767 ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
768 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
772 ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
774 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
778 case H264_NAL_END_SEQUENCE:
779 case H264_NAL_END_STREAM:
780 case H264_NAL_FILLER_DATA:
781 case H264_NAL_SPS_EXT:
782 case H264_NAL_AUXILIARY_SLICE:
785 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
786 nal->type, nal->size_bits);
789 if (context_count == h->nb_slice_ctx) {
790 ret = ff_h264_execute_decode_slices(h, context_count);
791 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
797 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
798 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
802 ret = ff_h264_execute_decode_slices(h, context_count);
803 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
810 if (h->cur_pic_ptr && !h->droppable) {
811 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
812 h->picture_structure == PICT_BOTTOM_FIELD);
815 return (ret < 0) ? ret : buf_size;
819 * Return the number of bytes consumed for building the current frame.
821 static int get_consumed_bytes(int pos, int buf_size)
824 pos = 1; // avoid infinite loops (I doubt that is needed but...)
825 if (pos + 10 > buf_size)
826 pos = buf_size; // oops ;)
831 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
834 int ret = av_frame_ref(dst, src);
838 if (!h->ps.sps || !h->ps.sps->crop)
841 for (i = 0; i < 3; i++) {
842 int hshift = (i > 0) ? h->chroma_x_shift : 0;
843 int vshift = (i > 0) ? h->chroma_y_shift : 0;
844 int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
845 (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
851 static int h264_decode_frame(AVCodecContext *avctx, void *data,
852 int *got_frame, AVPacket *avpkt)
854 const uint8_t *buf = avpkt->data;
855 int buf_size = avpkt->size;
856 H264Context *h = avctx->priv_data;
857 AVFrame *pict = data;
860 const uint8_t *new_extradata;
861 int new_extradata_size;
863 h->flags = avctx->flags;
864 h->setup_finished = 0;
866 /* end of stream, output what is still in the buffers */
872 h->cur_pic_ptr = NULL;
874 // FIXME factorize this with the output code below
875 out = h->delayed_pic[0];
879 !h->delayed_pic[i]->f->key_frame &&
880 !h->delayed_pic[i]->mmco_reset;
882 if (h->delayed_pic[i]->poc < out->poc) {
883 out = h->delayed_pic[i];
887 for (i = out_idx; h->delayed_pic[i]; i++)
888 h->delayed_pic[i] = h->delayed_pic[i + 1];
891 ret = output_frame(h, pict, out->f);
900 new_extradata_size = 0;
901 new_extradata = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
902 &new_extradata_size);
903 if (new_extradata_size > 0 && new_extradata) {
904 ret = ff_h264_decode_extradata(new_extradata, new_extradata_size,
905 &h->ps, &h->is_avc, &h->nal_length_size,
906 avctx->err_recognition, avctx);
911 buf_index = decode_nal_units(h, buf, buf_size);
913 return AVERROR_INVALIDDATA;
915 if (!h->cur_pic_ptr && h->nal_unit_type == H264_NAL_END_SEQUENCE) {
920 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
921 if (avctx->skip_frame >= AVDISCARD_NONREF)
923 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
924 return AVERROR_INVALIDDATA;
927 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
928 (h->mb_y >= h->mb_height && h->mb_height)) {
929 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
930 decode_postinit(h, 1);
932 ff_h264_field_end(h, &h->slice_ctx[0], 0);
935 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
936 h->next_output_pic->recovered)) {
937 if (!h->next_output_pic->recovered)
938 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
940 ret = output_frame(h, pict, h->next_output_pic->f);
947 assert(pict->buf[0] || !*got_frame);
949 return get_consumed_bytes(buf_index, buf_size);
952 #define OFFSET(x) offsetof(H264Context, x)
953 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
954 static const AVOption h264_options[] = {
955 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
959 static const AVClass h264_class = {
960 .class_name = "h264",
961 .item_name = av_default_item_name,
962 .option = h264_options,
963 .version = LIBAVUTIL_VERSION_INT,
966 AVCodec ff_h264_decoder = {
968 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
969 .type = AVMEDIA_TYPE_VIDEO,
970 .id = AV_CODEC_ID_H264,
971 .priv_data_size = sizeof(H264Context),
972 .init = ff_h264_decode_init,
973 .close = h264_decode_end,
974 .decode = h264_decode_frame,
975 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
976 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
977 AV_CODEC_CAP_FRAME_THREADS,
978 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
980 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
981 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
982 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
983 .priv_class = &h264_class,