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 FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/avassert.h"
31 #include "libavutil/display.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/stereo3d.h"
35 #include "libavutil/timer.h"
37 #include "bytestream.h"
39 #include "cabac_functions.h"
40 #include "error_resilience.h"
43 #include "h2645_parse.h"
45 #include "h264chroma.h"
46 #include "h264_mvpred.h"
50 #include "mpegutils.h"
52 #include "rectangle.h"
54 #include "vdpau_compat.h"
56 static int h264_decode_end(AVCodecContext *avctx);
58 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
60 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
62 H264Context *h = avctx->priv_data;
63 return h ? h->sps.num_reorder_frames : 0;
66 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
68 int mb_x, int mb_y, int mb_intra, int mb_skipped)
70 H264Context *h = opaque;
71 H264SliceContext *sl = &h->slice_ctx[0];
75 sl->mb_xy = mb_x + mb_y * h->mb_stride;
76 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
78 /* FIXME: It is possible albeit uncommon that slice references
79 * differ between slices. We take the easy approach and ignore
80 * it for now. If this turns out to have any relevance in
81 * practice then correct remapping should be added. */
82 if (ref >= sl->ref_count[0])
84 if (!sl->ref_list[0][ref].data[0]) {
85 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
88 if ((sl->ref_list[0][ref].reference&3) != 3) {
89 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
92 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
94 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
95 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
96 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
98 sl->mb_field_decoding_flag = 0;
99 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
102 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
105 AVCodecContext *avctx = h->avctx;
106 const AVFrame *src = h->cur_pic.f;
107 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
108 int vshift = desc->log2_chroma_h;
109 const int field_pic = h->picture_structure != PICT_FRAME;
115 height = FFMIN(height, avctx->height - y);
117 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
120 if (avctx->draw_horiz_band) {
121 int offset[AV_NUM_DATA_POINTERS];
124 offset[0] = y * src->linesize[0];
126 offset[2] = (y >> vshift) * src->linesize[1];
127 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
132 avctx->draw_horiz_band(avctx, src, offset,
133 y, h->picture_structure, height);
137 void ff_h264_free_tables(H264Context *h)
141 av_freep(&h->intra4x4_pred_mode);
142 av_freep(&h->chroma_pred_mode_table);
143 av_freep(&h->cbp_table);
144 av_freep(&h->mvd_table[0]);
145 av_freep(&h->mvd_table[1]);
146 av_freep(&h->direct_table);
147 av_freep(&h->non_zero_count);
148 av_freep(&h->slice_table_base);
149 h->slice_table = NULL;
150 av_freep(&h->list_counts);
152 av_freep(&h->mb2b_xy);
153 av_freep(&h->mb2br_xy);
155 av_buffer_pool_uninit(&h->qscale_table_pool);
156 av_buffer_pool_uninit(&h->mb_type_pool);
157 av_buffer_pool_uninit(&h->motion_val_pool);
158 av_buffer_pool_uninit(&h->ref_index_pool);
160 for (i = 0; i < h->nb_slice_ctx; i++) {
161 H264SliceContext *sl = &h->slice_ctx[i];
163 av_freep(&sl->dc_val_base);
164 av_freep(&sl->er.mb_index2xy);
165 av_freep(&sl->er.error_status_table);
166 av_freep(&sl->er.er_temp_buffer);
168 av_freep(&sl->bipred_scratchpad);
169 av_freep(&sl->edge_emu_buffer);
170 av_freep(&sl->top_borders[0]);
171 av_freep(&sl->top_borders[1]);
173 sl->bipred_scratchpad_allocated = 0;
174 sl->edge_emu_buffer_allocated = 0;
175 sl->top_borders_allocated[0] = 0;
176 sl->top_borders_allocated[1] = 0;
180 int ff_h264_alloc_tables(H264Context *h)
182 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
183 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
186 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
187 row_mb_num, 8 * sizeof(uint8_t), fail)
188 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
190 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
191 big_mb_num * 48 * sizeof(uint8_t), fail)
192 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
193 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
194 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
195 big_mb_num * sizeof(uint16_t), fail)
196 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
197 big_mb_num * sizeof(uint8_t), fail)
198 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
199 row_mb_num, 16 * sizeof(uint8_t), fail);
200 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
201 row_mb_num, 16 * sizeof(uint8_t), fail);
202 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
203 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
205 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
206 4 * big_mb_num * sizeof(uint8_t), fail);
207 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
208 big_mb_num * sizeof(uint8_t), fail)
210 memset(h->slice_table_base, -1,
211 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
212 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
214 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
215 big_mb_num * sizeof(uint32_t), fail);
216 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
217 big_mb_num * sizeof(uint32_t), fail);
218 for (y = 0; y < h->mb_height; y++)
219 for (x = 0; x < h->mb_width; x++) {
220 const int mb_xy = x + y * h->mb_stride;
221 const int b_xy = 4 * x + 4 * y * h->b_stride;
223 h->mb2b_xy[mb_xy] = b_xy;
224 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
227 if (!h->dequant4_coeff[0])
228 ff_h264_init_dequant_tables(h);
233 ff_h264_free_tables(h);
234 return AVERROR(ENOMEM);
239 * Allocate buffers which are not shared amongst multiple threads.
241 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
243 ERContext *er = &sl->er;
244 int mb_array_size = h->mb_height * h->mb_stride;
245 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
246 int c_size = h->mb_stride * (h->mb_height + 1);
247 int yc_size = y_size + 2 * c_size;
250 sl->ref_cache[0][scan8[5] + 1] =
251 sl->ref_cache[0][scan8[7] + 1] =
252 sl->ref_cache[0][scan8[13] + 1] =
253 sl->ref_cache[1][scan8[5] + 1] =
254 sl->ref_cache[1][scan8[7] + 1] =
255 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
257 if (sl != h->slice_ctx) {
258 memset(er, 0, sizeof(*er));
260 if (CONFIG_ERROR_RESILIENCE) {
263 er->avctx = h->avctx;
264 er->decode_mb = h264_er_decode_mb;
266 er->quarter_sample = 1;
268 er->mb_num = h->mb_num;
269 er->mb_width = h->mb_width;
270 er->mb_height = h->mb_height;
271 er->mb_stride = h->mb_stride;
272 er->b8_stride = h->mb_width * 2 + 1;
274 // error resilience code looks cleaner with this
275 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
276 (h->mb_num + 1) * sizeof(int), fail);
278 for (y = 0; y < h->mb_height; y++)
279 for (x = 0; x < h->mb_width; x++)
280 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
282 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
283 h->mb_stride + h->mb_width;
285 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
286 mb_array_size * sizeof(uint8_t), fail);
288 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
289 h->mb_height * h->mb_stride, fail);
291 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
292 yc_size * sizeof(int16_t), fail);
293 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
294 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
295 er->dc_val[2] = er->dc_val[1] + c_size;
296 for (i = 0; i < yc_size; i++)
297 sl->dc_val_base[i] = 1024;
303 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
306 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
307 int parse_extradata);
309 /* There are (invalid) samples in the wild with mp4-style extradata, where the
310 * parameter sets are stored unescaped (i.e. as RBSP).
311 * This function catches the parameter set decoding failure and tries again
312 * after escaping it */
313 static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
317 ret = decode_nal_units(h, buf, buf_size, 1);
318 if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
321 uint8_t *escaped_buf;
322 int escaped_buf_size;
324 av_log(h->avctx, AV_LOG_WARNING,
325 "SPS decoding failure, trying again after escaping the NAL\n");
327 if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
328 return AVERROR(ERANGE);
329 escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
330 escaped_buf = av_mallocz(escaped_buf_size);
332 return AVERROR(ENOMEM);
334 bytestream2_init(&gbc, buf, buf_size);
335 bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
337 while (bytestream2_get_bytes_left(&gbc)) {
338 if (bytestream2_get_bytes_left(&gbc) >= 3 &&
339 bytestream2_peek_be24(&gbc) <= 3) {
340 bytestream2_put_be24(&pbc, 3);
341 bytestream2_skip(&gbc, 2);
343 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
346 escaped_buf_size = bytestream2_tell_p(&pbc);
347 AV_WB16(escaped_buf, escaped_buf_size - 2);
349 ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
350 av_freep(&escaped_buf);
358 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
360 AVCodecContext *avctx = h->avctx;
363 if (!buf || size <= 0)
368 const unsigned char *p = buf;
373 av_log(avctx, AV_LOG_ERROR,
374 "avcC %d too short\n", size);
375 return AVERROR_INVALIDDATA;
377 /* sps and pps in the avcC always have length coded with 2 bytes,
378 * so put a fake nal_length_size = 2 while parsing them */
379 h->nal_length_size = 2;
380 // Decode sps from avcC
381 cnt = *(p + 5) & 0x1f; // Number of sps
383 for (i = 0; i < cnt; i++) {
384 nalsize = AV_RB16(p) + 2;
385 if(nalsize > size - (p-buf))
386 return AVERROR_INVALIDDATA;
387 ret = decode_extradata_ps_mp4(h, p, nalsize);
389 av_log(avctx, AV_LOG_ERROR,
390 "Decoding sps %d from avcC failed\n", i);
395 // Decode pps from avcC
396 cnt = *(p++); // Number of pps
397 for (i = 0; i < cnt; i++) {
398 nalsize = AV_RB16(p) + 2;
399 if(nalsize > size - (p-buf))
400 return AVERROR_INVALIDDATA;
401 ret = decode_extradata_ps_mp4(h, p, nalsize);
403 av_log(avctx, AV_LOG_ERROR,
404 "Decoding pps %d from avcC failed\n", i);
409 // Store right nal length size that will be used to parse all other nals
410 h->nal_length_size = (buf[4] & 0x03) + 1;
413 ret = decode_nal_units(h, buf, size, 1);
420 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
425 h->backup_width = -1;
426 h->backup_height = -1;
427 h->backup_pix_fmt = AV_PIX_FMT_NONE;
428 h->dequant_coeff_pps = -1;
429 h->current_sps_id = -1;
430 h->cur_chroma_format_idc = -1;
432 h->picture_structure = PICT_FRAME;
433 h->slice_context_count = 1;
434 h->workaround_bugs = avctx->workaround_bugs;
435 h->flags = avctx->flags;
436 h->prev_poc_msb = 1 << 16;
438 h->recovery_frame = -1;
439 h->frame_recovered = 0;
440 h->prev_frame_num = -1;
441 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
443 h->next_outputed_poc = INT_MIN;
444 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
445 h->last_pocs[i] = INT_MIN;
447 ff_h264_reset_sei(h);
449 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
451 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
452 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
455 return AVERROR(ENOMEM);
458 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
459 h->DPB[i].f = av_frame_alloc();
461 return AVERROR(ENOMEM);
464 h->cur_pic.f = av_frame_alloc();
466 return AVERROR(ENOMEM);
468 h->last_pic_for_ec.f = av_frame_alloc();
469 if (!h->last_pic_for_ec.f)
470 return AVERROR(ENOMEM);
472 for (i = 0; i < h->nb_slice_ctx; i++)
473 h->slice_ctx[i].h264 = h;
478 static AVOnce h264_vlc_init = AV_ONCE_INIT;
480 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
482 H264Context *h = avctx->priv_data;
485 ret = h264_init_context(avctx, h);
490 if (!avctx->has_b_frames)
493 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
495 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
496 return AVERROR_UNKNOWN;
499 if (avctx->codec_id == AV_CODEC_ID_H264) {
500 if (avctx->ticks_per_frame == 1) {
501 if(h->avctx->time_base.den < INT_MAX/2) {
502 h->avctx->time_base.den *= 2;
504 h->avctx->time_base.num /= 2;
506 avctx->ticks_per_frame = 2;
509 if (avctx->extradata_size > 0 && avctx->extradata) {
510 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
512 h264_decode_end(avctx);
517 if (h->sps.bitstream_restriction_flag &&
518 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
519 h->avctx->has_b_frames = h->sps.num_reorder_frames;
523 avctx->internal->allocate_progress = 1;
525 ff_h264_flush_change(h);
527 if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
530 if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
531 av_log(avctx, AV_LOG_WARNING,
532 "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
533 "Use it at your own risk\n");
540 static int decode_init_thread_copy(AVCodecContext *avctx)
542 H264Context *h = avctx->priv_data;
545 if (!avctx->internal->is_copy)
548 memset(h, 0, sizeof(*h));
550 ret = h264_init_context(avctx, h);
554 h->context_initialized = 0;
561 * Run setup operations that must be run after slice header decoding.
562 * This includes finding the next displayed frame.
564 * @param h h264 master context
565 * @param setup_finished enough NALs have been read that we can call
566 * ff_thread_finish_setup()
568 static void decode_postinit(H264Context *h, int setup_finished)
570 H264Picture *out = h->cur_pic_ptr;
571 H264Picture *cur = h->cur_pic_ptr;
572 int i, pics, out_of_order, out_idx;
574 h->cur_pic_ptr->f->pict_type = h->pict_type;
576 if (h->next_output_pic)
579 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
580 /* FIXME: if we have two PAFF fields in one packet, we can't start
581 * the next thread here. If we have one field per packet, we can.
582 * The check in decode_nal_units() is not good enough to find this
583 * yet, so we assume the worst for now. */
584 // if (setup_finished)
585 // ff_thread_finish_setup(h->avctx);
586 if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
588 if (h->avctx->hwaccel || h->missing_fields <=1)
592 cur->f->interlaced_frame = 0;
593 cur->f->repeat_pict = 0;
595 /* Signal interlacing information externally. */
596 /* Prioritize picture timing SEI information over used
597 * decoding process if it exists. */
599 if (h->sps.pic_struct_present_flag) {
600 switch (h->sei_pic_struct) {
601 case SEI_PIC_STRUCT_FRAME:
603 case SEI_PIC_STRUCT_TOP_FIELD:
604 case SEI_PIC_STRUCT_BOTTOM_FIELD:
605 cur->f->interlaced_frame = 1;
607 case SEI_PIC_STRUCT_TOP_BOTTOM:
608 case SEI_PIC_STRUCT_BOTTOM_TOP:
609 if (FIELD_OR_MBAFF_PICTURE(h))
610 cur->f->interlaced_frame = 1;
612 // try to flag soft telecine progressive
613 cur->f->interlaced_frame = h->prev_interlaced_frame;
615 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
616 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
617 /* Signal the possibility of telecined film externally
618 * (pic_struct 5,6). From these hints, let the applications
619 * decide if they apply deinterlacing. */
620 cur->f->repeat_pict = 1;
622 case SEI_PIC_STRUCT_FRAME_DOUBLING:
623 cur->f->repeat_pict = 2;
625 case SEI_PIC_STRUCT_FRAME_TRIPLING:
626 cur->f->repeat_pict = 4;
630 if ((h->sei_ct_type & 3) &&
631 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
632 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
634 /* Derive interlacing flag from used decoding process. */
635 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
637 h->prev_interlaced_frame = cur->f->interlaced_frame;
639 if (cur->field_poc[0] != cur->field_poc[1]) {
640 /* Derive top_field_first from field pocs. */
641 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
643 if (h->sps.pic_struct_present_flag) {
644 /* Use picture timing SEI information. Even if it is a
645 * information of a past frame, better than nothing. */
646 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
647 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
648 cur->f->top_field_first = 1;
650 cur->f->top_field_first = 0;
651 } else if (cur->f->interlaced_frame) {
652 /* Default to top field first when pic_struct_present_flag
653 * is not set but interlaced frame detected */
654 cur->f->top_field_first = 1;
656 /* Most likely progressive */
657 cur->f->top_field_first = 0;
661 if (h->sei_frame_packing_present &&
662 h->frame_packing_arrangement_type >= 0 &&
663 h->frame_packing_arrangement_type <= 6 &&
664 h->content_interpretation_type > 0 &&
665 h->content_interpretation_type < 3) {
666 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
668 switch (h->frame_packing_arrangement_type) {
670 stereo->type = AV_STEREO3D_CHECKERBOARD;
673 stereo->type = AV_STEREO3D_COLUMNS;
676 stereo->type = AV_STEREO3D_LINES;
679 if (h->quincunx_subsampling)
680 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
682 stereo->type = AV_STEREO3D_SIDEBYSIDE;
685 stereo->type = AV_STEREO3D_TOPBOTTOM;
688 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
691 stereo->type = AV_STEREO3D_2D;
695 if (h->content_interpretation_type == 2)
696 stereo->flags = AV_STEREO3D_FLAG_INVERT;
700 if (h->sei_display_orientation_present &&
701 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
702 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
703 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
704 AV_FRAME_DATA_DISPLAYMATRIX,
705 sizeof(int32_t) * 9);
707 av_display_rotation_set((int32_t *)rotation->data, angle);
708 av_display_matrix_flip((int32_t *)rotation->data,
709 h->sei_hflip, h->sei_vflip);
713 if (h->sei_reguserdata_afd_present) {
714 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
718 *sd->data = h->active_format_description;
719 h->sei_reguserdata_afd_present = 0;
723 if (h->a53_caption) {
724 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
725 AV_FRAME_DATA_A53_CC,
726 h->a53_caption_size);
728 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
729 av_freep(&h->a53_caption);
730 h->a53_caption_size = 0;
731 h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
734 cur->mmco_reset = h->mmco_reset;
737 // FIXME do something with unavailable reference frames
739 /* Sort B-frames into display order */
740 if (h->sps.bitstream_restriction_flag ||
741 h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
742 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
744 h->low_delay = !h->avctx->has_b_frames;
746 for (i = 0; 1; i++) {
747 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
749 h->last_pocs[i-1] = cur->poc;
752 h->last_pocs[i-1]= h->last_pocs[i];
755 out_of_order = MAX_DELAYED_PIC_COUNT - i;
756 if( cur->f->pict_type == AV_PICTURE_TYPE_B
757 || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
758 out_of_order = FFMAX(out_of_order, 1);
759 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
760 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
761 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
762 h->last_pocs[i] = INT_MIN;
763 h->last_pocs[0] = cur->poc;
765 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
766 av_log(h->avctx, AV_LOG_INFO, "Increasing reorder buffer to %d\n", out_of_order);
767 h->avctx->has_b_frames = out_of_order;
772 while (h->delayed_pic[pics])
775 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
777 h->delayed_pic[pics++] = cur;
778 if (cur->reference == 0)
779 cur->reference = DELAYED_PIC_REF;
781 out = h->delayed_pic[0];
783 for (i = 1; h->delayed_pic[i] &&
784 !h->delayed_pic[i]->f->key_frame &&
785 !h->delayed_pic[i]->mmco_reset;
787 if (h->delayed_pic[i]->poc < out->poc) {
788 out = h->delayed_pic[i];
791 if (h->avctx->has_b_frames == 0 &&
792 (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
793 h->next_outputed_poc = INT_MIN;
794 out_of_order = out->poc < h->next_outputed_poc;
796 if (out_of_order || pics > h->avctx->has_b_frames) {
797 out->reference &= ~DELAYED_PIC_REF;
798 // for frame threading, the owner must be the second field's thread or
799 // else the first thread can release the picture and reuse it unsafely
800 for (i = out_idx; h->delayed_pic[i]; i++)
801 h->delayed_pic[i] = h->delayed_pic[i + 1];
803 if (!out_of_order && pics > h->avctx->has_b_frames) {
804 h->next_output_pic = out;
805 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
806 h->next_outputed_poc = INT_MIN;
808 h->next_outputed_poc = out->poc;
810 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
813 if (h->next_output_pic) {
814 if (h->next_output_pic->recovered) {
815 // We have reached an recovery point and all frames after it in
816 // display order are "recovered".
817 h->frame_recovered |= FRAME_RECOVERED_SEI;
819 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
822 if (setup_finished && !h->avctx->hwaccel) {
823 ff_thread_finish_setup(h->avctx);
825 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
826 h->setup_finished = 1;
831 * instantaneous decoder refresh.
833 static void idr(H264Context *h)
836 ff_h264_remove_all_refs(h);
838 h->prev_frame_num_offset = 0;
839 h->prev_poc_msb = 1<<16;
841 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
842 h->last_pocs[i] = INT_MIN;
845 /* forget old pics after a seek */
846 void ff_h264_flush_change(H264Context *h)
850 h->next_outputed_poc = INT_MIN;
851 h->prev_interlaced_frame = 1;
854 h->prev_frame_num = -1;
855 if (h->cur_pic_ptr) {
856 h->cur_pic_ptr->reference = 0;
857 for (j=i=0; h->delayed_pic[i]; i++)
858 if (h->delayed_pic[i] != h->cur_pic_ptr)
859 h->delayed_pic[j++] = h->delayed_pic[i];
860 h->delayed_pic[j] = NULL;
862 ff_h264_unref_picture(h, &h->last_pic_for_ec);
865 ff_h264_reset_sei(h);
866 h->recovery_frame = -1;
867 h->frame_recovered = 0;
868 h->current_slice = 0;
870 for (i = 0; i < h->nb_slice_ctx; i++)
871 h->slice_ctx[i].list_count = 0;
874 /* forget old pics after a seek */
875 static void flush_dpb(AVCodecContext *avctx)
877 H264Context *h = avctx->priv_data;
880 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
882 ff_h264_flush_change(h);
884 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
885 ff_h264_unref_picture(h, &h->DPB[i]);
886 h->cur_pic_ptr = NULL;
887 ff_h264_unref_picture(h, &h->cur_pic);
891 ff_h264_free_tables(h);
892 h->context_initialized = 0;
895 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
897 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
900 h->frame_num_offset = h->prev_frame_num_offset;
901 if (h->frame_num < h->prev_frame_num)
902 h->frame_num_offset += max_frame_num;
904 if (h->sps.poc_type == 0) {
905 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
907 if (h->poc_lsb < h->prev_poc_lsb &&
908 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
909 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
910 else if (h->poc_lsb > h->prev_poc_lsb &&
911 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
912 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
914 h->poc_msb = h->prev_poc_msb;
916 field_poc[1] = h->poc_msb + h->poc_lsb;
917 if (h->picture_structure == PICT_FRAME)
918 field_poc[1] += h->delta_poc_bottom;
919 } else if (h->sps.poc_type == 1) {
920 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
923 if (h->sps.poc_cycle_length != 0)
924 abs_frame_num = h->frame_num_offset + h->frame_num;
928 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
931 expected_delta_per_poc_cycle = 0;
932 for (i = 0; i < h->sps.poc_cycle_length; i++)
933 // FIXME integrate during sps parse
934 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
936 if (abs_frame_num > 0) {
937 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
938 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
940 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
941 for (i = 0; i <= frame_num_in_poc_cycle; i++)
942 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
946 if (h->nal_ref_idc == 0)
947 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
949 field_poc[0] = expectedpoc + h->delta_poc[0];
950 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
952 if (h->picture_structure == PICT_FRAME)
953 field_poc[1] += h->delta_poc[1];
955 int poc = 2 * (h->frame_num_offset + h->frame_num);
964 if (h->picture_structure != PICT_BOTTOM_FIELD)
965 pic_field_poc[0] = field_poc[0];
966 if (h->picture_structure != PICT_TOP_FIELD)
967 pic_field_poc[1] = field_poc[1];
968 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
974 * Compute profile from profile_idc and constraint_set?_flags.
978 * @return profile as defined by FF_PROFILE_H264_*
980 int ff_h264_get_profile(SPS *sps)
982 int profile = sps->profile_idc;
984 switch (sps->profile_idc) {
985 case FF_PROFILE_H264_BASELINE:
986 // constraint_set1_flag set to 1
987 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
989 case FF_PROFILE_H264_HIGH_10:
990 case FF_PROFILE_H264_HIGH_422:
991 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
992 // constraint_set3_flag set to 1
993 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1000 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1002 int ref_count[2], list_count;
1003 int num_ref_idx_active_override_flag;
1005 // set defaults, might be overridden a few lines later
1006 ref_count[0] = h->pps.ref_count[0];
1007 ref_count[1] = h->pps.ref_count[1];
1009 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1011 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1013 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1014 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1015 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1017 if (num_ref_idx_active_override_flag) {
1018 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1019 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1020 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1022 // full range is spec-ok in this case, even for frames
1026 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1027 av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]);
1028 sl->ref_count[0] = sl->ref_count[1] = 0;
1030 return AVERROR_INVALIDDATA;
1033 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1039 ref_count[0] = ref_count[1] = 0;
1042 if (list_count != sl->list_count ||
1043 ref_count[0] != sl->ref_count[0] ||
1044 ref_count[1] != sl->ref_count[1]) {
1045 sl->ref_count[0] = ref_count[0];
1046 sl->ref_count[1] = ref_count[1];
1047 sl->list_count = list_count;
1054 #if FF_API_CAP_VDPAU
1055 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1058 static int get_last_needed_nal(H264Context *h)
1060 int nals_needed = 0;
1061 int first_slice = 0;
1064 for (i = 0; i < h->pkt.nb_nals; i++) {
1065 H2645NAL *nal = &h->pkt.nals[i];
1068 /* packets can sometimes contain multiple PPS/SPS,
1069 * e.g. two PAFF field pictures in one packet, or a demuxer
1070 * which splits NALs strangely if so, when frame threading we
1071 * can't start the next thread until we've read all of them */
1072 switch (nal->type) {
1080 init_get_bits8(&gb, nal->data + 1, (nal->size - 1));
1081 if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
1083 first_slice != nal->type)
1086 first_slice = nal->type;
1093 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1094 int parse_extradata)
1096 AVCodecContext *const avctx = h->avctx;
1097 unsigned context_count = 0;
1098 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1102 h->nal_unit_type= 0;
1104 if(!h->slice_context_count)
1105 h->slice_context_count= 1;
1106 h->max_contexts = h->slice_context_count;
1107 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1108 h->current_slice = 0;
1109 if (!h->first_field)
1110 h->cur_pic_ptr = NULL;
1111 ff_h264_reset_sei(h);
1114 if (h->nal_length_size == 4) {
1115 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1117 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1121 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
1122 h->nal_length_size, avctx->codec_id);
1124 av_log(avctx, AV_LOG_ERROR,
1125 "Error splitting the input into NAL units.\n");
1126 /* don't consider NAL parsing failure a fatal error when parsing extradata, as the stream may work without it */
1127 return parse_extradata ? buf_size : ret;
1130 if (avctx->active_thread_type & FF_THREAD_FRAME)
1131 nals_needed = get_last_needed_nal(h);
1133 for (i = 0; i < h->pkt.nb_nals; i++) {
1134 H2645NAL *nal = &h->pkt.nals[i];
1135 H264SliceContext *sl = &h->slice_ctx[context_count];
1138 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1139 nal->ref_idc == 0 && nal->type != NAL_SEI)
1143 /* Ignore per frame NAL unit type during extradata
1144 * parsing. Decoding slices is not possible in codec init
1146 if (parse_extradata) {
1147 switch (nal->type) {
1153 av_log(h->avctx, AV_LOG_WARNING,
1154 "Ignoring NAL %d in global header/extradata\n",
1156 // fall through to next case
1157 case NAL_AUXILIARY_SLICE:
1158 nal->type = NAL_FF_IGNORE;
1162 // FIXME these should stop being context-global variables
1163 h->nal_ref_idc = nal->ref_idc;
1164 h->nal_unit_type = nal->type;
1167 switch (nal->type) {
1169 if ((nal->data[1] & 0xFC) == 0x98) {
1170 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1171 h->next_outputed_poc = INT_MIN;
1175 if (nal->type != NAL_IDR_SLICE) {
1176 av_log(h->avctx, AV_LOG_ERROR,
1177 "Invalid mix of idr and non-idr slices\n");
1182 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1183 av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1184 ret = AVERROR_INVALIDDATA;
1187 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1190 h->has_recovery_point = 1;
1193 if ( nals_needed >= i
1194 || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1197 if ((err = ff_h264_decode_slice_header(h, sl)))
1200 if (h->sei_recovery_frame_cnt >= 0) {
1201 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1202 h->valid_recovery_point = 1;
1204 if ( h->recovery_frame < 0
1205 || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1206 h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
1208 if (!h->valid_recovery_point)
1209 h->recovery_frame = h->frame_num;
1213 h->cur_pic_ptr->f->key_frame |= (nal->type == NAL_IDR_SLICE);
1215 if (nal->type == NAL_IDR_SLICE ||
1216 (h->recovery_frame == h->frame_num && nal->ref_idc)) {
1217 h->recovery_frame = -1;
1218 h->cur_pic_ptr->recovered = 1;
1220 // If we have an IDR, all frames after it in decoded order are
1222 if (nal->type == NAL_IDR_SLICE)
1223 h->frame_recovered |= FRAME_RECOVERED_IDR;
1225 h->cur_pic_ptr->recovered |= h->frame_recovered;
1227 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1230 if (h->current_slice == 1) {
1231 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1232 decode_postinit(h, i >= nals_needed);
1234 if (h->avctx->hwaccel &&
1235 (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1237 #if FF_API_CAP_VDPAU
1238 if (CONFIG_H264_VDPAU_DECODER &&
1239 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
1240 ff_vdpau_h264_picture_start(h);
1244 if (sl->redundant_pic_count == 0) {
1245 if (avctx->hwaccel) {
1246 ret = avctx->hwaccel->decode_slice(avctx,
1251 #if FF_API_CAP_VDPAU
1252 } else if (CONFIG_H264_VDPAU_DECODER &&
1253 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
1254 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1256 sizeof(start_code));
1257 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1268 avpriv_request_sample(avctx, "data partitioning");
1272 ret = ff_h264_decode_sei(h);
1273 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1278 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1280 av_log(h->avctx, AV_LOG_DEBUG,
1281 "SPS decoding failure, trying again with the complete NAL\n");
1282 init_get_bits8(&h->gb, nal->raw_data + 1, nal->raw_size - 1);
1283 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1286 ff_h264_decode_seq_parameter_set(h, 1);
1291 ret = ff_h264_decode_picture_parameter_set(h, nal->size_bits);
1292 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1296 case NAL_END_SEQUENCE:
1297 case NAL_END_STREAM:
1298 case NAL_FILLER_DATA:
1300 case NAL_AUXILIARY_SLICE:
1305 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1306 nal->type, nal->size_bits);
1309 if (context_count == h->max_contexts) {
1310 ret = ff_h264_execute_decode_slices(h, context_count);
1311 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1316 if (err < 0 || err == SLICE_SKIPED) {
1318 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1319 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1320 } else if (err == SLICE_SINGLETHREAD) {
1321 if (context_count > 1) {
1322 ret = ff_h264_execute_decode_slices(h, context_count - 1);
1323 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1327 /* Slice could not be decoded in parallel mode, restart. Note
1328 * that rbsp_buffer is not transferred, but since we no longer
1329 * run in parallel mode this should not be an issue. */
1330 sl = &h->slice_ctx[0];
1334 if (context_count) {
1335 ret = ff_h264_execute_decode_slices(h, context_count);
1336 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1343 #if CONFIG_ERROR_RESILIENCE
1345 * FIXME: Error handling code does not seem to support interlaced
1346 * when slices span multiple rows
1347 * The ff_er_add_slice calls don't work right for bottom
1348 * fields; they cause massive erroneous error concealing
1349 * Error marking covers both fields (top and bottom).
1350 * This causes a mismatched s->error_count
1351 * and a bad error table. Further, the error count goes to
1352 * INT_MAX when called for bottom field, because mb_y is
1353 * past end by one (callers fault) and resync_mb_y != 0
1354 * causes problems for the first MB line, too.
1356 if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new && h->enable_er) {
1357 H264SliceContext *sl = h->slice_ctx;
1358 int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
1360 ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
1363 ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
1364 sl->ref_list[0][0].parent = &h->last_pic_for_ec;
1365 memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
1366 memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
1367 sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
1368 } else if (sl->ref_count[0]) {
1369 ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
1371 ff_h264_set_erpic(&sl->er.last_pic, NULL);
1373 if (sl->ref_count[1])
1374 ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
1376 sl->er.ref_count = sl->ref_count[0];
1378 ff_er_frame_end(&sl->er);
1380 memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
1382 #endif /* CONFIG_ERROR_RESILIENCE */
1384 if (h->cur_pic_ptr && !h->droppable) {
1385 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1386 h->picture_structure == PICT_BOTTOM_FIELD);
1389 return (ret < 0) ? ret : buf_size;
1393 * Return the number of bytes consumed for building the current frame.
1395 static int get_consumed_bytes(int pos, int buf_size)
1398 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1399 if (pos + 10 > buf_size)
1400 pos = buf_size; // oops ;)
1405 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1407 AVFrame *src = srcp->f;
1408 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1410 int ret = av_frame_ref(dst, src);
1414 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1416 h->backup_width = h->avctx->width;
1417 h->backup_height = h->avctx->height;
1418 h->backup_pix_fmt = h->avctx->pix_fmt;
1420 h->avctx->width = dst->width;
1421 h->avctx->height = dst->height;
1422 h->avctx->pix_fmt = dst->format;
1424 if (srcp->sei_recovery_frame_cnt == 0)
1429 for (i = 0; i < desc->nb_components; i++) {
1430 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1431 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1432 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1433 (srcp->crop_top >> vshift) * dst->linesize[i];
1434 dst->data[i] += off;
1439 static int is_extra(const uint8_t *buf, int buf_size)
1441 int cnt= buf[5]&0x1f;
1442 const uint8_t *p= buf+6;
1444 int nalsize= AV_RB16(p) + 2;
1445 if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
1453 int nalsize= AV_RB16(p) + 2;
1454 if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
1461 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1462 int *got_frame, AVPacket *avpkt)
1464 const uint8_t *buf = avpkt->data;
1465 int buf_size = avpkt->size;
1466 H264Context *h = avctx->priv_data;
1467 AVFrame *pict = data;
1473 h->flags = avctx->flags;
1474 h->setup_finished = 0;
1476 if (h->backup_width != -1) {
1477 avctx->width = h->backup_width;
1478 h->backup_width = -1;
1480 if (h->backup_height != -1) {
1481 avctx->height = h->backup_height;
1482 h->backup_height = -1;
1484 if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
1485 avctx->pix_fmt = h->backup_pix_fmt;
1486 h->backup_pix_fmt = AV_PIX_FMT_NONE;
1489 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1491 /* end of stream, output what is still in the buffers */
1492 if (buf_size == 0) {
1495 h->cur_pic_ptr = NULL;
1498 // FIXME factorize this with the output code below
1499 out = h->delayed_pic[0];
1502 h->delayed_pic[i] &&
1503 !h->delayed_pic[i]->f->key_frame &&
1504 !h->delayed_pic[i]->mmco_reset;
1506 if (h->delayed_pic[i]->poc < out->poc) {
1507 out = h->delayed_pic[i];
1511 for (i = out_idx; h->delayed_pic[i]; i++)
1512 h->delayed_pic[i] = h->delayed_pic[i + 1];
1515 out->reference &= ~DELAYED_PIC_REF;
1516 ret = output_frame(h, pict, out);
1524 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1526 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1527 if (is_extra(side, side_size))
1528 ff_h264_decode_extradata(h, side, side_size);
1530 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1531 if (is_extra(buf, buf_size))
1532 return ff_h264_decode_extradata(h, buf, buf_size);
1535 buf_index = decode_nal_units(h, buf, buf_size, 0);
1537 return AVERROR_INVALIDDATA;
1539 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1540 av_assert0(buf_index <= buf_size);
1544 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1545 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1546 buf_size >= 4 && !memcmp("Q264", buf, 4))
1548 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1549 return AVERROR_INVALIDDATA;
1552 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1553 (h->mb_y >= h->mb_height && h->mb_height)) {
1554 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1555 decode_postinit(h, 1);
1557 if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
1560 /* Wait for second field. */
1562 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1563 (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
1564 h->next_output_pic->recovered)) {
1565 if (!h->next_output_pic->recovered)
1566 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1568 if (!h->avctx->hwaccel &&
1569 (h->next_output_pic->field_poc[0] == INT_MAX ||
1570 h->next_output_pic->field_poc[1] == INT_MAX)
1573 AVFrame *f = h->next_output_pic->f;
1574 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1575 uint8_t *dst_data[4];
1577 const uint8_t *src_data[4];
1579 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1581 for (p = 0; p<4; p++) {
1582 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1583 src_data[p] = f->data[p] + field *f->linesize[p];
1584 linesizes[p] = 2*f->linesize[p];
1587 av_image_copy(dst_data, linesizes, src_data, linesizes,
1588 f->format, f->width, f->height>>1);
1591 ret = output_frame(h, pict, h->next_output_pic);
1595 if (CONFIG_MPEGVIDEO) {
1596 ff_print_debug_info2(h->avctx, pict, NULL,
1597 h->next_output_pic->mb_type,
1598 h->next_output_pic->qscale_table,
1599 h->next_output_pic->motion_val,
1601 h->mb_width, h->mb_height, h->mb_stride, 1);
1606 av_assert0(pict->buf[0] || !*got_frame);
1608 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1610 return get_consumed_bytes(buf_index, buf_size);
1613 av_cold void ff_h264_free_context(H264Context *h)
1617 ff_h264_free_tables(h);
1619 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1620 ff_h264_unref_picture(h, &h->DPB[i]);
1621 av_frame_free(&h->DPB[i].f);
1623 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1625 h->cur_pic_ptr = NULL;
1627 for (i = 0; i < h->nb_slice_ctx; i++)
1628 av_freep(&h->slice_ctx[i].rbsp_buffer);
1629 av_freep(&h->slice_ctx);
1630 h->nb_slice_ctx = 0;
1632 h->a53_caption_size = 0;
1633 av_freep(&h->a53_caption);
1635 for (i = 0; i < MAX_SPS_COUNT; i++)
1636 av_freep(h->sps_buffers + i);
1638 for (i = 0; i < MAX_PPS_COUNT; i++)
1639 av_freep(h->pps_buffers + i);
1641 ff_h2645_packet_uninit(&h->pkt);
1644 static av_cold int h264_decode_end(AVCodecContext *avctx)
1646 H264Context *h = avctx->priv_data;
1648 ff_h264_remove_all_refs(h);
1649 ff_h264_free_context(h);
1651 ff_h264_unref_picture(h, &h->cur_pic);
1652 av_frame_free(&h->cur_pic.f);
1653 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1654 av_frame_free(&h->last_pic_for_ec.f);
1659 #define OFFSET(x) offsetof(H264Context, x)
1660 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1661 static const AVOption h264_options[] = {
1662 {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
1663 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1664 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
1668 static const AVClass h264_class = {
1669 .class_name = "H264 Decoder",
1670 .item_name = av_default_item_name,
1671 .option = h264_options,
1672 .version = LIBAVUTIL_VERSION_INT,
1675 AVCodec ff_h264_decoder = {
1677 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1678 .type = AVMEDIA_TYPE_VIDEO,
1679 .id = AV_CODEC_ID_H264,
1680 .priv_data_size = sizeof(H264Context),
1681 .init = ff_h264_decode_init,
1682 .close = h264_decode_end,
1683 .decode = h264_decode_frame,
1684 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1685 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1686 AV_CODEC_CAP_FRAME_THREADS,
1687 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1689 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1690 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1691 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1692 .priv_class = &h264_class,
1695 #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
1696 static const AVClass h264_vdpau_class = {
1697 .class_name = "H264 VDPAU Decoder",
1698 .item_name = av_default_item_name,
1699 .option = h264_options,
1700 .version = LIBAVUTIL_VERSION_INT,
1703 AVCodec ff_h264_vdpau_decoder = {
1704 .name = "h264_vdpau",
1705 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
1706 .type = AVMEDIA_TYPE_VIDEO,
1707 .id = AV_CODEC_ID_H264,
1708 .priv_data_size = sizeof(H264Context),
1709 .init = ff_h264_decode_init,
1710 .close = h264_decode_end,
1711 .decode = h264_decode_frame,
1712 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
1714 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
1716 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1717 .priv_class = &h264_vdpau_class,