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"
53 #include "vdpau_compat.h"
55 static int h264_decode_end(AVCodecContext *avctx);
57 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
59 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
61 H264Context *h = avctx->priv_data;
62 return h ? h->sps.num_reorder_frames : 0;
65 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
67 int mb_x, int mb_y, int mb_intra, int mb_skipped)
69 H264Context *h = opaque;
70 H264SliceContext *sl = &h->slice_ctx[0];
74 sl->mb_xy = mb_x + mb_y * h->mb_stride;
75 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
77 /* FIXME: It is possible albeit uncommon that slice references
78 * differ between slices. We take the easy approach and ignore
79 * it for now. If this turns out to have any relevance in
80 * practice then correct remapping should be added. */
81 if (ref >= sl->ref_count[0])
83 if (!sl->ref_list[0][ref].data[0]) {
84 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
87 if ((sl->ref_list[0][ref].reference&3) != 3) {
88 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
91 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
93 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
94 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
95 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
97 sl->mb_field_decoding_flag = 0;
98 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
101 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
104 AVCodecContext *avctx = h->avctx;
105 const AVFrame *src = h->cur_pic.f;
106 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
107 int vshift = desc->log2_chroma_h;
108 const int field_pic = h->picture_structure != PICT_FRAME;
114 height = FFMIN(height, avctx->height - y);
116 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
119 if (avctx->draw_horiz_band) {
120 int offset[AV_NUM_DATA_POINTERS];
123 offset[0] = y * src->linesize[0];
125 offset[2] = (y >> vshift) * src->linesize[1];
126 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
131 avctx->draw_horiz_band(avctx, src, offset,
132 y, h->picture_structure, height);
137 * Check if the top & left blocks are available if needed and
138 * change the dc mode so it only uses the available blocks.
140 int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
142 static const int8_t top[12] = {
143 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
145 static const int8_t left[12] = {
146 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
150 if (!(sl->top_samples_available & 0x8000)) {
151 for (i = 0; i < 4; i++) {
152 int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
154 av_log(h->avctx, AV_LOG_ERROR,
155 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
156 status, sl->mb_x, sl->mb_y);
157 return AVERROR_INVALIDDATA;
159 sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
164 if ((sl->left_samples_available & 0x8888) != 0x8888) {
165 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
166 for (i = 0; i < 4; i++)
167 if (!(sl->left_samples_available & mask[i])) {
168 int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
170 av_log(h->avctx, AV_LOG_ERROR,
171 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
172 status, sl->mb_x, sl->mb_y);
173 return AVERROR_INVALIDDATA;
175 sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
181 } // FIXME cleanup like ff_h264_check_intra_pred_mode
184 * Check if the top & left blocks are available if needed and
185 * change the dc mode so it only uses the available blocks.
187 int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
188 int mode, int is_chroma)
190 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
191 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
194 av_log(h->avctx, AV_LOG_ERROR,
195 "out of range intra chroma pred mode at %d %d\n",
197 return AVERROR_INVALIDDATA;
200 if (!(sl->top_samples_available & 0x8000)) {
203 av_log(h->avctx, AV_LOG_ERROR,
204 "top block unavailable for requested intra mode at %d %d\n",
206 return AVERROR_INVALIDDATA;
210 if ((sl->left_samples_available & 0x8080) != 0x8080) {
213 av_log(h->avctx, AV_LOG_ERROR,
214 "left block unavailable for requested intra mode at %d %d\n",
216 return AVERROR_INVALIDDATA;
218 if (is_chroma && (sl->left_samples_available & 0x8080)) {
219 // mad cow disease mode, aka MBAFF + constrained_intra_pred
220 mode = ALZHEIMER_DC_L0T_PRED8x8 +
221 (!(sl->left_samples_available & 0x8000)) +
222 2 * (mode == DC_128_PRED8x8);
229 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
231 int *dst_length, int *consumed, int length)
236 // src[0]&0x80; // forbidden bit
237 h->nal_ref_idc = src[0] >> 5;
238 h->nal_unit_type = src[0] & 0x1F;
243 #define STARTCODE_TEST \
244 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
245 if (src[i + 2] != 3 && src[i + 2] != 0) { \
246 /* startcode, so we must be past the end */ \
252 #if HAVE_FAST_UNALIGNED
253 #define FIND_FIRST_ZERO \
254 if (i > 0 && !src[i]) \
260 for (i = 0; i + 1 < length; i += 9) {
261 if (!((~AV_RN64A(src + i) &
262 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
263 0x8000800080008080ULL))
270 for (i = 0; i + 1 < length; i += 5) {
271 if (!((~AV_RN32A(src + i) &
272 (AV_RN32A(src + i) - 0x01000101U)) &
281 for (i = 0; i + 1 < length; i += 2) {
284 if (i > 0 && src[i - 1] == 0)
290 av_fast_padded_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size, length+MAX_MBPAIR_SIZE);
291 dst = sl->rbsp_buffer;
296 if(i>=length-1){ //no escaped 0
298 *consumed= length+1; //+1 for the header
299 if(h->avctx->flags2 & AV_CODEC_FLAG2_FAST){
302 memcpy(dst, src, length);
309 while (si + 2 < length) {
310 // remove escapes (very rare 1:2^22)
311 if (src[si + 2] > 3) {
312 dst[di++] = src[si++];
313 dst[di++] = src[si++];
314 } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {
315 if (src[si + 2] == 3) { // escape
320 } else // next start code
324 dst[di++] = src[si++];
327 dst[di++] = src[si++];
330 memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
333 *consumed = si + 1; // +1 for the header
334 /* FIXME store exact number of bits in the getbitcontext
335 * (it is needed for decoding) */
340 * Identify the exact end of the bitstream
341 * @return the length of the trailing, or 0 if damaged
343 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
348 ff_tlog(h->avctx, "rbsp trailing %X\n", v);
350 for (r = 1; r < 9; r++) {
358 void ff_h264_free_tables(H264Context *h)
362 av_freep(&h->intra4x4_pred_mode);
363 av_freep(&h->chroma_pred_mode_table);
364 av_freep(&h->cbp_table);
365 av_freep(&h->mvd_table[0]);
366 av_freep(&h->mvd_table[1]);
367 av_freep(&h->direct_table);
368 av_freep(&h->non_zero_count);
369 av_freep(&h->slice_table_base);
370 h->slice_table = NULL;
371 av_freep(&h->list_counts);
373 av_freep(&h->mb2b_xy);
374 av_freep(&h->mb2br_xy);
376 av_buffer_pool_uninit(&h->qscale_table_pool);
377 av_buffer_pool_uninit(&h->mb_type_pool);
378 av_buffer_pool_uninit(&h->motion_val_pool);
379 av_buffer_pool_uninit(&h->ref_index_pool);
381 for (i = 0; i < h->nb_slice_ctx; i++) {
382 H264SliceContext *sl = &h->slice_ctx[i];
384 av_freep(&sl->dc_val_base);
385 av_freep(&sl->er.mb_index2xy);
386 av_freep(&sl->er.error_status_table);
387 av_freep(&sl->er.er_temp_buffer);
389 av_freep(&sl->bipred_scratchpad);
390 av_freep(&sl->edge_emu_buffer);
391 av_freep(&sl->top_borders[0]);
392 av_freep(&sl->top_borders[1]);
394 sl->bipred_scratchpad_allocated = 0;
395 sl->edge_emu_buffer_allocated = 0;
396 sl->top_borders_allocated[0] = 0;
397 sl->top_borders_allocated[1] = 0;
401 int ff_h264_alloc_tables(H264Context *h)
403 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
404 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
407 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
408 row_mb_num, 8 * sizeof(uint8_t), fail)
409 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
411 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
412 big_mb_num * 48 * sizeof(uint8_t), fail)
413 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
414 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
415 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
416 big_mb_num * sizeof(uint16_t), fail)
417 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
418 big_mb_num * sizeof(uint8_t), fail)
419 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
420 row_mb_num, 16 * sizeof(uint8_t), fail);
421 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
422 row_mb_num, 16 * sizeof(uint8_t), fail);
423 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
424 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
426 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
427 4 * big_mb_num * sizeof(uint8_t), fail);
428 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
429 big_mb_num * sizeof(uint8_t), fail)
431 memset(h->slice_table_base, -1,
432 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
433 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
435 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
436 big_mb_num * sizeof(uint32_t), fail);
437 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
438 big_mb_num * sizeof(uint32_t), fail);
439 for (y = 0; y < h->mb_height; y++)
440 for (x = 0; x < h->mb_width; x++) {
441 const int mb_xy = x + y * h->mb_stride;
442 const int b_xy = 4 * x + 4 * y * h->b_stride;
444 h->mb2b_xy[mb_xy] = b_xy;
445 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
448 if (!h->dequant4_coeff[0])
449 ff_h264_init_dequant_tables(h);
454 ff_h264_free_tables(h);
455 return AVERROR(ENOMEM);
460 * Allocate buffers which are not shared amongst multiple threads.
462 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
464 ERContext *er = &sl->er;
465 int mb_array_size = h->mb_height * h->mb_stride;
466 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
467 int c_size = h->mb_stride * (h->mb_height + 1);
468 int yc_size = y_size + 2 * c_size;
471 sl->ref_cache[0][scan8[5] + 1] =
472 sl->ref_cache[0][scan8[7] + 1] =
473 sl->ref_cache[0][scan8[13] + 1] =
474 sl->ref_cache[1][scan8[5] + 1] =
475 sl->ref_cache[1][scan8[7] + 1] =
476 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
478 if (sl != h->slice_ctx) {
479 memset(er, 0, sizeof(*er));
481 if (CONFIG_ERROR_RESILIENCE) {
484 er->avctx = h->avctx;
485 er->decode_mb = h264_er_decode_mb;
487 er->quarter_sample = 1;
489 er->mb_num = h->mb_num;
490 er->mb_width = h->mb_width;
491 er->mb_height = h->mb_height;
492 er->mb_stride = h->mb_stride;
493 er->b8_stride = h->mb_width * 2 + 1;
495 // error resilience code looks cleaner with this
496 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
497 (h->mb_num + 1) * sizeof(int), fail);
499 for (y = 0; y < h->mb_height; y++)
500 for (x = 0; x < h->mb_width; x++)
501 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
503 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
504 h->mb_stride + h->mb_width;
506 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
507 mb_array_size * sizeof(uint8_t), fail);
509 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
510 h->mb_height * h->mb_stride, fail);
512 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
513 yc_size * sizeof(int16_t), fail);
514 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
515 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
516 er->dc_val[2] = er->dc_val[1] + c_size;
517 for (i = 0; i < yc_size; i++)
518 sl->dc_val_base[i] = 1024;
524 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
527 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
528 int parse_extradata);
530 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
532 AVCodecContext *avctx = h->avctx;
535 if (!buf || size <= 0)
540 const unsigned char *p = buf;
545 av_log(avctx, AV_LOG_ERROR,
546 "avcC %d too short\n", size);
547 return AVERROR_INVALIDDATA;
549 /* sps and pps in the avcC always have length coded with 2 bytes,
550 * so put a fake nal_length_size = 2 while parsing them */
551 h->nal_length_size = 2;
552 // Decode sps from avcC
553 cnt = *(p + 5) & 0x1f; // Number of sps
555 for (i = 0; i < cnt; i++) {
556 nalsize = AV_RB16(p) + 2;
557 if(nalsize > size - (p-buf))
558 return AVERROR_INVALIDDATA;
559 ret = decode_nal_units(h, p, nalsize, 1);
561 av_log(avctx, AV_LOG_ERROR,
562 "Decoding sps %d from avcC failed\n", i);
567 // Decode pps from avcC
568 cnt = *(p++); // Number of pps
569 for (i = 0; i < cnt; i++) {
570 nalsize = AV_RB16(p) + 2;
571 if(nalsize > size - (p-buf))
572 return AVERROR_INVALIDDATA;
573 ret = decode_nal_units(h, p, nalsize, 1);
575 av_log(avctx, AV_LOG_ERROR,
576 "Decoding pps %d from avcC failed\n", i);
581 // Store right nal length size that will be used to parse all other nals
582 h->nal_length_size = (buf[4] & 0x03) + 1;
585 ret = decode_nal_units(h, buf, size, 1);
592 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
597 h->backup_width = -1;
598 h->backup_height = -1;
599 h->backup_pix_fmt = AV_PIX_FMT_NONE;
600 h->dequant_coeff_pps = -1;
601 h->current_sps_id = -1;
602 h->cur_chroma_format_idc = -1;
604 h->picture_structure = PICT_FRAME;
605 h->slice_context_count = 1;
606 h->workaround_bugs = avctx->workaround_bugs;
607 h->flags = avctx->flags;
608 h->prev_poc_msb = 1 << 16;
610 h->recovery_frame = -1;
611 h->frame_recovered = 0;
612 h->prev_frame_num = -1;
613 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
615 h->next_outputed_poc = INT_MIN;
616 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
617 h->last_pocs[i] = INT_MIN;
619 ff_h264_reset_sei(h);
621 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
623 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
624 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
627 return AVERROR(ENOMEM);
630 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
631 h->DPB[i].f = av_frame_alloc();
633 return AVERROR(ENOMEM);
636 h->cur_pic.f = av_frame_alloc();
638 return AVERROR(ENOMEM);
640 h->last_pic_for_ec.f = av_frame_alloc();
641 if (!h->last_pic_for_ec.f)
642 return AVERROR(ENOMEM);
644 for (i = 0; i < h->nb_slice_ctx; i++)
645 h->slice_ctx[i].h264 = h;
650 static AVOnce h264_vlc_init = AV_ONCE_INIT;
652 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
654 H264Context *h = avctx->priv_data;
657 ret = h264_init_context(avctx, h);
662 if (!avctx->has_b_frames)
665 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
667 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
668 return AVERROR_UNKNOWN;
671 if (avctx->codec_id == AV_CODEC_ID_H264) {
672 if (avctx->ticks_per_frame == 1) {
673 if(h->avctx->time_base.den < INT_MAX/2) {
674 h->avctx->time_base.den *= 2;
676 h->avctx->time_base.num /= 2;
678 avctx->ticks_per_frame = 2;
681 if (avctx->extradata_size > 0 && avctx->extradata) {
682 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
684 h264_decode_end(avctx);
689 if (h->sps.bitstream_restriction_flag &&
690 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
691 h->avctx->has_b_frames = h->sps.num_reorder_frames;
695 avctx->internal->allocate_progress = 1;
697 ff_h264_flush_change(h);
699 if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
702 if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
703 av_log(avctx, AV_LOG_WARNING,
704 "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
705 "Use it at your own risk\n");
712 static int decode_init_thread_copy(AVCodecContext *avctx)
714 H264Context *h = avctx->priv_data;
717 if (!avctx->internal->is_copy)
720 memset(h, 0, sizeof(*h));
722 ret = h264_init_context(avctx, h);
726 h->context_initialized = 0;
733 * Run setup operations that must be run after slice header decoding.
734 * This includes finding the next displayed frame.
736 * @param h h264 master context
737 * @param setup_finished enough NALs have been read that we can call
738 * ff_thread_finish_setup()
740 static void decode_postinit(H264Context *h, int setup_finished)
742 H264Picture *out = h->cur_pic_ptr;
743 H264Picture *cur = h->cur_pic_ptr;
744 int i, pics, out_of_order, out_idx;
746 h->cur_pic_ptr->f->pict_type = h->pict_type;
748 if (h->next_output_pic)
751 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
752 /* FIXME: if we have two PAFF fields in one packet, we can't start
753 * the next thread here. If we have one field per packet, we can.
754 * The check in decode_nal_units() is not good enough to find this
755 * yet, so we assume the worst for now. */
756 // if (setup_finished)
757 // ff_thread_finish_setup(h->avctx);
758 if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
760 if (h->avctx->hwaccel || h->missing_fields <=1)
764 cur->f->interlaced_frame = 0;
765 cur->f->repeat_pict = 0;
767 /* Signal interlacing information externally. */
768 /* Prioritize picture timing SEI information over used
769 * decoding process if it exists. */
771 if (h->sps.pic_struct_present_flag) {
772 switch (h->sei_pic_struct) {
773 case SEI_PIC_STRUCT_FRAME:
775 case SEI_PIC_STRUCT_TOP_FIELD:
776 case SEI_PIC_STRUCT_BOTTOM_FIELD:
777 cur->f->interlaced_frame = 1;
779 case SEI_PIC_STRUCT_TOP_BOTTOM:
780 case SEI_PIC_STRUCT_BOTTOM_TOP:
781 if (FIELD_OR_MBAFF_PICTURE(h))
782 cur->f->interlaced_frame = 1;
784 // try to flag soft telecine progressive
785 cur->f->interlaced_frame = h->prev_interlaced_frame;
787 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
788 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
789 /* Signal the possibility of telecined film externally
790 * (pic_struct 5,6). From these hints, let the applications
791 * decide if they apply deinterlacing. */
792 cur->f->repeat_pict = 1;
794 case SEI_PIC_STRUCT_FRAME_DOUBLING:
795 cur->f->repeat_pict = 2;
797 case SEI_PIC_STRUCT_FRAME_TRIPLING:
798 cur->f->repeat_pict = 4;
802 if ((h->sei_ct_type & 3) &&
803 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
804 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
806 /* Derive interlacing flag from used decoding process. */
807 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
809 h->prev_interlaced_frame = cur->f->interlaced_frame;
811 if (cur->field_poc[0] != cur->field_poc[1]) {
812 /* Derive top_field_first from field pocs. */
813 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
815 if (h->sps.pic_struct_present_flag) {
816 /* Use picture timing SEI information. Even if it is a
817 * information of a past frame, better than nothing. */
818 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
819 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
820 cur->f->top_field_first = 1;
822 cur->f->top_field_first = 0;
823 } else if (cur->f->interlaced_frame) {
824 /* Default to top field first when pic_struct_present_flag
825 * is not set but interlaced frame detected */
826 cur->f->top_field_first = 1;
828 /* Most likely progressive */
829 cur->f->top_field_first = 0;
833 if (h->sei_frame_packing_present &&
834 h->frame_packing_arrangement_type >= 0 &&
835 h->frame_packing_arrangement_type <= 6 &&
836 h->content_interpretation_type > 0 &&
837 h->content_interpretation_type < 3) {
838 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
840 switch (h->frame_packing_arrangement_type) {
842 stereo->type = AV_STEREO3D_CHECKERBOARD;
845 stereo->type = AV_STEREO3D_COLUMNS;
848 stereo->type = AV_STEREO3D_LINES;
851 if (h->quincunx_subsampling)
852 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
854 stereo->type = AV_STEREO3D_SIDEBYSIDE;
857 stereo->type = AV_STEREO3D_TOPBOTTOM;
860 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
863 stereo->type = AV_STEREO3D_2D;
867 if (h->content_interpretation_type == 2)
868 stereo->flags = AV_STEREO3D_FLAG_INVERT;
872 if (h->sei_display_orientation_present &&
873 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
874 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
875 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
876 AV_FRAME_DATA_DISPLAYMATRIX,
877 sizeof(int32_t) * 9);
879 av_display_rotation_set((int32_t *)rotation->data, angle);
880 av_display_matrix_flip((int32_t *)rotation->data,
881 h->sei_hflip, h->sei_vflip);
885 if (h->sei_reguserdata_afd_present) {
886 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
890 *sd->data = h->active_format_description;
891 h->sei_reguserdata_afd_present = 0;
895 if (h->a53_caption) {
896 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
897 AV_FRAME_DATA_A53_CC,
898 h->a53_caption_size);
900 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
901 av_freep(&h->a53_caption);
902 h->a53_caption_size = 0;
903 h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
906 cur->mmco_reset = h->mmco_reset;
909 // FIXME do something with unavailable reference frames
911 /* Sort B-frames into display order */
912 if (h->sps.bitstream_restriction_flag ||
913 h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
914 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
916 h->low_delay = !h->avctx->has_b_frames;
918 for (i = 0; 1; i++) {
919 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
921 h->last_pocs[i-1] = cur->poc;
924 h->last_pocs[i-1]= h->last_pocs[i];
927 out_of_order = MAX_DELAYED_PIC_COUNT - i;
928 if( cur->f->pict_type == AV_PICTURE_TYPE_B
929 || (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))
930 out_of_order = FFMAX(out_of_order, 1);
931 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
932 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
933 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
934 h->last_pocs[i] = INT_MIN;
935 h->last_pocs[0] = cur->poc;
937 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
938 av_log(h->avctx, AV_LOG_INFO, "Increasing reorder buffer to %d\n", out_of_order);
939 h->avctx->has_b_frames = out_of_order;
944 while (h->delayed_pic[pics])
947 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
949 h->delayed_pic[pics++] = cur;
950 if (cur->reference == 0)
951 cur->reference = DELAYED_PIC_REF;
953 out = h->delayed_pic[0];
955 for (i = 1; h->delayed_pic[i] &&
956 !h->delayed_pic[i]->f->key_frame &&
957 !h->delayed_pic[i]->mmco_reset;
959 if (h->delayed_pic[i]->poc < out->poc) {
960 out = h->delayed_pic[i];
963 if (h->avctx->has_b_frames == 0 &&
964 (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
965 h->next_outputed_poc = INT_MIN;
966 out_of_order = out->poc < h->next_outputed_poc;
968 if (out_of_order || pics > h->avctx->has_b_frames) {
969 out->reference &= ~DELAYED_PIC_REF;
970 // for frame threading, the owner must be the second field's thread or
971 // else the first thread can release the picture and reuse it unsafely
972 for (i = out_idx; h->delayed_pic[i]; i++)
973 h->delayed_pic[i] = h->delayed_pic[i + 1];
975 if (!out_of_order && pics > h->avctx->has_b_frames) {
976 h->next_output_pic = out;
977 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
978 h->next_outputed_poc = INT_MIN;
980 h->next_outputed_poc = out->poc;
982 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
985 if (h->next_output_pic) {
986 if (h->next_output_pic->recovered) {
987 // We have reached an recovery point and all frames after it in
988 // display order are "recovered".
989 h->frame_recovered |= FRAME_RECOVERED_SEI;
991 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
994 if (setup_finished && !h->avctx->hwaccel) {
995 ff_thread_finish_setup(h->avctx);
997 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
998 h->setup_finished = 1;
1002 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
1005 int luma_def, chroma_def;
1008 sl->use_weight_chroma = 0;
1009 sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
1010 if (h->sps.chroma_format_idc)
1011 sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
1013 if (sl->luma_log2_weight_denom > 7U) {
1014 av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
1015 sl->luma_log2_weight_denom = 0;
1017 if (sl->chroma_log2_weight_denom > 7U) {
1018 av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
1019 sl->chroma_log2_weight_denom = 0;
1022 luma_def = 1 << sl->luma_log2_weight_denom;
1023 chroma_def = 1 << sl->chroma_log2_weight_denom;
1025 for (list = 0; list < 2; list++) {
1026 sl->luma_weight_flag[list] = 0;
1027 sl->chroma_weight_flag[list] = 0;
1028 for (i = 0; i < sl->ref_count[list]; i++) {
1029 int luma_weight_flag, chroma_weight_flag;
1031 luma_weight_flag = get_bits1(&sl->gb);
1032 if (luma_weight_flag) {
1033 sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
1034 sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
1035 if (sl->luma_weight[i][list][0] != luma_def ||
1036 sl->luma_weight[i][list][1] != 0) {
1038 sl->luma_weight_flag[list] = 1;
1041 sl->luma_weight[i][list][0] = luma_def;
1042 sl->luma_weight[i][list][1] = 0;
1045 if (h->sps.chroma_format_idc) {
1046 chroma_weight_flag = get_bits1(&sl->gb);
1047 if (chroma_weight_flag) {
1049 for (j = 0; j < 2; j++) {
1050 sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
1051 sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
1052 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1053 sl->chroma_weight[i][list][j][1] != 0) {
1054 sl->use_weight_chroma = 1;
1055 sl->chroma_weight_flag[list] = 1;
1060 for (j = 0; j < 2; j++) {
1061 sl->chroma_weight[i][list][j][0] = chroma_def;
1062 sl->chroma_weight[i][list][j][1] = 0;
1067 if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
1070 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1075 * instantaneous decoder refresh.
1077 static void idr(H264Context *h)
1080 ff_h264_remove_all_refs(h);
1082 h->prev_frame_num_offset = 0;
1083 h->prev_poc_msb = 1<<16;
1084 h->prev_poc_lsb = 0;
1085 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1086 h->last_pocs[i] = INT_MIN;
1089 /* forget old pics after a seek */
1090 void ff_h264_flush_change(H264Context *h)
1094 h->next_outputed_poc = INT_MIN;
1095 h->prev_interlaced_frame = 1;
1098 h->prev_frame_num = -1;
1099 if (h->cur_pic_ptr) {
1100 h->cur_pic_ptr->reference = 0;
1101 for (j=i=0; h->delayed_pic[i]; i++)
1102 if (h->delayed_pic[i] != h->cur_pic_ptr)
1103 h->delayed_pic[j++] = h->delayed_pic[i];
1104 h->delayed_pic[j] = NULL;
1106 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1109 ff_h264_reset_sei(h);
1110 h->recovery_frame = -1;
1111 h->frame_recovered = 0;
1112 h->current_slice = 0;
1114 for (i = 0; i < h->nb_slice_ctx; i++)
1115 h->slice_ctx[i].list_count = 0;
1118 /* forget old pics after a seek */
1119 static void flush_dpb(AVCodecContext *avctx)
1121 H264Context *h = avctx->priv_data;
1124 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1126 ff_h264_flush_change(h);
1128 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1129 ff_h264_unref_picture(h, &h->DPB[i]);
1130 h->cur_pic_ptr = NULL;
1131 ff_h264_unref_picture(h, &h->cur_pic);
1135 ff_h264_free_tables(h);
1136 h->context_initialized = 0;
1139 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1141 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1144 h->frame_num_offset = h->prev_frame_num_offset;
1145 if (h->frame_num < h->prev_frame_num)
1146 h->frame_num_offset += max_frame_num;
1148 if (h->sps.poc_type == 0) {
1149 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1151 if (h->poc_lsb < h->prev_poc_lsb &&
1152 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1153 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1154 else if (h->poc_lsb > h->prev_poc_lsb &&
1155 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1156 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1158 h->poc_msb = h->prev_poc_msb;
1160 field_poc[1] = h->poc_msb + h->poc_lsb;
1161 if (h->picture_structure == PICT_FRAME)
1162 field_poc[1] += h->delta_poc_bottom;
1163 } else if (h->sps.poc_type == 1) {
1164 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1167 if (h->sps.poc_cycle_length != 0)
1168 abs_frame_num = h->frame_num_offset + h->frame_num;
1172 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1175 expected_delta_per_poc_cycle = 0;
1176 for (i = 0; i < h->sps.poc_cycle_length; i++)
1177 // FIXME integrate during sps parse
1178 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1180 if (abs_frame_num > 0) {
1181 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1182 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1184 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1185 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1186 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1190 if (h->nal_ref_idc == 0)
1191 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1193 field_poc[0] = expectedpoc + h->delta_poc[0];
1194 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1196 if (h->picture_structure == PICT_FRAME)
1197 field_poc[1] += h->delta_poc[1];
1199 int poc = 2 * (h->frame_num_offset + h->frame_num);
1201 if (!h->nal_ref_idc)
1208 if (h->picture_structure != PICT_BOTTOM_FIELD)
1209 pic_field_poc[0] = field_poc[0];
1210 if (h->picture_structure != PICT_TOP_FIELD)
1211 pic_field_poc[1] = field_poc[1];
1212 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1218 * Compute profile from profile_idc and constraint_set?_flags.
1222 * @return profile as defined by FF_PROFILE_H264_*
1224 int ff_h264_get_profile(SPS *sps)
1226 int profile = sps->profile_idc;
1228 switch (sps->profile_idc) {
1229 case FF_PROFILE_H264_BASELINE:
1230 // constraint_set1_flag set to 1
1231 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1233 case FF_PROFILE_H264_HIGH_10:
1234 case FF_PROFILE_H264_HIGH_422:
1235 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1236 // constraint_set3_flag set to 1
1237 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1244 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1246 int ref_count[2], list_count;
1247 int num_ref_idx_active_override_flag;
1249 // set defaults, might be overridden a few lines later
1250 ref_count[0] = h->pps.ref_count[0];
1251 ref_count[1] = h->pps.ref_count[1];
1253 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1255 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1257 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1258 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1259 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1261 if (num_ref_idx_active_override_flag) {
1262 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1263 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1264 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1266 // full range is spec-ok in this case, even for frames
1270 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1271 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]);
1272 sl->ref_count[0] = sl->ref_count[1] = 0;
1274 return AVERROR_INVALIDDATA;
1277 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1283 ref_count[0] = ref_count[1] = 0;
1286 if (list_count != sl->list_count ||
1287 ref_count[0] != sl->ref_count[0] ||
1288 ref_count[1] != sl->ref_count[1]) {
1289 sl->ref_count[0] = ref_count[0];
1290 sl->ref_count[1] = ref_count[1];
1291 sl->list_count = list_count;
1298 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1300 static int get_bit_length(H264Context *h, const uint8_t *buf,
1301 const uint8_t *ptr, int dst_length,
1302 int i, int next_avc)
1304 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1305 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1306 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1307 h->workaround_bugs |= FF_BUG_TRUNCATED;
1309 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1310 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1316 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1319 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1321 int next_avc = h->is_avc ? 0 : buf_size;
1324 int nals_needed = 0;
1325 int first_slice = 0;
1330 int dst_length, bit_length, consumed;
1333 if (buf_index >= next_avc) {
1334 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1337 next_avc = buf_index + nalsize;
1339 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1340 if (buf_index >= buf_size)
1342 if (buf_index >= next_avc)
1346 ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1347 next_avc - buf_index);
1349 if (!ptr || dst_length < 0)
1350 return AVERROR_INVALIDDATA;
1352 buf_index += consumed;
1354 bit_length = get_bit_length(h, buf, ptr, dst_length,
1355 buf_index, next_avc);
1358 /* packets can sometimes contain multiple PPS/SPS,
1359 * e.g. two PAFF field pictures in one packet, or a demuxer
1360 * which splits NALs strangely if so, when frame threading we
1361 * can't start the next thread until we've read all of them */
1362 switch (h->nal_unit_type) {
1365 nals_needed = nal_index;
1370 init_get_bits(&gb, ptr, bit_length);
1371 if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
1373 first_slice != h->nal_unit_type)
1374 nals_needed = nal_index;
1376 first_slice = h->nal_unit_type;
1383 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1384 int parse_extradata)
1386 AVCodecContext *const avctx = h->avctx;
1387 H264SliceContext *sl;
1389 unsigned context_count;
1391 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1396 h->nal_unit_type= 0;
1398 if(!h->slice_context_count)
1399 h->slice_context_count= 1;
1400 h->max_contexts = h->slice_context_count;
1401 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1402 h->current_slice = 0;
1403 if (!h->first_field)
1404 h->cur_pic_ptr = NULL;
1405 ff_h264_reset_sei(h);
1408 if (h->nal_length_size == 4) {
1409 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1411 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1415 if (avctx->active_thread_type & FF_THREAD_FRAME)
1416 nals_needed = get_last_needed_nal(h, buf, buf_size);
1421 next_avc = h->is_avc ? 0 : buf_size;
1431 if (buf_index >= next_avc) {
1432 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1435 next_avc = buf_index + nalsize;
1437 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1438 if (buf_index >= buf_size)
1440 if (buf_index >= next_avc)
1444 sl = &h->slice_ctx[context_count];
1446 ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1447 &consumed, next_avc - buf_index);
1448 if (!ptr || dst_length < 0) {
1453 bit_length = get_bit_length(h, buf, ptr, dst_length,
1454 buf_index + consumed, next_avc);
1456 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1457 av_log(h->avctx, AV_LOG_DEBUG,
1458 "NAL %d/%d at %d/%d length %d\n",
1459 h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
1461 if (h->is_avc && (nalsize != consumed) && nalsize)
1462 av_log(h->avctx, AV_LOG_DEBUG,
1463 "AVC: Consumed only %d bytes instead of %d\n",
1466 buf_index += consumed;
1469 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1470 h->nal_ref_idc == 0 &&
1471 h->nal_unit_type != NAL_SEI)
1475 /* Ignore per frame NAL unit type during extradata
1476 * parsing. Decoding slices is not possible in codec init
1478 if (parse_extradata) {
1479 switch (h->nal_unit_type) {
1485 av_log(h->avctx, AV_LOG_WARNING,
1486 "Ignoring NAL %d in global header/extradata\n",
1488 // fall through to next case
1489 case NAL_AUXILIARY_SLICE:
1490 h->nal_unit_type = NAL_FF_IGNORE;
1496 switch (h->nal_unit_type) {
1498 if ((ptr[0] & 0xFC) == 0x98) {
1499 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1500 h->next_outputed_poc = INT_MIN;
1504 if (h->nal_unit_type != NAL_IDR_SLICE) {
1505 av_log(h->avctx, AV_LOG_ERROR,
1506 "Invalid mix of idr and non-idr slices\n");
1511 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1512 av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1513 ret = AVERROR_INVALIDDATA;
1516 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1519 h->has_recovery_point = 1;
1521 init_get_bits(&sl->gb, ptr, bit_length);
1523 if ( nals_needed >= nal_index
1524 || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1527 if ((err = ff_h264_decode_slice_header(h, sl)))
1530 if (h->sei_recovery_frame_cnt >= 0) {
1531 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1532 h->valid_recovery_point = 1;
1534 if ( h->recovery_frame < 0
1535 || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1536 h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
1538 if (!h->valid_recovery_point)
1539 h->recovery_frame = h->frame_num;
1543 h->cur_pic_ptr->f->key_frame |=
1544 (h->nal_unit_type == NAL_IDR_SLICE);
1546 if (h->nal_unit_type == NAL_IDR_SLICE ||
1547 h->recovery_frame == h->frame_num) {
1548 h->recovery_frame = -1;
1549 h->cur_pic_ptr->recovered = 1;
1551 // If we have an IDR, all frames after it in decoded order are
1553 if (h->nal_unit_type == NAL_IDR_SLICE)
1554 h->frame_recovered |= FRAME_RECOVERED_IDR;
1556 h->cur_pic_ptr->recovered |= h->frame_recovered;
1558 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1561 if (h->current_slice == 1) {
1562 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1563 decode_postinit(h, nal_index >= nals_needed);
1565 if (h->avctx->hwaccel &&
1566 (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1568 #if FF_API_CAP_VDPAU
1569 if (CONFIG_H264_VDPAU_DECODER &&
1570 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
1571 ff_vdpau_h264_picture_start(h);
1575 if (sl->redundant_pic_count == 0) {
1576 if (avctx->hwaccel) {
1577 ret = avctx->hwaccel->decode_slice(avctx,
1578 &buf[buf_index - consumed],
1582 #if FF_API_CAP_VDPAU
1583 } else if (CONFIG_H264_VDPAU_DECODER &&
1584 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
1585 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1587 sizeof(start_code));
1588 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1589 &buf[buf_index - consumed],
1599 avpriv_request_sample(avctx, "data partitioning");
1602 init_get_bits(&h->gb, ptr, bit_length);
1603 ret = ff_h264_decode_sei(h);
1604 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1608 init_get_bits(&h->gb, ptr, bit_length);
1609 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1611 if (h->is_avc ? nalsize : 1) {
1612 av_log(h->avctx, AV_LOG_DEBUG,
1613 "SPS decoding failure, trying again with the complete NAL\n");
1615 av_assert0(next_avc - buf_index + consumed == nalsize);
1616 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1618 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1619 8*(next_avc - buf_index + consumed - 1));
1620 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1623 init_get_bits(&h->gb, ptr, bit_length);
1624 ff_h264_decode_seq_parameter_set(h, 1);
1628 init_get_bits(&h->gb, ptr, bit_length);
1629 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1630 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1634 case NAL_END_SEQUENCE:
1635 case NAL_END_STREAM:
1636 case NAL_FILLER_DATA:
1638 case NAL_AUXILIARY_SLICE:
1643 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1644 h->nal_unit_type, bit_length);
1647 if (context_count == h->max_contexts) {
1648 ret = ff_h264_execute_decode_slices(h, context_count);
1649 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1654 if (err < 0 || err == SLICE_SKIPED) {
1656 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1657 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1658 } else if (err == SLICE_SINGLETHREAD) {
1659 if (context_count > 1) {
1660 ret = ff_h264_execute_decode_slices(h, context_count - 1);
1661 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1665 /* Slice could not be decoded in parallel mode, restart. Note
1666 * that rbsp_buffer is not transferred, but since we no longer
1667 * run in parallel mode this should not be an issue. */
1668 sl = &h->slice_ctx[0];
1673 if (context_count) {
1674 ret = ff_h264_execute_decode_slices(h, context_count);
1675 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1682 #if CONFIG_ERROR_RESILIENCE
1685 * FIXME: Error handling code does not seem to support interlaced
1686 * when slices span multiple rows
1687 * The ff_er_add_slice calls don't work right for bottom
1688 * fields; they cause massive erroneous error concealing
1689 * Error marking covers both fields (top and bottom).
1690 * This causes a mismatched s->error_count
1691 * and a bad error table. Further, the error count goes to
1692 * INT_MAX when called for bottom field, because mb_y is
1693 * past end by one (callers fault) and resync_mb_y != 0
1694 * causes problems for the first MB line, too.
1696 if (!FIELD_PICTURE(h) && h->current_slice && !h->sps.new && h->enable_er) {
1697 int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
1699 ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
1702 ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
1703 sl->ref_list[0][0].parent = &h->last_pic_for_ec;
1704 memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
1705 memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
1706 sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
1707 } else if (sl->ref_count[0]) {
1708 ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
1710 ff_h264_set_erpic(&sl->er.last_pic, NULL);
1712 if (sl->ref_count[1])
1713 ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
1715 sl->er.ref_count = sl->ref_count[0];
1717 ff_er_frame_end(&sl->er);
1719 memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
1721 #endif /* CONFIG_ERROR_RESILIENCE */
1723 if (h->cur_pic_ptr && !h->droppable) {
1724 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1725 h->picture_structure == PICT_BOTTOM_FIELD);
1728 return (ret < 0) ? ret : buf_index;
1732 * Return the number of bytes consumed for building the current frame.
1734 static int get_consumed_bytes(int pos, int buf_size)
1737 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1738 if (pos + 10 > buf_size)
1739 pos = buf_size; // oops ;)
1744 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1746 AVFrame *src = srcp->f;
1747 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1749 int ret = av_frame_ref(dst, src);
1753 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1755 h->backup_width = h->avctx->width;
1756 h->backup_height = h->avctx->height;
1757 h->backup_pix_fmt = h->avctx->pix_fmt;
1759 h->avctx->width = dst->width;
1760 h->avctx->height = dst->height;
1761 h->avctx->pix_fmt = dst->format;
1763 if (srcp->sei_recovery_frame_cnt == 0)
1768 for (i = 0; i < desc->nb_components; i++) {
1769 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1770 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1771 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1772 (srcp->crop_top >> vshift) * dst->linesize[i];
1773 dst->data[i] += off;
1778 static int is_extra(const uint8_t *buf, int buf_size)
1780 int cnt= buf[5]&0x1f;
1781 const uint8_t *p= buf+6;
1783 int nalsize= AV_RB16(p) + 2;
1784 if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
1792 int nalsize= AV_RB16(p) + 2;
1793 if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
1800 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1801 int *got_frame, AVPacket *avpkt)
1803 const uint8_t *buf = avpkt->data;
1804 int buf_size = avpkt->size;
1805 H264Context *h = avctx->priv_data;
1806 AVFrame *pict = data;
1812 h->flags = avctx->flags;
1813 h->setup_finished = 0;
1815 if (h->backup_width != -1) {
1816 avctx->width = h->backup_width;
1817 h->backup_width = -1;
1819 if (h->backup_height != -1) {
1820 avctx->height = h->backup_height;
1821 h->backup_height = -1;
1823 if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
1824 avctx->pix_fmt = h->backup_pix_fmt;
1825 h->backup_pix_fmt = AV_PIX_FMT_NONE;
1828 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1830 /* end of stream, output what is still in the buffers */
1831 if (buf_size == 0) {
1834 h->cur_pic_ptr = NULL;
1837 // FIXME factorize this with the output code below
1838 out = h->delayed_pic[0];
1841 h->delayed_pic[i] &&
1842 !h->delayed_pic[i]->f->key_frame &&
1843 !h->delayed_pic[i]->mmco_reset;
1845 if (h->delayed_pic[i]->poc < out->poc) {
1846 out = h->delayed_pic[i];
1850 for (i = out_idx; h->delayed_pic[i]; i++)
1851 h->delayed_pic[i] = h->delayed_pic[i + 1];
1854 out->reference &= ~DELAYED_PIC_REF;
1855 ret = output_frame(h, pict, out);
1863 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1865 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1866 if (is_extra(side, side_size))
1867 ff_h264_decode_extradata(h, side, side_size);
1869 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1870 if (is_extra(buf, buf_size))
1871 return ff_h264_decode_extradata(h, buf, buf_size);
1874 buf_index = decode_nal_units(h, buf, buf_size, 0);
1876 return AVERROR_INVALIDDATA;
1878 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1879 av_assert0(buf_index <= buf_size);
1883 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1884 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1885 buf_size >= 4 && !memcmp("Q264", buf, 4))
1887 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1888 return AVERROR_INVALIDDATA;
1891 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1892 (h->mb_y >= h->mb_height && h->mb_height)) {
1893 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1894 decode_postinit(h, 1);
1896 if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
1899 /* Wait for second field. */
1901 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1902 (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
1903 h->next_output_pic->recovered)) {
1904 if (!h->next_output_pic->recovered)
1905 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1907 if (!h->avctx->hwaccel &&
1908 (h->next_output_pic->field_poc[0] == INT_MAX ||
1909 h->next_output_pic->field_poc[1] == INT_MAX)
1912 AVFrame *f = h->next_output_pic->f;
1913 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1914 uint8_t *dst_data[4];
1916 const uint8_t *src_data[4];
1918 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1920 for (p = 0; p<4; p++) {
1921 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1922 src_data[p] = f->data[p] + field *f->linesize[p];
1923 linesizes[p] = 2*f->linesize[p];
1926 av_image_copy(dst_data, linesizes, src_data, linesizes,
1927 f->format, f->width, f->height>>1);
1930 ret = output_frame(h, pict, h->next_output_pic);
1934 if (CONFIG_MPEGVIDEO) {
1935 ff_print_debug_info2(h->avctx, pict, NULL,
1936 h->next_output_pic->mb_type,
1937 h->next_output_pic->qscale_table,
1938 h->next_output_pic->motion_val,
1940 h->mb_width, h->mb_height, h->mb_stride, 1);
1945 av_assert0(pict->buf[0] || !*got_frame);
1947 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1949 return get_consumed_bytes(buf_index, buf_size);
1952 av_cold void ff_h264_free_context(H264Context *h)
1956 ff_h264_free_tables(h);
1958 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1959 ff_h264_unref_picture(h, &h->DPB[i]);
1960 av_frame_free(&h->DPB[i].f);
1962 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1964 h->cur_pic_ptr = NULL;
1966 for (i = 0; i < h->nb_slice_ctx; i++)
1967 av_freep(&h->slice_ctx[i].rbsp_buffer);
1968 av_freep(&h->slice_ctx);
1969 h->nb_slice_ctx = 0;
1971 h->a53_caption_size = 0;
1972 av_freep(&h->a53_caption);
1974 for (i = 0; i < MAX_SPS_COUNT; i++)
1975 av_freep(h->sps_buffers + i);
1977 for (i = 0; i < MAX_PPS_COUNT; i++)
1978 av_freep(h->pps_buffers + i);
1981 static av_cold int h264_decode_end(AVCodecContext *avctx)
1983 H264Context *h = avctx->priv_data;
1985 ff_h264_remove_all_refs(h);
1986 ff_h264_free_context(h);
1988 ff_h264_unref_picture(h, &h->cur_pic);
1989 av_frame_free(&h->cur_pic.f);
1990 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1991 av_frame_free(&h->last_pic_for_ec.f);
1996 #define OFFSET(x) offsetof(H264Context, x)
1997 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1998 static const AVOption h264_options[] = {
1999 {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
2000 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
2001 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
2005 static const AVClass h264_class = {
2006 .class_name = "H264 Decoder",
2007 .item_name = av_default_item_name,
2008 .option = h264_options,
2009 .version = LIBAVUTIL_VERSION_INT,
2012 AVCodec ff_h264_decoder = {
2014 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
2015 .type = AVMEDIA_TYPE_VIDEO,
2016 .id = AV_CODEC_ID_H264,
2017 .priv_data_size = sizeof(H264Context),
2018 .init = ff_h264_decode_init,
2019 .close = h264_decode_end,
2020 .decode = h264_decode_frame,
2021 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
2022 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
2023 AV_CODEC_CAP_FRAME_THREADS,
2024 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
2026 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
2027 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
2028 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
2029 .priv_class = &h264_class,
2032 #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
2033 static const AVClass h264_vdpau_class = {
2034 .class_name = "H264 VDPAU Decoder",
2035 .item_name = av_default_item_name,
2036 .option = h264_options,
2037 .version = LIBAVUTIL_VERSION_INT,
2040 AVCodec ff_h264_vdpau_decoder = {
2041 .name = "h264_vdpau",
2042 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
2043 .type = AVMEDIA_TYPE_VIDEO,
2044 .id = AV_CODEC_ID_H264,
2045 .priv_data_size = sizeof(H264Context),
2046 .init = ff_h264_decode_init,
2047 .close = h264_decode_end,
2048 .decode = h264_decode_frame,
2049 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
2051 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2053 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
2054 .priv_class = &h264_vdpau_class,