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"
38 #include "cabac_functions.h"
39 #include "error_resilience.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
48 #include "mpegutils.h"
50 #include "rectangle.h"
52 #include "vdpau_compat.h"
54 static int h264_decode_end(AVCodecContext *avctx);
56 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
58 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
60 H264Context *h = avctx->priv_data;
61 return h ? h->sps.num_reorder_frames : 0;
64 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
66 int mb_x, int mb_y, int mb_intra, int mb_skipped)
68 H264Context *h = opaque;
69 H264SliceContext *sl = &h->slice_ctx[0];
73 sl->mb_xy = mb_x + mb_y * h->mb_stride;
74 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
76 /* FIXME: It is possible albeit uncommon that slice references
77 * differ between slices. We take the easy approach and ignore
78 * it for now. If this turns out to have any relevance in
79 * practice then correct remapping should be added. */
80 if (ref >= sl->ref_count[0])
82 if (!sl->ref_list[0][ref].data[0]) {
83 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
86 if ((sl->ref_list[0][ref].reference&3) != 3) {
87 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
90 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
92 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
93 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
94 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
96 sl->mb_field_decoding_flag = 0;
97 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
100 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
103 AVCodecContext *avctx = h->avctx;
104 const AVFrame *src = h->cur_pic.f;
105 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
106 int vshift = desc->log2_chroma_h;
107 const int field_pic = h->picture_structure != PICT_FRAME;
113 height = FFMIN(height, avctx->height - y);
115 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
118 if (avctx->draw_horiz_band) {
119 int offset[AV_NUM_DATA_POINTERS];
122 offset[0] = y * src->linesize[0];
124 offset[2] = (y >> vshift) * src->linesize[1];
125 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
130 avctx->draw_horiz_band(avctx, src, offset,
131 y, h->picture_structure, height);
135 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
137 int *dst_length, int *consumed, int length)
142 // src[0]&0x80; // forbidden bit
143 h->nal_ref_idc = src[0] >> 5;
144 h->nal_unit_type = src[0] & 0x1F;
149 #define STARTCODE_TEST \
150 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
151 if (src[i + 2] != 3 && src[i + 2] != 0) { \
152 /* startcode, so we must be past the end */ \
158 #if HAVE_FAST_UNALIGNED
159 #define FIND_FIRST_ZERO \
160 if (i > 0 && !src[i]) \
166 for (i = 0; i + 1 < length; i += 9) {
167 if (!((~AV_RN64A(src + i) &
168 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
169 0x8000800080008080ULL))
176 for (i = 0; i + 1 < length; i += 5) {
177 if (!((~AV_RN32A(src + i) &
178 (AV_RN32A(src + i) - 0x01000101U)) &
187 for (i = 0; i + 1 < length; i += 2) {
190 if (i > 0 && src[i - 1] == 0)
196 av_fast_padded_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size, length+MAX_MBPAIR_SIZE);
197 dst = sl->rbsp_buffer;
202 if(i>=length-1){ //no escaped 0
204 *consumed= length+1; //+1 for the header
205 if(h->avctx->flags2 & AV_CODEC_FLAG2_FAST){
208 memcpy(dst, src, length);
215 while (si + 2 < length) {
216 // remove escapes (very rare 1:2^22)
217 if (src[si + 2] > 3) {
218 dst[di++] = src[si++];
219 dst[di++] = src[si++];
220 } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {
221 if (src[si + 2] == 3) { // escape
226 } else // next start code
230 dst[di++] = src[si++];
233 dst[di++] = src[si++];
236 memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
239 *consumed = si + 1; // +1 for the header
240 /* FIXME store exact number of bits in the getbitcontext
241 * (it is needed for decoding) */
246 * Identify the exact end of the bitstream
247 * @return the length of the trailing, or 0 if damaged
249 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
254 ff_tlog(h->avctx, "rbsp trailing %X\n", v);
256 for (r = 1; r < 9; r++) {
264 void ff_h264_free_tables(H264Context *h)
268 av_freep(&h->intra4x4_pred_mode);
269 av_freep(&h->chroma_pred_mode_table);
270 av_freep(&h->cbp_table);
271 av_freep(&h->mvd_table[0]);
272 av_freep(&h->mvd_table[1]);
273 av_freep(&h->direct_table);
274 av_freep(&h->non_zero_count);
275 av_freep(&h->slice_table_base);
276 h->slice_table = NULL;
277 av_freep(&h->list_counts);
279 av_freep(&h->mb2b_xy);
280 av_freep(&h->mb2br_xy);
282 av_buffer_pool_uninit(&h->qscale_table_pool);
283 av_buffer_pool_uninit(&h->mb_type_pool);
284 av_buffer_pool_uninit(&h->motion_val_pool);
285 av_buffer_pool_uninit(&h->ref_index_pool);
287 for (i = 0; i < h->nb_slice_ctx; i++) {
288 H264SliceContext *sl = &h->slice_ctx[i];
290 av_freep(&sl->dc_val_base);
291 av_freep(&sl->er.mb_index2xy);
292 av_freep(&sl->er.error_status_table);
293 av_freep(&sl->er.er_temp_buffer);
295 av_freep(&sl->bipred_scratchpad);
296 av_freep(&sl->edge_emu_buffer);
297 av_freep(&sl->top_borders[0]);
298 av_freep(&sl->top_borders[1]);
300 sl->bipred_scratchpad_allocated = 0;
301 sl->edge_emu_buffer_allocated = 0;
302 sl->top_borders_allocated[0] = 0;
303 sl->top_borders_allocated[1] = 0;
307 int ff_h264_alloc_tables(H264Context *h)
309 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
310 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
313 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
314 row_mb_num, 8 * sizeof(uint8_t), fail)
315 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
317 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
318 big_mb_num * 48 * sizeof(uint8_t), fail)
319 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
320 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
321 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
322 big_mb_num * sizeof(uint16_t), fail)
323 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
324 big_mb_num * sizeof(uint8_t), fail)
325 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
326 row_mb_num, 16 * sizeof(uint8_t), fail);
327 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
328 row_mb_num, 16 * sizeof(uint8_t), fail);
329 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
330 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
332 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
333 4 * big_mb_num * sizeof(uint8_t), fail);
334 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
335 big_mb_num * sizeof(uint8_t), fail)
337 memset(h->slice_table_base, -1,
338 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
339 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
341 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
342 big_mb_num * sizeof(uint32_t), fail);
343 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
344 big_mb_num * sizeof(uint32_t), fail);
345 for (y = 0; y < h->mb_height; y++)
346 for (x = 0; x < h->mb_width; x++) {
347 const int mb_xy = x + y * h->mb_stride;
348 const int b_xy = 4 * x + 4 * y * h->b_stride;
350 h->mb2b_xy[mb_xy] = b_xy;
351 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
354 if (!h->dequant4_coeff[0])
355 ff_h264_init_dequant_tables(h);
360 ff_h264_free_tables(h);
361 return AVERROR(ENOMEM);
366 * Allocate buffers which are not shared amongst multiple threads.
368 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
370 ERContext *er = &sl->er;
371 int mb_array_size = h->mb_height * h->mb_stride;
372 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
373 int c_size = h->mb_stride * (h->mb_height + 1);
374 int yc_size = y_size + 2 * c_size;
377 sl->ref_cache[0][scan8[5] + 1] =
378 sl->ref_cache[0][scan8[7] + 1] =
379 sl->ref_cache[0][scan8[13] + 1] =
380 sl->ref_cache[1][scan8[5] + 1] =
381 sl->ref_cache[1][scan8[7] + 1] =
382 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
384 if (sl != h->slice_ctx) {
385 memset(er, 0, sizeof(*er));
387 if (CONFIG_ERROR_RESILIENCE) {
390 er->avctx = h->avctx;
391 er->decode_mb = h264_er_decode_mb;
393 er->quarter_sample = 1;
395 er->mb_num = h->mb_num;
396 er->mb_width = h->mb_width;
397 er->mb_height = h->mb_height;
398 er->mb_stride = h->mb_stride;
399 er->b8_stride = h->mb_width * 2 + 1;
401 // error resilience code looks cleaner with this
402 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
403 (h->mb_num + 1) * sizeof(int), fail);
405 for (y = 0; y < h->mb_height; y++)
406 for (x = 0; x < h->mb_width; x++)
407 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
409 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
410 h->mb_stride + h->mb_width;
412 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
413 mb_array_size * sizeof(uint8_t), fail);
415 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
416 h->mb_height * h->mb_stride, fail);
418 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
419 yc_size * sizeof(int16_t), fail);
420 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
421 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
422 er->dc_val[2] = er->dc_val[1] + c_size;
423 for (i = 0; i < yc_size; i++)
424 sl->dc_val_base[i] = 1024;
430 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
433 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
434 int parse_extradata);
436 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
438 AVCodecContext *avctx = h->avctx;
441 if (!buf || size <= 0)
446 const unsigned char *p = buf;
451 av_log(avctx, AV_LOG_ERROR,
452 "avcC %d too short\n", size);
453 return AVERROR_INVALIDDATA;
455 /* sps and pps in the avcC always have length coded with 2 bytes,
456 * so put a fake nal_length_size = 2 while parsing them */
457 h->nal_length_size = 2;
458 // Decode sps from avcC
459 cnt = *(p + 5) & 0x1f; // Number of sps
461 for (i = 0; i < cnt; i++) {
462 nalsize = AV_RB16(p) + 2;
463 if(nalsize > size - (p-buf))
464 return AVERROR_INVALIDDATA;
465 ret = decode_nal_units(h, p, nalsize, 1);
467 av_log(avctx, AV_LOG_ERROR,
468 "Decoding sps %d from avcC failed\n", i);
473 // Decode pps from avcC
474 cnt = *(p++); // Number of pps
475 for (i = 0; i < cnt; i++) {
476 nalsize = AV_RB16(p) + 2;
477 if(nalsize > size - (p-buf))
478 return AVERROR_INVALIDDATA;
479 ret = decode_nal_units(h, p, nalsize, 1);
481 av_log(avctx, AV_LOG_ERROR,
482 "Decoding pps %d from avcC failed\n", i);
487 // Store right nal length size that will be used to parse all other nals
488 h->nal_length_size = (buf[4] & 0x03) + 1;
491 ret = decode_nal_units(h, buf, size, 1);
498 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
503 h->backup_width = -1;
504 h->backup_height = -1;
505 h->backup_pix_fmt = AV_PIX_FMT_NONE;
506 h->dequant_coeff_pps = -1;
507 h->current_sps_id = -1;
508 h->cur_chroma_format_idc = -1;
510 h->picture_structure = PICT_FRAME;
511 h->slice_context_count = 1;
512 h->workaround_bugs = avctx->workaround_bugs;
513 h->flags = avctx->flags;
514 h->prev_poc_msb = 1 << 16;
516 h->recovery_frame = -1;
517 h->frame_recovered = 0;
518 h->prev_frame_num = -1;
519 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
521 h->next_outputed_poc = INT_MIN;
522 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
523 h->last_pocs[i] = INT_MIN;
525 ff_h264_reset_sei(h);
527 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
529 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
530 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
533 return AVERROR(ENOMEM);
536 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
537 h->DPB[i].f = av_frame_alloc();
539 return AVERROR(ENOMEM);
542 h->cur_pic.f = av_frame_alloc();
544 return AVERROR(ENOMEM);
546 h->last_pic_for_ec.f = av_frame_alloc();
547 if (!h->last_pic_for_ec.f)
548 return AVERROR(ENOMEM);
550 for (i = 0; i < h->nb_slice_ctx; i++)
551 h->slice_ctx[i].h264 = h;
556 static AVOnce h264_vlc_init = AV_ONCE_INIT;
558 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
560 H264Context *h = avctx->priv_data;
563 ret = h264_init_context(avctx, h);
568 if (!avctx->has_b_frames)
571 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
573 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
574 return AVERROR_UNKNOWN;
577 if (avctx->codec_id == AV_CODEC_ID_H264) {
578 if (avctx->ticks_per_frame == 1) {
579 if(h->avctx->time_base.den < INT_MAX/2) {
580 h->avctx->time_base.den *= 2;
582 h->avctx->time_base.num /= 2;
584 avctx->ticks_per_frame = 2;
587 if (avctx->extradata_size > 0 && avctx->extradata) {
588 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
590 h264_decode_end(avctx);
595 if (h->sps.bitstream_restriction_flag &&
596 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
597 h->avctx->has_b_frames = h->sps.num_reorder_frames;
601 avctx->internal->allocate_progress = 1;
603 ff_h264_flush_change(h);
605 if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
608 if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
609 av_log(avctx, AV_LOG_WARNING,
610 "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
611 "Use it at your own risk\n");
618 static int decode_init_thread_copy(AVCodecContext *avctx)
620 H264Context *h = avctx->priv_data;
623 if (!avctx->internal->is_copy)
626 memset(h, 0, sizeof(*h));
628 ret = h264_init_context(avctx, h);
632 h->context_initialized = 0;
639 * Run setup operations that must be run after slice header decoding.
640 * This includes finding the next displayed frame.
642 * @param h h264 master context
643 * @param setup_finished enough NALs have been read that we can call
644 * ff_thread_finish_setup()
646 static void decode_postinit(H264Context *h, int setup_finished)
648 H264Picture *out = h->cur_pic_ptr;
649 H264Picture *cur = h->cur_pic_ptr;
650 int i, pics, out_of_order, out_idx;
652 h->cur_pic_ptr->f->pict_type = h->pict_type;
654 if (h->next_output_pic)
657 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
658 /* FIXME: if we have two PAFF fields in one packet, we can't start
659 * the next thread here. If we have one field per packet, we can.
660 * The check in decode_nal_units() is not good enough to find this
661 * yet, so we assume the worst for now. */
662 // if (setup_finished)
663 // ff_thread_finish_setup(h->avctx);
664 if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
666 if (h->avctx->hwaccel || h->missing_fields <=1)
670 cur->f->interlaced_frame = 0;
671 cur->f->repeat_pict = 0;
673 /* Signal interlacing information externally. */
674 /* Prioritize picture timing SEI information over used
675 * decoding process if it exists. */
677 if (h->sps.pic_struct_present_flag) {
678 switch (h->sei_pic_struct) {
679 case SEI_PIC_STRUCT_FRAME:
681 case SEI_PIC_STRUCT_TOP_FIELD:
682 case SEI_PIC_STRUCT_BOTTOM_FIELD:
683 cur->f->interlaced_frame = 1;
685 case SEI_PIC_STRUCT_TOP_BOTTOM:
686 case SEI_PIC_STRUCT_BOTTOM_TOP:
687 if (FIELD_OR_MBAFF_PICTURE(h))
688 cur->f->interlaced_frame = 1;
690 // try to flag soft telecine progressive
691 cur->f->interlaced_frame = h->prev_interlaced_frame;
693 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
694 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
695 /* Signal the possibility of telecined film externally
696 * (pic_struct 5,6). From these hints, let the applications
697 * decide if they apply deinterlacing. */
698 cur->f->repeat_pict = 1;
700 case SEI_PIC_STRUCT_FRAME_DOUBLING:
701 cur->f->repeat_pict = 2;
703 case SEI_PIC_STRUCT_FRAME_TRIPLING:
704 cur->f->repeat_pict = 4;
708 if ((h->sei_ct_type & 3) &&
709 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
710 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
712 /* Derive interlacing flag from used decoding process. */
713 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
715 h->prev_interlaced_frame = cur->f->interlaced_frame;
717 if (cur->field_poc[0] != cur->field_poc[1]) {
718 /* Derive top_field_first from field pocs. */
719 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
721 if (h->sps.pic_struct_present_flag) {
722 /* Use picture timing SEI information. Even if it is a
723 * information of a past frame, better than nothing. */
724 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
725 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
726 cur->f->top_field_first = 1;
728 cur->f->top_field_first = 0;
729 } else if (cur->f->interlaced_frame) {
730 /* Default to top field first when pic_struct_present_flag
731 * is not set but interlaced frame detected */
732 cur->f->top_field_first = 1;
734 /* Most likely progressive */
735 cur->f->top_field_first = 0;
739 if (h->sei_frame_packing_present &&
740 h->frame_packing_arrangement_type >= 0 &&
741 h->frame_packing_arrangement_type <= 6 &&
742 h->content_interpretation_type > 0 &&
743 h->content_interpretation_type < 3) {
744 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
746 switch (h->frame_packing_arrangement_type) {
748 stereo->type = AV_STEREO3D_CHECKERBOARD;
751 stereo->type = AV_STEREO3D_COLUMNS;
754 stereo->type = AV_STEREO3D_LINES;
757 if (h->quincunx_subsampling)
758 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
760 stereo->type = AV_STEREO3D_SIDEBYSIDE;
763 stereo->type = AV_STEREO3D_TOPBOTTOM;
766 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
769 stereo->type = AV_STEREO3D_2D;
773 if (h->content_interpretation_type == 2)
774 stereo->flags = AV_STEREO3D_FLAG_INVERT;
778 if (h->sei_display_orientation_present &&
779 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
780 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
781 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
782 AV_FRAME_DATA_DISPLAYMATRIX,
783 sizeof(int32_t) * 9);
785 av_display_rotation_set((int32_t *)rotation->data, angle);
786 av_display_matrix_flip((int32_t *)rotation->data,
787 h->sei_hflip, h->sei_vflip);
791 if (h->sei_reguserdata_afd_present) {
792 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
796 *sd->data = h->active_format_description;
797 h->sei_reguserdata_afd_present = 0;
801 if (h->a53_caption) {
802 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
803 AV_FRAME_DATA_A53_CC,
804 h->a53_caption_size);
806 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
807 av_freep(&h->a53_caption);
808 h->a53_caption_size = 0;
809 h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
812 cur->mmco_reset = h->mmco_reset;
815 // FIXME do something with unavailable reference frames
817 /* Sort B-frames into display order */
818 if (h->sps.bitstream_restriction_flag ||
819 h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
820 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
822 h->low_delay = !h->avctx->has_b_frames;
824 for (i = 0; 1; i++) {
825 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
827 h->last_pocs[i-1] = cur->poc;
830 h->last_pocs[i-1]= h->last_pocs[i];
833 out_of_order = MAX_DELAYED_PIC_COUNT - i;
834 if( cur->f->pict_type == AV_PICTURE_TYPE_B
835 || (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))
836 out_of_order = FFMAX(out_of_order, 1);
837 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
838 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
839 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
840 h->last_pocs[i] = INT_MIN;
841 h->last_pocs[0] = cur->poc;
843 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
844 av_log(h->avctx, AV_LOG_INFO, "Increasing reorder buffer to %d\n", out_of_order);
845 h->avctx->has_b_frames = out_of_order;
850 while (h->delayed_pic[pics])
853 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
855 h->delayed_pic[pics++] = cur;
856 if (cur->reference == 0)
857 cur->reference = DELAYED_PIC_REF;
859 out = h->delayed_pic[0];
861 for (i = 1; h->delayed_pic[i] &&
862 !h->delayed_pic[i]->f->key_frame &&
863 !h->delayed_pic[i]->mmco_reset;
865 if (h->delayed_pic[i]->poc < out->poc) {
866 out = h->delayed_pic[i];
869 if (h->avctx->has_b_frames == 0 &&
870 (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
871 h->next_outputed_poc = INT_MIN;
872 out_of_order = out->poc < h->next_outputed_poc;
874 if (out_of_order || pics > h->avctx->has_b_frames) {
875 out->reference &= ~DELAYED_PIC_REF;
876 // for frame threading, the owner must be the second field's thread or
877 // else the first thread can release the picture and reuse it unsafely
878 for (i = out_idx; h->delayed_pic[i]; i++)
879 h->delayed_pic[i] = h->delayed_pic[i + 1];
881 if (!out_of_order && pics > h->avctx->has_b_frames) {
882 h->next_output_pic = out;
883 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
884 h->next_outputed_poc = INT_MIN;
886 h->next_outputed_poc = out->poc;
888 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
891 if (h->next_output_pic) {
892 if (h->next_output_pic->recovered) {
893 // We have reached an recovery point and all frames after it in
894 // display order are "recovered".
895 h->frame_recovered |= FRAME_RECOVERED_SEI;
897 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
900 if (setup_finished && !h->avctx->hwaccel) {
901 ff_thread_finish_setup(h->avctx);
903 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
904 h->setup_finished = 1;
909 * instantaneous decoder refresh.
911 static void idr(H264Context *h)
914 ff_h264_remove_all_refs(h);
916 h->prev_frame_num_offset = 0;
917 h->prev_poc_msb = 1<<16;
919 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
920 h->last_pocs[i] = INT_MIN;
923 /* forget old pics after a seek */
924 void ff_h264_flush_change(H264Context *h)
928 h->next_outputed_poc = INT_MIN;
929 h->prev_interlaced_frame = 1;
932 h->prev_frame_num = -1;
933 if (h->cur_pic_ptr) {
934 h->cur_pic_ptr->reference = 0;
935 for (j=i=0; h->delayed_pic[i]; i++)
936 if (h->delayed_pic[i] != h->cur_pic_ptr)
937 h->delayed_pic[j++] = h->delayed_pic[i];
938 h->delayed_pic[j] = NULL;
940 ff_h264_unref_picture(h, &h->last_pic_for_ec);
943 ff_h264_reset_sei(h);
944 h->recovery_frame = -1;
945 h->frame_recovered = 0;
946 h->current_slice = 0;
948 for (i = 0; i < h->nb_slice_ctx; i++)
949 h->slice_ctx[i].list_count = 0;
952 /* forget old pics after a seek */
953 static void flush_dpb(AVCodecContext *avctx)
955 H264Context *h = avctx->priv_data;
958 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
960 ff_h264_flush_change(h);
962 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
963 ff_h264_unref_picture(h, &h->DPB[i]);
964 h->cur_pic_ptr = NULL;
965 ff_h264_unref_picture(h, &h->cur_pic);
969 ff_h264_free_tables(h);
970 h->context_initialized = 0;
973 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
975 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
978 h->frame_num_offset = h->prev_frame_num_offset;
979 if (h->frame_num < h->prev_frame_num)
980 h->frame_num_offset += max_frame_num;
982 if (h->sps.poc_type == 0) {
983 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
985 if (h->poc_lsb < h->prev_poc_lsb &&
986 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
987 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
988 else if (h->poc_lsb > h->prev_poc_lsb &&
989 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
990 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
992 h->poc_msb = h->prev_poc_msb;
994 field_poc[1] = h->poc_msb + h->poc_lsb;
995 if (h->picture_structure == PICT_FRAME)
996 field_poc[1] += h->delta_poc_bottom;
997 } else if (h->sps.poc_type == 1) {
998 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1001 if (h->sps.poc_cycle_length != 0)
1002 abs_frame_num = h->frame_num_offset + h->frame_num;
1006 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1009 expected_delta_per_poc_cycle = 0;
1010 for (i = 0; i < h->sps.poc_cycle_length; i++)
1011 // FIXME integrate during sps parse
1012 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1014 if (abs_frame_num > 0) {
1015 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1016 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1018 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1019 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1020 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1024 if (h->nal_ref_idc == 0)
1025 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1027 field_poc[0] = expectedpoc + h->delta_poc[0];
1028 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1030 if (h->picture_structure == PICT_FRAME)
1031 field_poc[1] += h->delta_poc[1];
1033 int poc = 2 * (h->frame_num_offset + h->frame_num);
1035 if (!h->nal_ref_idc)
1042 if (h->picture_structure != PICT_BOTTOM_FIELD)
1043 pic_field_poc[0] = field_poc[0];
1044 if (h->picture_structure != PICT_TOP_FIELD)
1045 pic_field_poc[1] = field_poc[1];
1046 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1052 * Compute profile from profile_idc and constraint_set?_flags.
1056 * @return profile as defined by FF_PROFILE_H264_*
1058 int ff_h264_get_profile(SPS *sps)
1060 int profile = sps->profile_idc;
1062 switch (sps->profile_idc) {
1063 case FF_PROFILE_H264_BASELINE:
1064 // constraint_set1_flag set to 1
1065 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1067 case FF_PROFILE_H264_HIGH_10:
1068 case FF_PROFILE_H264_HIGH_422:
1069 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1070 // constraint_set3_flag set to 1
1071 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1078 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1080 int ref_count[2], list_count;
1081 int num_ref_idx_active_override_flag;
1083 // set defaults, might be overridden a few lines later
1084 ref_count[0] = h->pps.ref_count[0];
1085 ref_count[1] = h->pps.ref_count[1];
1087 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1089 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1091 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1092 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1093 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1095 if (num_ref_idx_active_override_flag) {
1096 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1097 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1098 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1100 // full range is spec-ok in this case, even for frames
1104 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1105 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]);
1106 sl->ref_count[0] = sl->ref_count[1] = 0;
1108 return AVERROR_INVALIDDATA;
1111 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1117 ref_count[0] = ref_count[1] = 0;
1120 if (list_count != sl->list_count ||
1121 ref_count[0] != sl->ref_count[0] ||
1122 ref_count[1] != sl->ref_count[1]) {
1123 sl->ref_count[0] = ref_count[0];
1124 sl->ref_count[1] = ref_count[1];
1125 sl->list_count = list_count;
1132 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1134 static int get_bit_length(H264Context *h, const uint8_t *buf,
1135 const uint8_t *ptr, int dst_length,
1136 int i, int next_avc)
1138 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1139 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1140 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1141 h->workaround_bugs |= FF_BUG_TRUNCATED;
1143 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1144 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1150 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1153 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1155 int next_avc = h->is_avc ? 0 : buf_size;
1158 int nals_needed = 0;
1159 int first_slice = 0;
1164 int dst_length, bit_length, consumed;
1167 if (buf_index >= next_avc) {
1168 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1171 next_avc = buf_index + nalsize;
1173 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1174 if (buf_index >= buf_size)
1176 if (buf_index >= next_avc)
1180 ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1181 next_avc - buf_index);
1183 if (!ptr || dst_length < 0)
1184 return AVERROR_INVALIDDATA;
1186 buf_index += consumed;
1188 bit_length = get_bit_length(h, buf, ptr, dst_length,
1189 buf_index, next_avc);
1192 /* packets can sometimes contain multiple PPS/SPS,
1193 * e.g. two PAFF field pictures in one packet, or a demuxer
1194 * which splits NALs strangely if so, when frame threading we
1195 * can't start the next thread until we've read all of them */
1196 switch (h->nal_unit_type) {
1199 nals_needed = nal_index;
1204 init_get_bits(&gb, ptr, bit_length);
1205 if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
1207 first_slice != h->nal_unit_type)
1208 nals_needed = nal_index;
1210 first_slice = h->nal_unit_type;
1217 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1218 int parse_extradata)
1220 AVCodecContext *const avctx = h->avctx;
1221 H264SliceContext *sl;
1223 unsigned context_count;
1225 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1230 h->nal_unit_type= 0;
1232 if(!h->slice_context_count)
1233 h->slice_context_count= 1;
1234 h->max_contexts = h->slice_context_count;
1235 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1236 h->current_slice = 0;
1237 if (!h->first_field)
1238 h->cur_pic_ptr = NULL;
1239 ff_h264_reset_sei(h);
1242 if (h->nal_length_size == 4) {
1243 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1245 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1249 if (avctx->active_thread_type & FF_THREAD_FRAME)
1250 nals_needed = get_last_needed_nal(h, buf, buf_size);
1255 next_avc = h->is_avc ? 0 : buf_size;
1265 if (buf_index >= next_avc) {
1266 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1269 next_avc = buf_index + nalsize;
1271 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1272 if (buf_index >= buf_size)
1274 if (buf_index >= next_avc)
1278 sl = &h->slice_ctx[context_count];
1280 ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1281 &consumed, next_avc - buf_index);
1282 if (!ptr || dst_length < 0) {
1287 bit_length = get_bit_length(h, buf, ptr, dst_length,
1288 buf_index + consumed, next_avc);
1290 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1291 av_log(h->avctx, AV_LOG_DEBUG,
1292 "NAL %d/%d at %d/%d length %d\n",
1293 h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
1295 if (h->is_avc && (nalsize != consumed) && nalsize)
1296 av_log(h->avctx, AV_LOG_DEBUG,
1297 "AVC: Consumed only %d bytes instead of %d\n",
1300 buf_index += consumed;
1303 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1304 h->nal_ref_idc == 0 &&
1305 h->nal_unit_type != NAL_SEI)
1309 /* Ignore per frame NAL unit type during extradata
1310 * parsing. Decoding slices is not possible in codec init
1312 if (parse_extradata) {
1313 switch (h->nal_unit_type) {
1319 av_log(h->avctx, AV_LOG_WARNING,
1320 "Ignoring NAL %d in global header/extradata\n",
1322 // fall through to next case
1323 case NAL_AUXILIARY_SLICE:
1324 h->nal_unit_type = NAL_FF_IGNORE;
1330 switch (h->nal_unit_type) {
1332 if ((ptr[0] & 0xFC) == 0x98) {
1333 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1334 h->next_outputed_poc = INT_MIN;
1338 if (h->nal_unit_type != NAL_IDR_SLICE) {
1339 av_log(h->avctx, AV_LOG_ERROR,
1340 "Invalid mix of idr and non-idr slices\n");
1345 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1346 av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1347 ret = AVERROR_INVALIDDATA;
1350 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1353 h->has_recovery_point = 1;
1355 init_get_bits(&sl->gb, ptr, bit_length);
1357 if ( nals_needed >= nal_index
1358 || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1361 if ((err = ff_h264_decode_slice_header(h, sl)))
1364 if (h->sei_recovery_frame_cnt >= 0) {
1365 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1366 h->valid_recovery_point = 1;
1368 if ( h->recovery_frame < 0
1369 || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1370 h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
1372 if (!h->valid_recovery_point)
1373 h->recovery_frame = h->frame_num;
1377 h->cur_pic_ptr->f->key_frame |=
1378 (h->nal_unit_type == NAL_IDR_SLICE);
1380 if (h->nal_unit_type == NAL_IDR_SLICE ||
1381 (h->recovery_frame == h->frame_num && h->nal_ref_idc)) {
1382 h->recovery_frame = -1;
1383 h->cur_pic_ptr->recovered = 1;
1385 // If we have an IDR, all frames after it in decoded order are
1387 if (h->nal_unit_type == NAL_IDR_SLICE)
1388 h->frame_recovered |= FRAME_RECOVERED_IDR;
1390 h->cur_pic_ptr->recovered |= h->frame_recovered;
1392 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1395 if (h->current_slice == 1) {
1396 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1397 decode_postinit(h, nal_index >= nals_needed);
1399 if (h->avctx->hwaccel &&
1400 (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1402 #if FF_API_CAP_VDPAU
1403 if (CONFIG_H264_VDPAU_DECODER &&
1404 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
1405 ff_vdpau_h264_picture_start(h);
1409 if (sl->redundant_pic_count == 0) {
1410 if (avctx->hwaccel) {
1411 ret = avctx->hwaccel->decode_slice(avctx,
1412 &buf[buf_index - consumed],
1416 #if FF_API_CAP_VDPAU
1417 } else if (CONFIG_H264_VDPAU_DECODER &&
1418 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
1419 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1421 sizeof(start_code));
1422 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1423 &buf[buf_index - consumed],
1433 avpriv_request_sample(avctx, "data partitioning");
1436 init_get_bits(&h->gb, ptr, bit_length);
1437 ret = ff_h264_decode_sei(h);
1438 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1442 init_get_bits(&h->gb, ptr, bit_length);
1443 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1445 if (h->is_avc ? nalsize : 1) {
1446 av_log(h->avctx, AV_LOG_DEBUG,
1447 "SPS decoding failure, trying again with the complete NAL\n");
1449 av_assert0(next_avc - buf_index + consumed == nalsize);
1450 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1452 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1453 8*(next_avc - buf_index + consumed - 1));
1454 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1457 init_get_bits(&h->gb, ptr, bit_length);
1458 ff_h264_decode_seq_parameter_set(h, 1);
1462 init_get_bits(&h->gb, ptr, bit_length);
1463 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1464 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1468 case NAL_END_SEQUENCE:
1469 case NAL_END_STREAM:
1470 case NAL_FILLER_DATA:
1472 case NAL_AUXILIARY_SLICE:
1477 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1478 h->nal_unit_type, bit_length);
1481 if (context_count == h->max_contexts) {
1482 ret = ff_h264_execute_decode_slices(h, context_count);
1483 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1488 if (err < 0 || err == SLICE_SKIPED) {
1490 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1491 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1492 } else if (err == SLICE_SINGLETHREAD) {
1493 if (context_count > 1) {
1494 ret = ff_h264_execute_decode_slices(h, context_count - 1);
1495 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1499 /* Slice could not be decoded in parallel mode, restart. Note
1500 * that rbsp_buffer is not transferred, but since we no longer
1501 * run in parallel mode this should not be an issue. */
1502 sl = &h->slice_ctx[0];
1507 if (context_count) {
1508 ret = ff_h264_execute_decode_slices(h, context_count);
1509 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1516 #if CONFIG_ERROR_RESILIENCE
1519 * FIXME: Error handling code does not seem to support interlaced
1520 * when slices span multiple rows
1521 * The ff_er_add_slice calls don't work right for bottom
1522 * fields; they cause massive erroneous error concealing
1523 * Error marking covers both fields (top and bottom).
1524 * This causes a mismatched s->error_count
1525 * and a bad error table. Further, the error count goes to
1526 * INT_MAX when called for bottom field, because mb_y is
1527 * past end by one (callers fault) and resync_mb_y != 0
1528 * causes problems for the first MB line, too.
1530 if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new && h->enable_er) {
1531 int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
1533 ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
1536 ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
1537 sl->ref_list[0][0].parent = &h->last_pic_for_ec;
1538 memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
1539 memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
1540 sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
1541 } else if (sl->ref_count[0]) {
1542 ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
1544 ff_h264_set_erpic(&sl->er.last_pic, NULL);
1546 if (sl->ref_count[1])
1547 ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
1549 sl->er.ref_count = sl->ref_count[0];
1551 ff_er_frame_end(&sl->er);
1553 memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
1555 #endif /* CONFIG_ERROR_RESILIENCE */
1557 if (h->cur_pic_ptr && !h->droppable) {
1558 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1559 h->picture_structure == PICT_BOTTOM_FIELD);
1562 return (ret < 0) ? ret : buf_index;
1566 * Return the number of bytes consumed for building the current frame.
1568 static int get_consumed_bytes(int pos, int buf_size)
1571 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1572 if (pos + 10 > buf_size)
1573 pos = buf_size; // oops ;)
1578 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1580 AVFrame *src = srcp->f;
1581 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1583 int ret = av_frame_ref(dst, src);
1587 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1589 h->backup_width = h->avctx->width;
1590 h->backup_height = h->avctx->height;
1591 h->backup_pix_fmt = h->avctx->pix_fmt;
1593 h->avctx->width = dst->width;
1594 h->avctx->height = dst->height;
1595 h->avctx->pix_fmt = dst->format;
1597 if (srcp->sei_recovery_frame_cnt == 0)
1602 for (i = 0; i < desc->nb_components; i++) {
1603 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1604 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1605 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1606 (srcp->crop_top >> vshift) * dst->linesize[i];
1607 dst->data[i] += off;
1612 static int is_extra(const uint8_t *buf, int buf_size)
1614 int cnt= buf[5]&0x1f;
1615 const uint8_t *p= buf+6;
1617 int nalsize= AV_RB16(p) + 2;
1618 if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
1626 int nalsize= AV_RB16(p) + 2;
1627 if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
1634 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1635 int *got_frame, AVPacket *avpkt)
1637 const uint8_t *buf = avpkt->data;
1638 int buf_size = avpkt->size;
1639 H264Context *h = avctx->priv_data;
1640 AVFrame *pict = data;
1646 h->flags = avctx->flags;
1647 h->setup_finished = 0;
1649 if (h->backup_width != -1) {
1650 avctx->width = h->backup_width;
1651 h->backup_width = -1;
1653 if (h->backup_height != -1) {
1654 avctx->height = h->backup_height;
1655 h->backup_height = -1;
1657 if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
1658 avctx->pix_fmt = h->backup_pix_fmt;
1659 h->backup_pix_fmt = AV_PIX_FMT_NONE;
1662 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1664 /* end of stream, output what is still in the buffers */
1665 if (buf_size == 0) {
1668 h->cur_pic_ptr = NULL;
1671 // FIXME factorize this with the output code below
1672 out = h->delayed_pic[0];
1675 h->delayed_pic[i] &&
1676 !h->delayed_pic[i]->f->key_frame &&
1677 !h->delayed_pic[i]->mmco_reset;
1679 if (h->delayed_pic[i]->poc < out->poc) {
1680 out = h->delayed_pic[i];
1684 for (i = out_idx; h->delayed_pic[i]; i++)
1685 h->delayed_pic[i] = h->delayed_pic[i + 1];
1688 out->reference &= ~DELAYED_PIC_REF;
1689 ret = output_frame(h, pict, out);
1697 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1699 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1700 if (is_extra(side, side_size))
1701 ff_h264_decode_extradata(h, side, side_size);
1703 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1704 if (is_extra(buf, buf_size))
1705 return ff_h264_decode_extradata(h, buf, buf_size);
1708 buf_index = decode_nal_units(h, buf, buf_size, 0);
1710 return AVERROR_INVALIDDATA;
1712 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1713 av_assert0(buf_index <= buf_size);
1717 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1718 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1719 buf_size >= 4 && !memcmp("Q264", buf, 4))
1721 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1722 return AVERROR_INVALIDDATA;
1725 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1726 (h->mb_y >= h->mb_height && h->mb_height)) {
1727 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1728 decode_postinit(h, 1);
1730 if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
1733 /* Wait for second field. */
1735 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1736 (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
1737 h->next_output_pic->recovered)) {
1738 if (!h->next_output_pic->recovered)
1739 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1741 if (!h->avctx->hwaccel &&
1742 (h->next_output_pic->field_poc[0] == INT_MAX ||
1743 h->next_output_pic->field_poc[1] == INT_MAX)
1746 AVFrame *f = h->next_output_pic->f;
1747 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1748 uint8_t *dst_data[4];
1750 const uint8_t *src_data[4];
1752 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1754 for (p = 0; p<4; p++) {
1755 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1756 src_data[p] = f->data[p] + field *f->linesize[p];
1757 linesizes[p] = 2*f->linesize[p];
1760 av_image_copy(dst_data, linesizes, src_data, linesizes,
1761 f->format, f->width, f->height>>1);
1764 ret = output_frame(h, pict, h->next_output_pic);
1768 if (CONFIG_MPEGVIDEO) {
1769 ff_print_debug_info2(h->avctx, pict, NULL,
1770 h->next_output_pic->mb_type,
1771 h->next_output_pic->qscale_table,
1772 h->next_output_pic->motion_val,
1774 h->mb_width, h->mb_height, h->mb_stride, 1);
1779 av_assert0(pict->buf[0] || !*got_frame);
1781 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1783 return get_consumed_bytes(buf_index, buf_size);
1786 av_cold void ff_h264_free_context(H264Context *h)
1790 ff_h264_free_tables(h);
1792 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1793 ff_h264_unref_picture(h, &h->DPB[i]);
1794 av_frame_free(&h->DPB[i].f);
1796 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1798 h->cur_pic_ptr = NULL;
1800 for (i = 0; i < h->nb_slice_ctx; i++)
1801 av_freep(&h->slice_ctx[i].rbsp_buffer);
1802 av_freep(&h->slice_ctx);
1803 h->nb_slice_ctx = 0;
1805 h->a53_caption_size = 0;
1806 av_freep(&h->a53_caption);
1808 for (i = 0; i < MAX_SPS_COUNT; i++)
1809 av_freep(h->sps_buffers + i);
1811 for (i = 0; i < MAX_PPS_COUNT; i++)
1812 av_freep(h->pps_buffers + i);
1815 static av_cold int h264_decode_end(AVCodecContext *avctx)
1817 H264Context *h = avctx->priv_data;
1819 ff_h264_remove_all_refs(h);
1820 ff_h264_free_context(h);
1822 ff_h264_unref_picture(h, &h->cur_pic);
1823 av_frame_free(&h->cur_pic.f);
1824 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1825 av_frame_free(&h->last_pic_for_ec.f);
1830 #define OFFSET(x) offsetof(H264Context, x)
1831 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1832 static const AVOption h264_options[] = {
1833 {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
1834 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1835 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
1839 static const AVClass h264_class = {
1840 .class_name = "H264 Decoder",
1841 .item_name = av_default_item_name,
1842 .option = h264_options,
1843 .version = LIBAVUTIL_VERSION_INT,
1846 AVCodec ff_h264_decoder = {
1848 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1849 .type = AVMEDIA_TYPE_VIDEO,
1850 .id = AV_CODEC_ID_H264,
1851 .priv_data_size = sizeof(H264Context),
1852 .init = ff_h264_decode_init,
1853 .close = h264_decode_end,
1854 .decode = h264_decode_frame,
1855 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1856 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1857 AV_CODEC_CAP_FRAME_THREADS,
1858 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1860 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1861 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1862 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1863 .priv_class = &h264_class,
1866 #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
1867 static const AVClass h264_vdpau_class = {
1868 .class_name = "H264 VDPAU Decoder",
1869 .item_name = av_default_item_name,
1870 .option = h264_options,
1871 .version = LIBAVUTIL_VERSION_INT,
1874 AVCodec ff_h264_vdpau_decoder = {
1875 .name = "h264_vdpau",
1876 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
1877 .type = AVMEDIA_TYPE_VIDEO,
1878 .id = AV_CODEC_ID_H264,
1879 .priv_data_size = sizeof(H264Context),
1880 .init = ff_h264_decode_init,
1881 .close = h264_decode_end,
1882 .decode = h264_decode_frame,
1883 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
1885 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
1887 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1888 .priv_class = &h264_vdpau_class,