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->ps.sps ? h->ps.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)));
230 ff_h264_free_tables(h);
231 return AVERROR(ENOMEM);
236 * Allocate buffers which are not shared amongst multiple threads.
238 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
240 ERContext *er = &sl->er;
241 int mb_array_size = h->mb_height * h->mb_stride;
242 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
243 int c_size = h->mb_stride * (h->mb_height + 1);
244 int yc_size = y_size + 2 * c_size;
247 sl->ref_cache[0][scan8[5] + 1] =
248 sl->ref_cache[0][scan8[7] + 1] =
249 sl->ref_cache[0][scan8[13] + 1] =
250 sl->ref_cache[1][scan8[5] + 1] =
251 sl->ref_cache[1][scan8[7] + 1] =
252 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
254 if (sl != h->slice_ctx) {
255 memset(er, 0, sizeof(*er));
257 if (CONFIG_ERROR_RESILIENCE) {
260 er->avctx = h->avctx;
261 er->decode_mb = h264_er_decode_mb;
263 er->quarter_sample = 1;
265 er->mb_num = h->mb_num;
266 er->mb_width = h->mb_width;
267 er->mb_height = h->mb_height;
268 er->mb_stride = h->mb_stride;
269 er->b8_stride = h->mb_width * 2 + 1;
271 // error resilience code looks cleaner with this
272 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
273 (h->mb_num + 1) * sizeof(int), fail);
275 for (y = 0; y < h->mb_height; y++)
276 for (x = 0; x < h->mb_width; x++)
277 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
279 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
280 h->mb_stride + h->mb_width;
282 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
283 mb_array_size * sizeof(uint8_t), fail);
285 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
286 h->mb_height * h->mb_stride, fail);
288 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
289 yc_size * sizeof(int16_t), fail);
290 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
291 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
292 er->dc_val[2] = er->dc_val[1] + c_size;
293 for (i = 0; i < yc_size; i++)
294 sl->dc_val_base[i] = 1024;
300 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
303 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
304 int parse_extradata);
306 /* There are (invalid) samples in the wild with mp4-style extradata, where the
307 * parameter sets are stored unescaped (i.e. as RBSP).
308 * This function catches the parameter set decoding failure and tries again
309 * after escaping it */
310 static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
314 ret = decode_nal_units(h, buf, buf_size, 1);
315 if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
318 uint8_t *escaped_buf;
319 int escaped_buf_size;
321 av_log(h->avctx, AV_LOG_WARNING,
322 "SPS decoding failure, trying again after escaping the NAL\n");
324 if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
325 return AVERROR(ERANGE);
326 escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
327 escaped_buf = av_mallocz(escaped_buf_size);
329 return AVERROR(ENOMEM);
331 bytestream2_init(&gbc, buf, buf_size);
332 bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
334 while (bytestream2_get_bytes_left(&gbc)) {
335 if (bytestream2_get_bytes_left(&gbc) >= 3 &&
336 bytestream2_peek_be24(&gbc) <= 3) {
337 bytestream2_put_be24(&pbc, 3);
338 bytestream2_skip(&gbc, 2);
340 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
343 escaped_buf_size = bytestream2_tell_p(&pbc);
344 AV_WB16(escaped_buf, escaped_buf_size - 2);
346 ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
347 av_freep(&escaped_buf);
355 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
357 AVCodecContext *avctx = h->avctx;
360 if (!buf || size <= 0)
365 const unsigned char *p = buf;
370 av_log(avctx, AV_LOG_ERROR,
371 "avcC %d too short\n", size);
372 return AVERROR_INVALIDDATA;
374 /* sps and pps in the avcC always have length coded with 2 bytes,
375 * so put a fake nal_length_size = 2 while parsing them */
376 h->nal_length_size = 2;
377 // Decode sps from avcC
378 cnt = *(p + 5) & 0x1f; // Number of sps
380 for (i = 0; i < cnt; i++) {
381 nalsize = AV_RB16(p) + 2;
382 if(nalsize > size - (p-buf))
383 return AVERROR_INVALIDDATA;
384 ret = decode_extradata_ps_mp4(h, p, nalsize);
386 av_log(avctx, AV_LOG_ERROR,
387 "Decoding sps %d from avcC failed\n", i);
392 // Decode pps from avcC
393 cnt = *(p++); // Number of pps
394 for (i = 0; i < cnt; i++) {
395 nalsize = AV_RB16(p) + 2;
396 if(nalsize > size - (p-buf))
397 return AVERROR_INVALIDDATA;
398 ret = decode_extradata_ps_mp4(h, p, nalsize);
400 av_log(avctx, AV_LOG_ERROR,
401 "Decoding pps %d from avcC failed\n", i);
406 // Store right nal length size that will be used to parse all other nals
407 h->nal_length_size = (buf[4] & 0x03) + 1;
410 ret = decode_nal_units(h, buf, size, 1);
417 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
422 h->backup_width = -1;
423 h->backup_height = -1;
424 h->backup_pix_fmt = AV_PIX_FMT_NONE;
425 h->current_sps_id = -1;
426 h->cur_chroma_format_idc = -1;
428 h->picture_structure = PICT_FRAME;
429 h->slice_context_count = 1;
430 h->workaround_bugs = avctx->workaround_bugs;
431 h->flags = avctx->flags;
432 h->prev_poc_msb = 1 << 16;
434 h->recovery_frame = -1;
435 h->frame_recovered = 0;
436 h->prev_frame_num = -1;
437 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
439 h->next_outputed_poc = INT_MIN;
440 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
441 h->last_pocs[i] = INT_MIN;
443 ff_h264_reset_sei(h);
445 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
447 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
448 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
451 return AVERROR(ENOMEM);
454 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
455 h->DPB[i].f = av_frame_alloc();
457 return AVERROR(ENOMEM);
460 h->cur_pic.f = av_frame_alloc();
462 return AVERROR(ENOMEM);
464 h->last_pic_for_ec.f = av_frame_alloc();
465 if (!h->last_pic_for_ec.f)
466 return AVERROR(ENOMEM);
468 for (i = 0; i < h->nb_slice_ctx; i++)
469 h->slice_ctx[i].h264 = h;
474 static AVOnce h264_vlc_init = AV_ONCE_INIT;
476 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
478 H264Context *h = avctx->priv_data;
481 ret = h264_init_context(avctx, h);
486 if (!avctx->has_b_frames)
489 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
491 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
492 return AVERROR_UNKNOWN;
495 if (avctx->codec_id == AV_CODEC_ID_H264) {
496 if (avctx->ticks_per_frame == 1) {
497 if(h->avctx->time_base.den < INT_MAX/2) {
498 h->avctx->time_base.den *= 2;
500 h->avctx->time_base.num /= 2;
502 avctx->ticks_per_frame = 2;
505 if (avctx->extradata_size > 0 && avctx->extradata) {
506 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
508 h264_decode_end(avctx);
513 if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
514 h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
515 h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
519 avctx->internal->allocate_progress = 1;
521 ff_h264_flush_change(h);
523 if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
526 if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
527 av_log(avctx, AV_LOG_WARNING,
528 "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
529 "Use it at your own risk\n");
536 static int decode_init_thread_copy(AVCodecContext *avctx)
538 H264Context *h = avctx->priv_data;
541 if (!avctx->internal->is_copy)
544 memset(h, 0, sizeof(*h));
546 ret = h264_init_context(avctx, h);
550 h->context_initialized = 0;
557 * Run setup operations that must be run after slice header decoding.
558 * This includes finding the next displayed frame.
560 * @param h h264 master context
561 * @param setup_finished enough NALs have been read that we can call
562 * ff_thread_finish_setup()
564 static void decode_postinit(H264Context *h, int setup_finished)
566 const SPS *sps = h->ps.sps;
567 H264Picture *out = h->cur_pic_ptr;
568 H264Picture *cur = h->cur_pic_ptr;
569 int i, pics, out_of_order, out_idx;
571 h->cur_pic_ptr->f->pict_type = h->pict_type;
573 if (h->next_output_pic)
576 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
577 /* FIXME: if we have two PAFF fields in one packet, we can't start
578 * the next thread here. If we have one field per packet, we can.
579 * The check in decode_nal_units() is not good enough to find this
580 * yet, so we assume the worst for now. */
581 // if (setup_finished)
582 // ff_thread_finish_setup(h->avctx);
583 if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
585 if (h->avctx->hwaccel || h->missing_fields <=1)
589 cur->f->interlaced_frame = 0;
590 cur->f->repeat_pict = 0;
592 /* Signal interlacing information externally. */
593 /* Prioritize picture timing SEI information over used
594 * decoding process if it exists. */
596 if (sps->pic_struct_present_flag) {
597 switch (h->sei_pic_struct) {
598 case SEI_PIC_STRUCT_FRAME:
600 case SEI_PIC_STRUCT_TOP_FIELD:
601 case SEI_PIC_STRUCT_BOTTOM_FIELD:
602 cur->f->interlaced_frame = 1;
604 case SEI_PIC_STRUCT_TOP_BOTTOM:
605 case SEI_PIC_STRUCT_BOTTOM_TOP:
606 if (FIELD_OR_MBAFF_PICTURE(h))
607 cur->f->interlaced_frame = 1;
609 // try to flag soft telecine progressive
610 cur->f->interlaced_frame = h->prev_interlaced_frame;
612 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
613 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
614 /* Signal the possibility of telecined film externally
615 * (pic_struct 5,6). From these hints, let the applications
616 * decide if they apply deinterlacing. */
617 cur->f->repeat_pict = 1;
619 case SEI_PIC_STRUCT_FRAME_DOUBLING:
620 cur->f->repeat_pict = 2;
622 case SEI_PIC_STRUCT_FRAME_TRIPLING:
623 cur->f->repeat_pict = 4;
627 if ((h->sei_ct_type & 3) &&
628 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
629 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
631 /* Derive interlacing flag from used decoding process. */
632 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
634 h->prev_interlaced_frame = cur->f->interlaced_frame;
636 if (cur->field_poc[0] != cur->field_poc[1]) {
637 /* Derive top_field_first from field pocs. */
638 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
640 if (sps->pic_struct_present_flag) {
641 /* Use picture timing SEI information. Even if it is a
642 * information of a past frame, better than nothing. */
643 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
644 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
645 cur->f->top_field_first = 1;
647 cur->f->top_field_first = 0;
648 } else if (cur->f->interlaced_frame) {
649 /* Default to top field first when pic_struct_present_flag
650 * is not set but interlaced frame detected */
651 cur->f->top_field_first = 1;
653 /* Most likely progressive */
654 cur->f->top_field_first = 0;
658 if (h->sei_frame_packing_present &&
659 h->frame_packing_arrangement_type >= 0 &&
660 h->frame_packing_arrangement_type <= 6 &&
661 h->content_interpretation_type > 0 &&
662 h->content_interpretation_type < 3) {
663 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
665 switch (h->frame_packing_arrangement_type) {
667 stereo->type = AV_STEREO3D_CHECKERBOARD;
670 stereo->type = AV_STEREO3D_COLUMNS;
673 stereo->type = AV_STEREO3D_LINES;
676 if (h->quincunx_subsampling)
677 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
679 stereo->type = AV_STEREO3D_SIDEBYSIDE;
682 stereo->type = AV_STEREO3D_TOPBOTTOM;
685 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
688 stereo->type = AV_STEREO3D_2D;
692 if (h->content_interpretation_type == 2)
693 stereo->flags = AV_STEREO3D_FLAG_INVERT;
697 if (h->sei_display_orientation_present &&
698 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
699 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
700 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
701 AV_FRAME_DATA_DISPLAYMATRIX,
702 sizeof(int32_t) * 9);
704 av_display_rotation_set((int32_t *)rotation->data, angle);
705 av_display_matrix_flip((int32_t *)rotation->data,
706 h->sei_hflip, h->sei_vflip);
710 if (h->sei_reguserdata_afd_present) {
711 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
715 *sd->data = h->active_format_description;
716 h->sei_reguserdata_afd_present = 0;
720 if (h->a53_caption) {
721 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
722 AV_FRAME_DATA_A53_CC,
723 h->a53_caption_size);
725 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
726 av_freep(&h->a53_caption);
727 h->a53_caption_size = 0;
728 h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
731 cur->mmco_reset = h->mmco_reset;
734 // FIXME do something with unavailable reference frames
736 /* Sort B-frames into display order */
737 if (sps->bitstream_restriction_flag ||
738 h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
739 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
741 h->low_delay = !h->avctx->has_b_frames;
743 for (i = 0; 1; i++) {
744 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
746 h->last_pocs[i-1] = cur->poc;
749 h->last_pocs[i-1]= h->last_pocs[i];
752 out_of_order = MAX_DELAYED_PIC_COUNT - i;
753 if( cur->f->pict_type == AV_PICTURE_TYPE_B
754 || (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))
755 out_of_order = FFMAX(out_of_order, 1);
756 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
757 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
758 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
759 h->last_pocs[i] = INT_MIN;
760 h->last_pocs[0] = cur->poc;
762 } else if(h->avctx->has_b_frames < out_of_order && !sps->bitstream_restriction_flag){
763 av_log(h->avctx, AV_LOG_INFO, "Increasing reorder buffer to %d\n", out_of_order);
764 h->avctx->has_b_frames = out_of_order;
769 while (h->delayed_pic[pics])
772 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
774 h->delayed_pic[pics++] = cur;
775 if (cur->reference == 0)
776 cur->reference = DELAYED_PIC_REF;
778 out = h->delayed_pic[0];
780 for (i = 1; h->delayed_pic[i] &&
781 !h->delayed_pic[i]->f->key_frame &&
782 !h->delayed_pic[i]->mmco_reset;
784 if (h->delayed_pic[i]->poc < out->poc) {
785 out = h->delayed_pic[i];
788 if (h->avctx->has_b_frames == 0 &&
789 (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
790 h->next_outputed_poc = INT_MIN;
791 out_of_order = out->poc < h->next_outputed_poc;
793 if (out_of_order || pics > h->avctx->has_b_frames) {
794 out->reference &= ~DELAYED_PIC_REF;
795 // for frame threading, the owner must be the second field's thread or
796 // else the first thread can release the picture and reuse it unsafely
797 for (i = out_idx; h->delayed_pic[i]; i++)
798 h->delayed_pic[i] = h->delayed_pic[i + 1];
800 if (!out_of_order && pics > h->avctx->has_b_frames) {
801 h->next_output_pic = out;
802 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
803 h->next_outputed_poc = INT_MIN;
805 h->next_outputed_poc = out->poc;
807 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
810 if (h->next_output_pic) {
811 if (h->next_output_pic->recovered) {
812 // We have reached an recovery point and all frames after it in
813 // display order are "recovered".
814 h->frame_recovered |= FRAME_RECOVERED_SEI;
816 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
819 if (setup_finished && !h->avctx->hwaccel) {
820 ff_thread_finish_setup(h->avctx);
822 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
823 h->setup_finished = 1;
828 * instantaneous decoder refresh.
830 static void idr(H264Context *h)
833 ff_h264_remove_all_refs(h);
835 h->prev_frame_num_offset = 0;
836 h->prev_poc_msb = 1<<16;
838 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
839 h->last_pocs[i] = INT_MIN;
842 /* forget old pics after a seek */
843 void ff_h264_flush_change(H264Context *h)
847 h->next_outputed_poc = INT_MIN;
848 h->prev_interlaced_frame = 1;
851 h->prev_frame_num = -1;
852 if (h->cur_pic_ptr) {
853 h->cur_pic_ptr->reference = 0;
854 for (j=i=0; h->delayed_pic[i]; i++)
855 if (h->delayed_pic[i] != h->cur_pic_ptr)
856 h->delayed_pic[j++] = h->delayed_pic[i];
857 h->delayed_pic[j] = NULL;
859 ff_h264_unref_picture(h, &h->last_pic_for_ec);
862 ff_h264_reset_sei(h);
863 h->recovery_frame = -1;
864 h->frame_recovered = 0;
865 h->current_slice = 0;
867 for (i = 0; i < h->nb_slice_ctx; i++)
868 h->slice_ctx[i].list_count = 0;
871 /* forget old pics after a seek */
872 static void flush_dpb(AVCodecContext *avctx)
874 H264Context *h = avctx->priv_data;
877 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
879 ff_h264_flush_change(h);
881 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
882 ff_h264_unref_picture(h, &h->DPB[i]);
883 h->cur_pic_ptr = NULL;
884 ff_h264_unref_picture(h, &h->cur_pic);
888 ff_h264_free_tables(h);
889 h->context_initialized = 0;
892 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
894 const SPS *sps = h->ps.sps;
895 const int max_frame_num = 1 << sps->log2_max_frame_num;
898 h->frame_num_offset = h->prev_frame_num_offset;
899 if (h->frame_num < h->prev_frame_num)
900 h->frame_num_offset += max_frame_num;
902 if (sps->poc_type == 0) {
903 const int max_poc_lsb = 1 << sps->log2_max_poc_lsb;
905 if (h->poc_lsb < h->prev_poc_lsb &&
906 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
907 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
908 else if (h->poc_lsb > h->prev_poc_lsb &&
909 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
910 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
912 h->poc_msb = h->prev_poc_msb;
914 field_poc[1] = h->poc_msb + h->poc_lsb;
915 if (h->picture_structure == PICT_FRAME)
916 field_poc[1] += h->delta_poc_bottom;
917 } else if (sps->poc_type == 1) {
918 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
921 if (sps->poc_cycle_length != 0)
922 abs_frame_num = h->frame_num_offset + h->frame_num;
926 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
929 expected_delta_per_poc_cycle = 0;
930 for (i = 0; i < sps->poc_cycle_length; i++)
931 // FIXME integrate during sps parse
932 expected_delta_per_poc_cycle += sps->offset_for_ref_frame[i];
934 if (abs_frame_num > 0) {
935 int poc_cycle_cnt = (abs_frame_num - 1) / sps->poc_cycle_length;
936 int frame_num_in_poc_cycle = (abs_frame_num - 1) % sps->poc_cycle_length;
938 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
939 for (i = 0; i <= frame_num_in_poc_cycle; i++)
940 expectedpoc = expectedpoc + sps->offset_for_ref_frame[i];
944 if (h->nal_ref_idc == 0)
945 expectedpoc = expectedpoc + sps->offset_for_non_ref_pic;
947 field_poc[0] = expectedpoc + h->delta_poc[0];
948 field_poc[1] = field_poc[0] + sps->offset_for_top_to_bottom_field;
950 if (h->picture_structure == PICT_FRAME)
951 field_poc[1] += h->delta_poc[1];
953 int poc = 2 * (h->frame_num_offset + h->frame_num);
962 if (h->picture_structure != PICT_BOTTOM_FIELD)
963 pic_field_poc[0] = field_poc[0];
964 if (h->picture_structure != PICT_TOP_FIELD)
965 pic_field_poc[1] = field_poc[1];
966 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
972 * Compute profile from profile_idc and constraint_set?_flags.
976 * @return profile as defined by FF_PROFILE_H264_*
978 int ff_h264_get_profile(const SPS *sps)
980 int profile = sps->profile_idc;
982 switch (sps->profile_idc) {
983 case FF_PROFILE_H264_BASELINE:
984 // constraint_set1_flag set to 1
985 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
987 case FF_PROFILE_H264_HIGH_10:
988 case FF_PROFILE_H264_HIGH_422:
989 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
990 // constraint_set3_flag set to 1
991 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1000 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1003 static int get_last_needed_nal(H264Context *h)
1005 int nals_needed = 0;
1006 int first_slice = 0;
1010 for (i = 0; i < h->pkt.nb_nals; i++) {
1011 H2645NAL *nal = &h->pkt.nals[i];
1014 /* packets can sometimes contain multiple PPS/SPS,
1015 * e.g. two PAFF field pictures in one packet, or a demuxer
1016 * which splits NALs strangely if so, when frame threading we
1017 * can't start the next thread until we've read all of them */
1018 switch (nal->type) {
1026 ret = init_get_bits8(&gb, nal->data + 1, (nal->size - 1));
1029 if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
1031 first_slice != nal->type)
1034 first_slice = nal->type;
1041 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1042 int parse_extradata)
1044 AVCodecContext *const avctx = h->avctx;
1045 unsigned context_count = 0;
1046 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1050 h->nal_unit_type= 0;
1052 if(!h->slice_context_count)
1053 h->slice_context_count= 1;
1054 h->max_contexts = h->slice_context_count;
1055 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1056 h->current_slice = 0;
1057 if (!h->first_field)
1058 h->cur_pic_ptr = NULL;
1059 ff_h264_reset_sei(h);
1062 if (h->nal_length_size == 4) {
1063 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1065 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1069 ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
1070 h->nal_length_size, avctx->codec_id);
1072 av_log(avctx, AV_LOG_ERROR,
1073 "Error splitting the input into NAL units.\n");
1074 /* don't consider NAL parsing failure a fatal error when parsing extradata, as the stream may work without it */
1075 return parse_extradata ? buf_size : ret;
1078 if (avctx->active_thread_type & FF_THREAD_FRAME)
1079 nals_needed = get_last_needed_nal(h);
1080 if (nals_needed < 0)
1083 for (i = 0; i < h->pkt.nb_nals; i++) {
1084 H2645NAL *nal = &h->pkt.nals[i];
1085 H264SliceContext *sl = &h->slice_ctx[context_count];
1088 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1089 nal->ref_idc == 0 && nal->type != NAL_SEI)
1093 /* Ignore per frame NAL unit type during extradata
1094 * parsing. Decoding slices is not possible in codec init
1096 if (parse_extradata) {
1097 switch (nal->type) {
1103 av_log(h->avctx, AV_LOG_WARNING,
1104 "Ignoring NAL %d in global header/extradata\n",
1106 // fall through to next case
1107 case NAL_AUXILIARY_SLICE:
1108 nal->type = NAL_FF_IGNORE;
1112 // FIXME these should stop being context-global variables
1113 h->nal_ref_idc = nal->ref_idc;
1114 h->nal_unit_type = nal->type;
1117 switch (nal->type) {
1119 if ((nal->data[1] & 0xFC) == 0x98) {
1120 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1121 h->next_outputed_poc = INT_MIN;
1125 if (nal->type != NAL_IDR_SLICE) {
1126 av_log(h->avctx, AV_LOG_ERROR,
1127 "Invalid mix of idr and non-idr slices\n");
1132 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1133 av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1134 ret = AVERROR_INVALIDDATA;
1137 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1140 h->has_recovery_point = 1;
1143 if ( nals_needed >= i
1144 || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1147 if ((err = ff_h264_decode_slice_header(h, sl)))
1150 if (h->sei_recovery_frame_cnt >= 0) {
1151 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1152 h->valid_recovery_point = 1;
1154 if ( h->recovery_frame < 0
1155 || av_mod_uintp2(h->recovery_frame - h->frame_num, h->ps.sps->log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1156 h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->ps.sps->log2_max_frame_num);
1158 if (!h->valid_recovery_point)
1159 h->recovery_frame = h->frame_num;
1163 h->cur_pic_ptr->f->key_frame |= (nal->type == NAL_IDR_SLICE);
1165 if (nal->type == NAL_IDR_SLICE ||
1166 (h->recovery_frame == h->frame_num && nal->ref_idc)) {
1167 h->recovery_frame = -1;
1168 h->cur_pic_ptr->recovered = 1;
1170 // If we have an IDR, all frames after it in decoded order are
1172 if (nal->type == NAL_IDR_SLICE)
1173 h->frame_recovered |= FRAME_RECOVERED_IDR;
1175 h->cur_pic_ptr->recovered |= h->frame_recovered;
1177 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1180 if (h->current_slice == 1) {
1181 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1182 decode_postinit(h, i >= nals_needed);
1184 if (h->avctx->hwaccel &&
1185 (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1187 #if FF_API_CAP_VDPAU
1188 if (CONFIG_H264_VDPAU_DECODER &&
1189 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
1190 ff_vdpau_h264_picture_start(h);
1194 if (sl->redundant_pic_count == 0) {
1195 if (avctx->hwaccel) {
1196 ret = avctx->hwaccel->decode_slice(avctx,
1201 #if FF_API_CAP_VDPAU
1202 } else if (CONFIG_H264_VDPAU_DECODER &&
1203 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
1204 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1206 sizeof(start_code));
1207 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1218 avpriv_request_sample(avctx, "data partitioning");
1222 ret = ff_h264_decode_sei(h);
1223 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1227 GetBitContext tmp_gb = nal->gb;
1228 if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
1230 av_log(h->avctx, AV_LOG_DEBUG,
1231 "SPS decoding failure, trying again with the complete NAL\n");
1232 init_get_bits8(&tmp_gb, nal->raw_data + 1, nal->raw_size - 1);
1233 if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
1235 ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps, 1);
1239 ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
1241 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1245 case NAL_END_SEQUENCE:
1246 case NAL_END_STREAM:
1247 case NAL_FILLER_DATA:
1249 case NAL_AUXILIARY_SLICE:
1254 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1255 nal->type, nal->size_bits);
1258 if (context_count == h->max_contexts) {
1259 ret = ff_h264_execute_decode_slices(h, context_count);
1260 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1265 if (err < 0 || err == SLICE_SKIPED) {
1267 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1268 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1269 } else if (err == SLICE_SINGLETHREAD) {
1270 if (context_count > 0) {
1271 ret = ff_h264_execute_decode_slices(h, context_count);
1272 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1276 /* Slice could not be decoded in parallel mode, restart. Note
1277 * that rbsp_buffer is not transferred, but since we no longer
1278 * run in parallel mode this should not be an issue. */
1279 sl = &h->slice_ctx[0];
1283 if (context_count) {
1284 ret = ff_h264_execute_decode_slices(h, context_count);
1285 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1292 #if CONFIG_ERROR_RESILIENCE
1294 * FIXME: Error handling code does not seem to support interlaced
1295 * when slices span multiple rows
1296 * The ff_er_add_slice calls don't work right for bottom
1297 * fields; they cause massive erroneous error concealing
1298 * Error marking covers both fields (top and bottom).
1299 * This causes a mismatched s->error_count
1300 * and a bad error table. Further, the error count goes to
1301 * INT_MAX when called for bottom field, because mb_y is
1302 * past end by one (callers fault) and resync_mb_y != 0
1303 * causes problems for the first MB line, too.
1305 if (!FIELD_PICTURE(h) && h->current_slice &&
1306 h->ps.sps == (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data &&
1309 H264SliceContext *sl = h->slice_ctx;
1310 int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
1312 ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
1315 ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
1316 sl->ref_list[0][0].parent = &h->last_pic_for_ec;
1317 memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
1318 memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
1319 sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
1320 } else if (sl->ref_count[0]) {
1321 ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
1323 ff_h264_set_erpic(&sl->er.last_pic, NULL);
1325 if (sl->ref_count[1])
1326 ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
1328 sl->er.ref_count = sl->ref_count[0];
1330 ff_er_frame_end(&sl->er);
1332 memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
1334 #endif /* CONFIG_ERROR_RESILIENCE */
1336 if (h->cur_pic_ptr && !h->droppable) {
1337 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1338 h->picture_structure == PICT_BOTTOM_FIELD);
1341 return (ret < 0) ? ret : buf_size;
1345 * Return the number of bytes consumed for building the current frame.
1347 static int get_consumed_bytes(int pos, int buf_size)
1350 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1351 if (pos + 10 > buf_size)
1352 pos = buf_size; // oops ;)
1357 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1359 AVFrame *src = srcp->f;
1360 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1362 int ret = av_frame_ref(dst, src);
1366 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1368 h->backup_width = h->avctx->width;
1369 h->backup_height = h->avctx->height;
1370 h->backup_pix_fmt = h->avctx->pix_fmt;
1372 h->avctx->width = dst->width;
1373 h->avctx->height = dst->height;
1374 h->avctx->pix_fmt = dst->format;
1376 if (srcp->sei_recovery_frame_cnt == 0)
1381 for (i = 0; i < desc->nb_components; i++) {
1382 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1383 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1384 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1385 (srcp->crop_top >> vshift) * dst->linesize[i];
1386 dst->data[i] += off;
1391 static int is_extra(const uint8_t *buf, int buf_size)
1393 int cnt= buf[5]&0x1f;
1394 const uint8_t *p= buf+6;
1396 int nalsize= AV_RB16(p) + 2;
1397 if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
1405 int nalsize= AV_RB16(p) + 2;
1406 if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
1413 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1414 int *got_frame, AVPacket *avpkt)
1416 const uint8_t *buf = avpkt->data;
1417 int buf_size = avpkt->size;
1418 H264Context *h = avctx->priv_data;
1419 AVFrame *pict = data;
1425 h->flags = avctx->flags;
1426 h->setup_finished = 0;
1428 if (h->backup_width != -1) {
1429 avctx->width = h->backup_width;
1430 h->backup_width = -1;
1432 if (h->backup_height != -1) {
1433 avctx->height = h->backup_height;
1434 h->backup_height = -1;
1436 if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
1437 avctx->pix_fmt = h->backup_pix_fmt;
1438 h->backup_pix_fmt = AV_PIX_FMT_NONE;
1441 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1443 /* end of stream, output what is still in the buffers */
1444 if (buf_size == 0) {
1447 h->cur_pic_ptr = NULL;
1450 // FIXME factorize this with the output code below
1451 out = h->delayed_pic[0];
1454 h->delayed_pic[i] &&
1455 !h->delayed_pic[i]->f->key_frame &&
1456 !h->delayed_pic[i]->mmco_reset;
1458 if (h->delayed_pic[i]->poc < out->poc) {
1459 out = h->delayed_pic[i];
1463 for (i = out_idx; h->delayed_pic[i]; i++)
1464 h->delayed_pic[i] = h->delayed_pic[i + 1];
1467 out->reference &= ~DELAYED_PIC_REF;
1468 ret = output_frame(h, pict, out);
1476 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1478 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1479 if (is_extra(side, side_size))
1480 ff_h264_decode_extradata(h, side, side_size);
1482 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1483 if (is_extra(buf, buf_size))
1484 return ff_h264_decode_extradata(h, buf, buf_size);
1487 buf_index = decode_nal_units(h, buf, buf_size, 0);
1489 return AVERROR_INVALIDDATA;
1491 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1492 av_assert0(buf_index <= buf_size);
1496 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1497 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1498 buf_size >= 4 && !memcmp("Q264", buf, 4))
1500 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1501 return AVERROR_INVALIDDATA;
1504 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1505 (h->mb_y >= h->mb_height && h->mb_height)) {
1506 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1507 decode_postinit(h, 1);
1509 if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
1512 /* Wait for second field. */
1514 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1515 (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
1516 h->next_output_pic->recovered)) {
1517 if (!h->next_output_pic->recovered)
1518 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1520 if (!h->avctx->hwaccel &&
1521 (h->next_output_pic->field_poc[0] == INT_MAX ||
1522 h->next_output_pic->field_poc[1] == INT_MAX)
1525 AVFrame *f = h->next_output_pic->f;
1526 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1527 uint8_t *dst_data[4];
1529 const uint8_t *src_data[4];
1531 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1533 for (p = 0; p<4; p++) {
1534 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1535 src_data[p] = f->data[p] + field *f->linesize[p];
1536 linesizes[p] = 2*f->linesize[p];
1539 av_image_copy(dst_data, linesizes, src_data, linesizes,
1540 f->format, f->width, f->height>>1);
1543 ret = output_frame(h, pict, h->next_output_pic);
1547 if (CONFIG_MPEGVIDEO) {
1548 ff_print_debug_info2(h->avctx, pict, NULL,
1549 h->next_output_pic->mb_type,
1550 h->next_output_pic->qscale_table,
1551 h->next_output_pic->motion_val,
1553 h->mb_width, h->mb_height, h->mb_stride, 1);
1558 av_assert0(pict->buf[0] || !*got_frame);
1560 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1562 return get_consumed_bytes(buf_index, buf_size);
1565 av_cold void ff_h264_free_context(H264Context *h)
1569 ff_h264_free_tables(h);
1571 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1572 ff_h264_unref_picture(h, &h->DPB[i]);
1573 av_frame_free(&h->DPB[i].f);
1575 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1577 h->cur_pic_ptr = NULL;
1579 for (i = 0; i < h->nb_slice_ctx; i++)
1580 av_freep(&h->slice_ctx[i].rbsp_buffer);
1581 av_freep(&h->slice_ctx);
1582 h->nb_slice_ctx = 0;
1584 h->a53_caption_size = 0;
1585 av_freep(&h->a53_caption);
1587 for (i = 0; i < MAX_SPS_COUNT; i++)
1588 av_buffer_unref(&h->ps.sps_list[i]);
1590 for (i = 0; i < MAX_PPS_COUNT; i++)
1591 av_buffer_unref(&h->ps.pps_list[i]);
1593 av_buffer_unref(&h->ps.sps_ref);
1594 av_buffer_unref(&h->ps.pps_ref);
1596 ff_h2645_packet_uninit(&h->pkt);
1599 static av_cold int h264_decode_end(AVCodecContext *avctx)
1601 H264Context *h = avctx->priv_data;
1603 ff_h264_remove_all_refs(h);
1604 ff_h264_free_context(h);
1606 ff_h264_unref_picture(h, &h->cur_pic);
1607 av_frame_free(&h->cur_pic.f);
1608 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1609 av_frame_free(&h->last_pic_for_ec.f);
1614 #define OFFSET(x) offsetof(H264Context, x)
1615 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1616 static const AVOption h264_options[] = {
1617 {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
1618 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1619 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
1623 static const AVClass h264_class = {
1624 .class_name = "H264 Decoder",
1625 .item_name = av_default_item_name,
1626 .option = h264_options,
1627 .version = LIBAVUTIL_VERSION_INT,
1630 AVCodec ff_h264_decoder = {
1632 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1633 .type = AVMEDIA_TYPE_VIDEO,
1634 .id = AV_CODEC_ID_H264,
1635 .priv_data_size = sizeof(H264Context),
1636 .init = ff_h264_decode_init,
1637 .close = h264_decode_end,
1638 .decode = h264_decode_frame,
1639 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1640 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1641 AV_CODEC_CAP_FRAME_THREADS,
1642 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1644 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1645 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1646 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1647 .priv_class = &h264_class,
1650 #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
1651 static const AVClass h264_vdpau_class = {
1652 .class_name = "H264 VDPAU Decoder",
1653 .item_name = av_default_item_name,
1654 .option = h264_options,
1655 .version = LIBAVUTIL_VERSION_INT,
1658 AVCodec ff_h264_vdpau_decoder = {
1659 .name = "h264_vdpau",
1660 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
1661 .type = AVMEDIA_TYPE_VIDEO,
1662 .id = AV_CODEC_ID_H264,
1663 .priv_data_size = sizeof(H264Context),
1664 .init = ff_h264_decode_init,
1665 .close = h264_decode_end,
1666 .decode = h264_decode_frame,
1667 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
1669 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
1671 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1672 .priv_class = &h264_vdpau_class,