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"
49 #include "rectangle.h"
52 #include "vdpau_internal.h"
54 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
58 H264Context *h = avctx->priv_data;
59 return h ? h->sps.num_reorder_frames : 0;
62 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
64 int mb_x, int mb_y, int mb_intra, int mb_skipped)
66 H264Context *h = opaque;
67 H264SliceContext *sl = &h->slice_ctx[0];
71 sl->mb_xy = mb_x + mb_y * h->mb_stride;
72 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
74 /* FIXME: It is possible albeit uncommon that slice references
75 * differ between slices. We take the easy approach and ignore
76 * it for now. If this turns out to have any relevance in
77 * practice then correct remapping should be added. */
78 if (ref >= sl->ref_count[0])
80 if (!sl->ref_list[0][ref].data[0]) {
81 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
84 if ((sl->ref_list[0][ref].reference&3) != 3) {
85 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
88 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
90 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
91 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
92 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
94 sl->mb_field_decoding_flag = 0;
95 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
98 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
101 AVCodecContext *avctx = h->avctx;
102 const AVFrame *src = &h->cur_pic.f;
103 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
104 int vshift = desc->log2_chroma_h;
105 const int field_pic = h->picture_structure != PICT_FRAME;
111 height = FFMIN(height, avctx->height - y);
113 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
116 if (avctx->draw_horiz_band) {
117 int offset[AV_NUM_DATA_POINTERS];
120 offset[0] = y * src->linesize[0];
122 offset[2] = (y >> vshift) * src->linesize[1];
123 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
128 avctx->draw_horiz_band(avctx, src, offset,
129 y, h->picture_structure, height);
134 * Check if the top & left blocks are available if needed and
135 * change the dc mode so it only uses the available blocks.
137 int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
139 static const int8_t top[12] = {
140 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
142 static const int8_t left[12] = {
143 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
147 if (!(sl->top_samples_available & 0x8000)) {
148 for (i = 0; i < 4; i++) {
149 int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
151 av_log(h->avctx, AV_LOG_ERROR,
152 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
153 status, sl->mb_x, sl->mb_y);
154 return AVERROR_INVALIDDATA;
156 sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
161 if ((sl->left_samples_available & 0x8888) != 0x8888) {
162 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
163 for (i = 0; i < 4; i++)
164 if (!(sl->left_samples_available & mask[i])) {
165 int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
167 av_log(h->avctx, AV_LOG_ERROR,
168 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
169 status, sl->mb_x, sl->mb_y);
170 return AVERROR_INVALIDDATA;
172 sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
178 } // FIXME cleanup like ff_h264_check_intra_pred_mode
181 * Check if the top & left blocks are available if needed and
182 * change the dc mode so it only uses the available blocks.
184 int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
185 int mode, int is_chroma)
187 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
188 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
191 av_log(h->avctx, AV_LOG_ERROR,
192 "out of range intra chroma pred mode at %d %d\n",
194 return AVERROR_INVALIDDATA;
197 if (!(sl->top_samples_available & 0x8000)) {
200 av_log(h->avctx, AV_LOG_ERROR,
201 "top block unavailable for requested intra mode at %d %d\n",
203 return AVERROR_INVALIDDATA;
207 if ((sl->left_samples_available & 0x8080) != 0x8080) {
210 av_log(h->avctx, AV_LOG_ERROR,
211 "left block unavailable for requested intra mode at %d %d\n",
213 return AVERROR_INVALIDDATA;
215 if (is_chroma && (sl->left_samples_available & 0x8080)) {
216 // mad cow disease mode, aka MBAFF + constrained_intra_pred
217 mode = ALZHEIMER_DC_L0T_PRED8x8 +
218 (!(sl->left_samples_available & 0x8000)) +
219 2 * (mode == DC_128_PRED8x8);
226 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
228 int *dst_length, int *consumed, int length)
233 // src[0]&0x80; // forbidden bit
234 h->nal_ref_idc = src[0] >> 5;
235 h->nal_unit_type = src[0] & 0x1F;
240 #define STARTCODE_TEST \
241 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
242 if (src[i + 2] != 3 && src[i + 2] != 0) { \
243 /* startcode, so we must be past the end */ \
249 #if HAVE_FAST_UNALIGNED
250 #define FIND_FIRST_ZERO \
251 if (i > 0 && !src[i]) \
257 for (i = 0; i + 1 < length; i += 9) {
258 if (!((~AV_RN64A(src + i) &
259 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
260 0x8000800080008080ULL))
267 for (i = 0; i + 1 < length; i += 5) {
268 if (!((~AV_RN32A(src + i) &
269 (AV_RN32A(src + i) - 0x01000101U)) &
278 for (i = 0; i + 1 < length; i += 2) {
281 if (i > 0 && src[i - 1] == 0)
287 av_fast_padded_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size, length+MAX_MBPAIR_SIZE);
288 dst = sl->rbsp_buffer;
293 if(i>=length-1){ //no escaped 0
295 *consumed= length+1; //+1 for the header
296 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
299 memcpy(dst, src, length);
306 while (si + 2 < length) {
307 // remove escapes (very rare 1:2^22)
308 if (src[si + 2] > 3) {
309 dst[di++] = src[si++];
310 dst[di++] = src[si++];
311 } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {
312 if (src[si + 2] == 3) { // escape
317 } else // next start code
321 dst[di++] = src[si++];
324 dst[di++] = src[si++];
327 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
330 *consumed = si + 1; // +1 for the header
331 /* FIXME store exact number of bits in the getbitcontext
332 * (it is needed for decoding) */
337 * Identify the exact end of the bitstream
338 * @return the length of the trailing, or 0 if damaged
340 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
345 ff_tlog(h->avctx, "rbsp trailing %X\n", v);
347 for (r = 1; r < 9; r++) {
355 void ff_h264_free_tables(H264Context *h, int free_rbsp)
359 av_freep(&h->intra4x4_pred_mode);
360 av_freep(&h->chroma_pred_mode_table);
361 av_freep(&h->cbp_table);
362 av_freep(&h->mvd_table[0]);
363 av_freep(&h->mvd_table[1]);
364 av_freep(&h->direct_table);
365 av_freep(&h->non_zero_count);
366 av_freep(&h->slice_table_base);
367 h->slice_table = NULL;
368 av_freep(&h->list_counts);
370 av_freep(&h->mb2b_xy);
371 av_freep(&h->mb2br_xy);
373 av_buffer_pool_uninit(&h->qscale_table_pool);
374 av_buffer_pool_uninit(&h->mb_type_pool);
375 av_buffer_pool_uninit(&h->motion_val_pool);
376 av_buffer_pool_uninit(&h->ref_index_pool);
378 if (free_rbsp && h->DPB) {
379 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
380 ff_h264_unref_picture(h, &h->DPB[i]);
381 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
384 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
385 h->DPB[i].needs_realloc = 1;
388 h->cur_pic_ptr = NULL;
390 for (i = 0; i < h->nb_slice_ctx; i++) {
391 H264SliceContext *sl = &h->slice_ctx[i];
393 av_freep(&sl->dc_val_base);
394 av_freep(&sl->er.mb_index2xy);
395 av_freep(&sl->er.error_status_table);
396 av_freep(&sl->er.er_temp_buffer);
398 av_freep(&sl->bipred_scratchpad);
399 av_freep(&sl->edge_emu_buffer);
400 av_freep(&sl->top_borders[0]);
401 av_freep(&sl->top_borders[1]);
403 sl->bipred_scratchpad_allocated = 0;
404 sl->edge_emu_buffer_allocated = 0;
405 sl->top_borders_allocated[0] = 0;
406 sl->top_borders_allocated[1] = 0;
409 av_freep(&sl->rbsp_buffer);
410 sl->rbsp_buffer_size = 0;
415 int ff_h264_alloc_tables(H264Context *h)
417 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
418 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
421 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
422 row_mb_num, 8 * sizeof(uint8_t), fail)
423 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
425 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
426 big_mb_num * 48 * sizeof(uint8_t), fail)
427 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
428 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
429 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
430 big_mb_num * sizeof(uint16_t), fail)
431 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
432 big_mb_num * sizeof(uint8_t), fail)
433 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
434 row_mb_num, 16 * sizeof(uint8_t), fail);
435 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
436 row_mb_num, 16 * sizeof(uint8_t), fail);
437 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
438 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
440 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
441 4 * big_mb_num * sizeof(uint8_t), fail);
442 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
443 big_mb_num * sizeof(uint8_t), fail)
445 memset(h->slice_table_base, -1,
446 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
447 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
449 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
450 big_mb_num * sizeof(uint32_t), fail);
451 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
452 big_mb_num * sizeof(uint32_t), fail);
453 for (y = 0; y < h->mb_height; y++)
454 for (x = 0; x < h->mb_width; x++) {
455 const int mb_xy = x + y * h->mb_stride;
456 const int b_xy = 4 * x + 4 * y * h->b_stride;
458 h->mb2b_xy[mb_xy] = b_xy;
459 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
462 if (!h->dequant4_coeff[0])
463 ff_h264_init_dequant_tables(h);
466 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
469 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
470 av_frame_unref(&h->DPB[i].f);
471 av_frame_unref(&h->cur_pic.f);
477 ff_h264_free_tables(h, 1);
478 return AVERROR(ENOMEM);
483 * Allocate buffers which are not shared amongst multiple threads.
485 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
487 ERContext *er = &sl->er;
488 int mb_array_size = h->mb_height * h->mb_stride;
489 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
490 int c_size = h->mb_stride * (h->mb_height + 1);
491 int yc_size = y_size + 2 * c_size;
494 sl->ref_cache[0][scan8[5] + 1] =
495 sl->ref_cache[0][scan8[7] + 1] =
496 sl->ref_cache[0][scan8[13] + 1] =
497 sl->ref_cache[1][scan8[5] + 1] =
498 sl->ref_cache[1][scan8[7] + 1] =
499 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
501 if (sl != h->slice_ctx) {
502 memset(er, 0, sizeof(*er));
504 if (CONFIG_ERROR_RESILIENCE) {
507 er->avctx = h->avctx;
508 er->decode_mb = h264_er_decode_mb;
510 er->quarter_sample = 1;
512 er->mb_num = h->mb_num;
513 er->mb_width = h->mb_width;
514 er->mb_height = h->mb_height;
515 er->mb_stride = h->mb_stride;
516 er->b8_stride = h->mb_width * 2 + 1;
518 // error resilience code looks cleaner with this
519 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
520 (h->mb_num + 1) * sizeof(int), fail);
522 for (y = 0; y < h->mb_height; y++)
523 for (x = 0; x < h->mb_width; x++)
524 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
526 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
527 h->mb_stride + h->mb_width;
529 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
530 mb_array_size * sizeof(uint8_t), fail);
532 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
533 h->mb_height * h->mb_stride, fail);
535 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
536 yc_size * sizeof(int16_t), fail);
537 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
538 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
539 er->dc_val[2] = er->dc_val[1] + c_size;
540 for (i = 0; i < yc_size; i++)
541 sl->dc_val_base[i] = 1024;
547 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
550 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
551 int parse_extradata);
553 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
555 AVCodecContext *avctx = h->avctx;
558 if (!buf || size <= 0)
563 const unsigned char *p = buf;
568 av_log(avctx, AV_LOG_ERROR,
569 "avcC %d too short\n", size);
570 return AVERROR_INVALIDDATA;
572 /* sps and pps in the avcC always have length coded with 2 bytes,
573 * so put a fake nal_length_size = 2 while parsing them */
574 h->nal_length_size = 2;
575 // Decode sps from avcC
576 cnt = *(p + 5) & 0x1f; // Number of sps
578 for (i = 0; i < cnt; i++) {
579 nalsize = AV_RB16(p) + 2;
580 if(nalsize > size - (p-buf))
581 return AVERROR_INVALIDDATA;
582 ret = decode_nal_units(h, p, nalsize, 1);
584 av_log(avctx, AV_LOG_ERROR,
585 "Decoding sps %d from avcC failed\n", i);
590 // Decode pps from avcC
591 cnt = *(p++); // Number of pps
592 for (i = 0; i < cnt; i++) {
593 nalsize = AV_RB16(p) + 2;
594 if(nalsize > size - (p-buf))
595 return AVERROR_INVALIDDATA;
596 ret = decode_nal_units(h, p, nalsize, 1);
598 av_log(avctx, AV_LOG_ERROR,
599 "Decoding pps %d from avcC failed\n", i);
604 // Store right nal length size that will be used to parse all other nals
605 h->nal_length_size = (buf[4] & 0x03) + 1;
608 ret = decode_nal_units(h, buf, size, 1);
615 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
620 h->dequant_coeff_pps = -1;
621 h->current_sps_id = -1;
622 h->cur_chroma_format_idc = -1;
624 h->picture_structure = PICT_FRAME;
625 h->slice_context_count = 1;
626 h->workaround_bugs = avctx->workaround_bugs;
627 h->flags = avctx->flags;
628 h->prev_poc_msb = 1 << 16;
630 h->recovery_frame = -1;
631 h->frame_recovered = 0;
632 h->prev_frame_num = -1;
633 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
635 h->outputed_poc = h->next_outputed_poc = INT_MIN;
636 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
637 h->last_pocs[i] = INT_MIN;
639 ff_h264_reset_sei(h);
641 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
643 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
644 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
647 return AVERROR(ENOMEM);
650 for (i = 0; i < h->nb_slice_ctx; i++)
651 h->slice_ctx[i].h264 = h;
656 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
658 H264Context *h = avctx->priv_data;
661 ret = h264_init_context(avctx, h);
666 if (!avctx->has_b_frames)
669 ff_h264_decode_init_vlc();
671 ff_init_cabac_states();
673 if (avctx->codec_id == AV_CODEC_ID_H264) {
674 if (avctx->ticks_per_frame == 1) {
675 if(h->avctx->time_base.den < INT_MAX/2) {
676 h->avctx->time_base.den *= 2;
678 h->avctx->time_base.num /= 2;
680 avctx->ticks_per_frame = 2;
683 if (avctx->extradata_size > 0 && avctx->extradata) {
684 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
686 ff_h264_free_context(h);
691 if (h->sps.bitstream_restriction_flag &&
692 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
693 h->avctx->has_b_frames = h->sps.num_reorder_frames;
697 avctx->internal->allocate_progress = 1;
699 ff_h264_flush_change(h);
701 if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
704 if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
705 av_log(avctx, AV_LOG_WARNING,
706 "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
707 "Use it at your own risk\n");
713 static int decode_init_thread_copy(AVCodecContext *avctx)
715 H264Context *h = avctx->priv_data;
718 if (!avctx->internal->is_copy)
721 memset(h, 0, sizeof(*h));
723 ret = h264_init_context(avctx, h);
727 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 (cur->f.interlaced_frame || 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;
824 /* Most likely progressive */
825 cur->f.top_field_first = 0;
829 if (h->sei_frame_packing_present &&
830 h->frame_packing_arrangement_type >= 0 &&
831 h->frame_packing_arrangement_type <= 6 &&
832 h->content_interpretation_type > 0 &&
833 h->content_interpretation_type < 3) {
834 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
836 switch (h->frame_packing_arrangement_type) {
838 stereo->type = AV_STEREO3D_CHECKERBOARD;
841 stereo->type = AV_STEREO3D_COLUMNS;
844 stereo->type = AV_STEREO3D_LINES;
847 if (h->quincunx_subsampling)
848 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
850 stereo->type = AV_STEREO3D_SIDEBYSIDE;
853 stereo->type = AV_STEREO3D_TOPBOTTOM;
856 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
859 stereo->type = AV_STEREO3D_2D;
863 if (h->content_interpretation_type == 2)
864 stereo->flags = AV_STEREO3D_FLAG_INVERT;
868 if (h->sei_display_orientation_present &&
869 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
870 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
871 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
872 AV_FRAME_DATA_DISPLAYMATRIX,
873 sizeof(int32_t) * 9);
875 av_display_rotation_set((int32_t *)rotation->data, angle);
876 av_display_matrix_flip((int32_t *)rotation->data,
877 h->sei_hflip, h->sei_vflip);
881 cur->mmco_reset = h->mmco_reset;
884 // FIXME do something with unavailable reference frames
886 /* Sort B-frames into display order */
888 if (h->sps.bitstream_restriction_flag &&
889 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
890 h->avctx->has_b_frames = h->sps.num_reorder_frames;
894 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
895 !h->sps.bitstream_restriction_flag) {
896 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
900 for (i = 0; 1; i++) {
901 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
903 h->last_pocs[i-1] = cur->poc;
906 h->last_pocs[i-1]= h->last_pocs[i];
909 out_of_order = MAX_DELAYED_PIC_COUNT - i;
910 if( cur->f.pict_type == AV_PICTURE_TYPE_B
911 || (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))
912 out_of_order = FFMAX(out_of_order, 1);
913 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
914 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
915 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
916 h->last_pocs[i] = INT_MIN;
917 h->last_pocs[0] = cur->poc;
919 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
920 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
921 h->avctx->has_b_frames = out_of_order;
926 while (h->delayed_pic[pics])
929 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
931 h->delayed_pic[pics++] = cur;
932 if (cur->reference == 0)
933 cur->reference = DELAYED_PIC_REF;
935 out = h->delayed_pic[0];
937 for (i = 1; h->delayed_pic[i] &&
938 !h->delayed_pic[i]->f.key_frame &&
939 !h->delayed_pic[i]->mmco_reset;
941 if (h->delayed_pic[i]->poc < out->poc) {
942 out = h->delayed_pic[i];
945 if (h->avctx->has_b_frames == 0 &&
946 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
947 h->next_outputed_poc = INT_MIN;
948 out_of_order = out->poc < h->next_outputed_poc;
950 if (out_of_order || pics > h->avctx->has_b_frames) {
951 out->reference &= ~DELAYED_PIC_REF;
952 // for frame threading, the owner must be the second field's thread or
953 // else the first thread can release the picture and reuse it unsafely
954 for (i = out_idx; h->delayed_pic[i]; i++)
955 h->delayed_pic[i] = h->delayed_pic[i + 1];
957 if (!out_of_order && pics > h->avctx->has_b_frames) {
958 h->next_output_pic = out;
959 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
960 h->next_outputed_poc = INT_MIN;
962 h->next_outputed_poc = out->poc;
964 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
967 if (h->next_output_pic) {
968 if (h->next_output_pic->recovered) {
969 // We have reached an recovery point and all frames after it in
970 // display order are "recovered".
971 h->frame_recovered |= FRAME_RECOVERED_SEI;
973 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
976 if (setup_finished && !h->avctx->hwaccel)
977 ff_thread_finish_setup(h->avctx);
980 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
983 int luma_def, chroma_def;
986 sl->use_weight_chroma = 0;
987 sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
988 if (h->sps.chroma_format_idc)
989 sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
991 if (sl->luma_log2_weight_denom > 7U) {
992 av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
993 sl->luma_log2_weight_denom = 0;
995 if (sl->chroma_log2_weight_denom > 7U) {
996 av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
997 sl->chroma_log2_weight_denom = 0;
1000 luma_def = 1 << sl->luma_log2_weight_denom;
1001 chroma_def = 1 << sl->chroma_log2_weight_denom;
1003 for (list = 0; list < 2; list++) {
1004 sl->luma_weight_flag[list] = 0;
1005 sl->chroma_weight_flag[list] = 0;
1006 for (i = 0; i < sl->ref_count[list]; i++) {
1007 int luma_weight_flag, chroma_weight_flag;
1009 luma_weight_flag = get_bits1(&sl->gb);
1010 if (luma_weight_flag) {
1011 sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
1012 sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
1013 if (sl->luma_weight[i][list][0] != luma_def ||
1014 sl->luma_weight[i][list][1] != 0) {
1016 sl->luma_weight_flag[list] = 1;
1019 sl->luma_weight[i][list][0] = luma_def;
1020 sl->luma_weight[i][list][1] = 0;
1023 if (h->sps.chroma_format_idc) {
1024 chroma_weight_flag = get_bits1(&sl->gb);
1025 if (chroma_weight_flag) {
1027 for (j = 0; j < 2; j++) {
1028 sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
1029 sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
1030 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1031 sl->chroma_weight[i][list][j][1] != 0) {
1032 sl->use_weight_chroma = 1;
1033 sl->chroma_weight_flag[list] = 1;
1038 for (j = 0; j < 2; j++) {
1039 sl->chroma_weight[i][list][j][0] = chroma_def;
1040 sl->chroma_weight[i][list][j][1] = 0;
1045 if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
1048 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1053 * instantaneous decoder refresh.
1055 static void idr(H264Context *h)
1058 ff_h264_remove_all_refs(h);
1060 h->prev_frame_num_offset = 0;
1061 h->prev_poc_msb = 1<<16;
1062 h->prev_poc_lsb = 0;
1063 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1064 h->last_pocs[i] = INT_MIN;
1067 /* forget old pics after a seek */
1068 void ff_h264_flush_change(H264Context *h)
1072 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1073 h->prev_interlaced_frame = 1;
1076 h->prev_frame_num = -1;
1077 if (h->cur_pic_ptr) {
1078 h->cur_pic_ptr->reference = 0;
1079 for (j=i=0; h->delayed_pic[i]; i++)
1080 if (h->delayed_pic[i] != h->cur_pic_ptr)
1081 h->delayed_pic[j++] = h->delayed_pic[i];
1082 h->delayed_pic[j] = NULL;
1084 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1087 ff_h264_reset_sei(h);
1088 h->recovery_frame = -1;
1089 h->frame_recovered = 0;
1090 h->current_slice = 0;
1092 for (i = 0; i < h->nb_slice_ctx; i++)
1093 h->slice_ctx[i].list_count = 0;
1096 /* forget old pics after a seek */
1097 static void flush_dpb(AVCodecContext *avctx)
1099 H264Context *h = avctx->priv_data;
1102 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1104 ff_h264_flush_change(h);
1107 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1108 ff_h264_unref_picture(h, &h->DPB[i]);
1109 h->cur_pic_ptr = NULL;
1110 ff_h264_unref_picture(h, &h->cur_pic);
1114 ff_h264_free_tables(h, 1);
1115 h->context_initialized = 0;
1118 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1120 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1123 h->frame_num_offset = h->prev_frame_num_offset;
1124 if (h->frame_num < h->prev_frame_num)
1125 h->frame_num_offset += max_frame_num;
1127 if (h->sps.poc_type == 0) {
1128 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1130 if (h->poc_lsb < h->prev_poc_lsb &&
1131 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1132 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1133 else if (h->poc_lsb > h->prev_poc_lsb &&
1134 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1135 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1137 h->poc_msb = h->prev_poc_msb;
1139 field_poc[1] = h->poc_msb + h->poc_lsb;
1140 if (h->picture_structure == PICT_FRAME)
1141 field_poc[1] += h->delta_poc_bottom;
1142 } else if (h->sps.poc_type == 1) {
1143 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1146 if (h->sps.poc_cycle_length != 0)
1147 abs_frame_num = h->frame_num_offset + h->frame_num;
1151 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1154 expected_delta_per_poc_cycle = 0;
1155 for (i = 0; i < h->sps.poc_cycle_length; i++)
1156 // FIXME integrate during sps parse
1157 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1159 if (abs_frame_num > 0) {
1160 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1161 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1163 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1164 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1165 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1169 if (h->nal_ref_idc == 0)
1170 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1172 field_poc[0] = expectedpoc + h->delta_poc[0];
1173 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1175 if (h->picture_structure == PICT_FRAME)
1176 field_poc[1] += h->delta_poc[1];
1178 int poc = 2 * (h->frame_num_offset + h->frame_num);
1180 if (!h->nal_ref_idc)
1187 if (h->picture_structure != PICT_BOTTOM_FIELD)
1188 pic_field_poc[0] = field_poc[0];
1189 if (h->picture_structure != PICT_TOP_FIELD)
1190 pic_field_poc[1] = field_poc[1];
1191 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1197 * Compute profile from profile_idc and constraint_set?_flags.
1201 * @return profile as defined by FF_PROFILE_H264_*
1203 int ff_h264_get_profile(SPS *sps)
1205 int profile = sps->profile_idc;
1207 switch (sps->profile_idc) {
1208 case FF_PROFILE_H264_BASELINE:
1209 // constraint_set1_flag set to 1
1210 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1212 case FF_PROFILE_H264_HIGH_10:
1213 case FF_PROFILE_H264_HIGH_422:
1214 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1215 // constraint_set3_flag set to 1
1216 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1223 int ff_h264_set_parameter_from_sps(H264Context *h)
1225 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1226 (h->sps.bitstream_restriction_flag &&
1227 !h->sps.num_reorder_frames)) {
1228 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1229 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1230 "Reenabling low delay requires a codec flush.\n");
1235 if (h->avctx->has_b_frames < 2)
1236 h->avctx->has_b_frames = !h->low_delay;
1238 if (h->cur_bit_depth_luma != h->sps.bit_depth_luma ||
1239 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1240 if (h->avctx->codec &&
1241 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
1242 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
1243 av_log(h->avctx, AV_LOG_ERROR,
1244 "VDPAU decoding does not support video colorspace.\n");
1245 return AVERROR_INVALIDDATA;
1247 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
1248 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
1249 h->cur_bit_depth_luma =
1250 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1251 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1252 h->pixel_shift = h->sps.bit_depth_luma > 8;
1254 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1255 h->sps.chroma_format_idc);
1256 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1257 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1258 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1259 h->sps.chroma_format_idc);
1261 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1263 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1264 h->sps.bit_depth_luma);
1265 return AVERROR_INVALIDDATA;
1271 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1273 int ref_count[2], list_count;
1274 int num_ref_idx_active_override_flag;
1276 // set defaults, might be overridden a few lines later
1277 ref_count[0] = h->pps.ref_count[0];
1278 ref_count[1] = h->pps.ref_count[1];
1280 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1282 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1284 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1285 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1286 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1288 if (num_ref_idx_active_override_flag) {
1289 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1290 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1291 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1293 // full range is spec-ok in this case, even for frames
1297 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1298 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]);
1299 sl->ref_count[0] = sl->ref_count[1] = 0;
1301 return AVERROR_INVALIDDATA;
1304 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1310 ref_count[0] = ref_count[1] = 0;
1313 if (list_count != sl->list_count ||
1314 ref_count[0] != sl->ref_count[0] ||
1315 ref_count[1] != sl->ref_count[1]) {
1316 sl->ref_count[0] = ref_count[0];
1317 sl->ref_count[1] = ref_count[1];
1318 sl->list_count = list_count;
1325 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1327 static int get_bit_length(H264Context *h, const uint8_t *buf,
1328 const uint8_t *ptr, int dst_length,
1329 int i, int next_avc)
1331 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1332 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1333 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1334 h->workaround_bugs |= FF_BUG_TRUNCATED;
1336 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1337 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1343 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1346 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1348 int next_avc = h->is_avc ? 0 : buf_size;
1351 int nals_needed = 0;
1352 int first_slice = 0;
1357 int dst_length, bit_length, consumed;
1360 if (buf_index >= next_avc) {
1361 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1364 next_avc = buf_index + nalsize;
1366 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1367 if (buf_index >= buf_size)
1369 if (buf_index >= next_avc)
1373 ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1374 next_avc - buf_index);
1376 if (!ptr || dst_length < 0)
1377 return AVERROR_INVALIDDATA;
1379 buf_index += consumed;
1381 bit_length = get_bit_length(h, buf, ptr, dst_length,
1382 buf_index, next_avc);
1385 /* packets can sometimes contain multiple PPS/SPS,
1386 * e.g. two PAFF field pictures in one packet, or a demuxer
1387 * which splits NALs strangely if so, when frame threading we
1388 * can't start the next thread until we've read all of them */
1389 switch (h->nal_unit_type) {
1392 nals_needed = nal_index;
1397 init_get_bits(&gb, ptr, bit_length);
1398 if (!get_ue_golomb(&gb) ||
1400 first_slice != h->nal_unit_type)
1401 nals_needed = nal_index;
1403 first_slice = h->nal_unit_type;
1410 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1411 int parse_extradata)
1413 AVCodecContext *const avctx = h->avctx;
1414 H264SliceContext *sl;
1416 unsigned context_count;
1418 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1423 h->nal_unit_type= 0;
1425 if(!h->slice_context_count)
1426 h->slice_context_count= 1;
1427 h->max_contexts = h->slice_context_count;
1428 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1429 h->current_slice = 0;
1430 if (!h->first_field)
1431 h->cur_pic_ptr = NULL;
1432 ff_h264_reset_sei(h);
1435 if (h->nal_length_size == 4) {
1436 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1438 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1442 if (avctx->active_thread_type & FF_THREAD_FRAME)
1443 nals_needed = get_last_needed_nal(h, buf, buf_size);
1448 next_avc = h->is_avc ? 0 : buf_size;
1458 if (buf_index >= next_avc) {
1459 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1462 next_avc = buf_index + nalsize;
1464 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1465 if (buf_index >= buf_size)
1467 if (buf_index >= next_avc)
1471 sl = &h->slice_ctx[context_count];
1473 ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1474 &consumed, next_avc - buf_index);
1475 if (!ptr || dst_length < 0) {
1480 bit_length = get_bit_length(h, buf, ptr, dst_length,
1481 buf_index + consumed, next_avc);
1483 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1484 av_log(h->avctx, AV_LOG_DEBUG,
1485 "NAL %d/%d at %d/%d length %d\n",
1486 h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
1488 if (h->is_avc && (nalsize != consumed) && nalsize)
1489 av_log(h->avctx, AV_LOG_DEBUG,
1490 "AVC: Consumed only %d bytes instead of %d\n",
1493 buf_index += consumed;
1496 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1497 h->nal_ref_idc == 0 &&
1498 h->nal_unit_type != NAL_SEI)
1502 /* Ignore per frame NAL unit type during extradata
1503 * parsing. Decoding slices is not possible in codec init
1505 if (parse_extradata) {
1506 switch (h->nal_unit_type) {
1512 av_log(h->avctx, AV_LOG_WARNING,
1513 "Ignoring NAL %d in global header/extradata\n",
1515 // fall through to next case
1516 case NAL_AUXILIARY_SLICE:
1517 h->nal_unit_type = NAL_FF_IGNORE;
1523 switch (h->nal_unit_type) {
1525 if ((ptr[0] & 0xFC) == 0x98) {
1526 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1527 h->next_outputed_poc = INT_MIN;
1531 if (h->nal_unit_type != NAL_IDR_SLICE) {
1532 av_log(h->avctx, AV_LOG_ERROR,
1533 "Invalid mix of idr and non-idr slices\n");
1538 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1539 av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1540 ret = AVERROR_INVALIDDATA;
1543 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1546 h->has_recovery_point = 1;
1548 init_get_bits(&sl->gb, ptr, bit_length);
1550 if ( nals_needed >= nal_index
1551 || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1554 if ((err = ff_h264_decode_slice_header(h, sl)))
1557 if (h->sei_recovery_frame_cnt >= 0) {
1558 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1559 h->valid_recovery_point = 1;
1561 if ( h->recovery_frame < 0
1562 || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1563 h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
1565 if (!h->valid_recovery_point)
1566 h->recovery_frame = h->frame_num;
1570 h->cur_pic_ptr->f.key_frame |=
1571 (h->nal_unit_type == NAL_IDR_SLICE);
1573 if (h->nal_unit_type == NAL_IDR_SLICE ||
1574 h->recovery_frame == h->frame_num) {
1575 h->recovery_frame = -1;
1576 h->cur_pic_ptr->recovered = 1;
1578 // If we have an IDR, all frames after it in decoded order are
1580 if (h->nal_unit_type == NAL_IDR_SLICE)
1581 h->frame_recovered |= FRAME_RECOVERED_IDR;
1582 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1583 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1585 h->cur_pic_ptr->recovered |= h->frame_recovered;
1587 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1590 if (h->current_slice == 1) {
1591 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1592 decode_postinit(h, nal_index >= nals_needed);
1594 if (h->avctx->hwaccel &&
1595 (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1597 if (CONFIG_H264_VDPAU_DECODER &&
1598 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
1599 ff_vdpau_h264_picture_start(h);
1602 if (sl->redundant_pic_count == 0) {
1603 if (avctx->hwaccel) {
1604 ret = avctx->hwaccel->decode_slice(avctx,
1605 &buf[buf_index - consumed],
1609 } else if (CONFIG_H264_VDPAU_DECODER &&
1610 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
1611 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1613 sizeof(start_code));
1614 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1615 &buf[buf_index - consumed],
1624 avpriv_request_sample(avctx, "data partitioning");
1625 ret = AVERROR(ENOSYS);
1629 init_get_bits(&h->gb, ptr, bit_length);
1630 ret = ff_h264_decode_sei(h);
1631 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1635 init_get_bits(&h->gb, ptr, bit_length);
1636 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1638 if (h->is_avc ? nalsize : 1) {
1639 av_log(h->avctx, AV_LOG_DEBUG,
1640 "SPS decoding failure, trying again with the complete NAL\n");
1642 av_assert0(next_avc - buf_index + consumed == nalsize);
1643 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1645 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1646 8*(next_avc - buf_index + consumed - 1));
1647 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1650 init_get_bits(&h->gb, ptr, bit_length);
1651 ff_h264_decode_seq_parameter_set(h, 1);
1655 init_get_bits(&h->gb, ptr, bit_length);
1656 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1657 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1661 case NAL_END_SEQUENCE:
1662 case NAL_END_STREAM:
1663 case NAL_FILLER_DATA:
1665 case NAL_AUXILIARY_SLICE:
1670 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1671 h->nal_unit_type, bit_length);
1674 if (context_count == h->max_contexts) {
1675 ret = ff_h264_execute_decode_slices(h, context_count);
1676 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1681 if (err < 0 || err == SLICE_SKIPED) {
1683 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1684 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1685 } else if (err == SLICE_SINGLETHREAD) {
1686 if (context_count > 1) {
1687 ret = ff_h264_execute_decode_slices(h, context_count - 1);
1688 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1692 /* Slice could not be decoded in parallel mode, restart. Note
1693 * that rbsp_buffer is not transferred, but since we no longer
1694 * run in parallel mode this should not be an issue. */
1695 sl = &h->slice_ctx[0];
1700 if (context_count) {
1701 ret = ff_h264_execute_decode_slices(h, context_count);
1702 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1709 if (h->cur_pic_ptr && !h->droppable) {
1710 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1711 h->picture_structure == PICT_BOTTOM_FIELD);
1714 return (ret < 0) ? ret : buf_index;
1718 * Return the number of bytes consumed for building the current frame.
1720 static int get_consumed_bytes(int pos, int buf_size)
1723 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1724 if (pos + 10 > buf_size)
1725 pos = buf_size; // oops ;)
1730 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1732 AVFrame *src = &srcp->f;
1733 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1735 int ret = av_frame_ref(dst, src);
1739 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1741 if (srcp->sei_recovery_frame_cnt == 0)
1746 for (i = 0; i < desc->nb_components; i++) {
1747 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1748 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1749 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1750 (srcp->crop_top >> vshift) * dst->linesize[i];
1751 dst->data[i] += off;
1756 static int is_extra(const uint8_t *buf, int buf_size)
1758 int cnt= buf[5]&0x1f;
1759 const uint8_t *p= buf+6;
1761 int nalsize= AV_RB16(p) + 2;
1762 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1770 int nalsize= AV_RB16(p) + 2;
1771 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1778 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1779 int *got_frame, AVPacket *avpkt)
1781 const uint8_t *buf = avpkt->data;
1782 int buf_size = avpkt->size;
1783 H264Context *h = avctx->priv_data;
1784 AVFrame *pict = data;
1790 h->flags = avctx->flags;
1792 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1794 /* end of stream, output what is still in the buffers */
1795 if (buf_size == 0) {
1798 h->cur_pic_ptr = NULL;
1801 // FIXME factorize this with the output code below
1802 out = h->delayed_pic[0];
1805 h->delayed_pic[i] &&
1806 !h->delayed_pic[i]->f.key_frame &&
1807 !h->delayed_pic[i]->mmco_reset;
1809 if (h->delayed_pic[i]->poc < out->poc) {
1810 out = h->delayed_pic[i];
1814 for (i = out_idx; h->delayed_pic[i]; i++)
1815 h->delayed_pic[i] = h->delayed_pic[i + 1];
1818 out->reference &= ~DELAYED_PIC_REF;
1819 ret = output_frame(h, pict, out);
1827 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1829 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1830 if (is_extra(side, side_size))
1831 ff_h264_decode_extradata(h, side, side_size);
1833 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1834 if (is_extra(buf, buf_size))
1835 return ff_h264_decode_extradata(h, buf, buf_size);
1838 buf_index = decode_nal_units(h, buf, buf_size, 0);
1840 return AVERROR_INVALIDDATA;
1842 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1843 av_assert0(buf_index <= buf_size);
1847 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1848 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1849 buf_size >= 4 && !memcmp("Q264", buf, 4))
1851 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1852 return AVERROR_INVALIDDATA;
1855 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1856 (h->mb_y >= h->mb_height && h->mb_height)) {
1857 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1858 decode_postinit(h, 1);
1860 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1862 /* Wait for second field. */
1864 if (h->next_output_pic && (
1865 h->next_output_pic->recovered)) {
1866 if (!h->next_output_pic->recovered)
1867 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1869 if (!h->avctx->hwaccel &&
1870 (h->next_output_pic->field_poc[0] == INT_MAX ||
1871 h->next_output_pic->field_poc[1] == INT_MAX)
1874 AVFrame *f = &h->next_output_pic->f;
1875 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1876 uint8_t *dst_data[4];
1878 const uint8_t *src_data[4];
1880 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1882 for (p = 0; p<4; p++) {
1883 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1884 src_data[p] = f->data[p] + field *f->linesize[p];
1885 linesizes[p] = 2*f->linesize[p];
1888 av_image_copy(dst_data, linesizes, src_data, linesizes,
1889 f->format, f->width, f->height>>1);
1892 ret = output_frame(h, pict, h->next_output_pic);
1896 if (CONFIG_MPEGVIDEO) {
1897 ff_print_debug_info2(h->avctx, pict, NULL,
1898 h->next_output_pic->mb_type,
1899 h->next_output_pic->qscale_table,
1900 h->next_output_pic->motion_val,
1902 h->mb_width, h->mb_height, h->mb_stride, 1);
1907 av_assert0(pict->buf[0] || !*got_frame);
1909 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1911 return get_consumed_bytes(buf_index, buf_size);
1914 av_cold void ff_h264_free_context(H264Context *h)
1918 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1920 av_freep(&h->slice_ctx);
1921 h->nb_slice_ctx = 0;
1923 for (i = 0; i < MAX_SPS_COUNT; i++)
1924 av_freep(h->sps_buffers + i);
1926 for (i = 0; i < MAX_PPS_COUNT; i++)
1927 av_freep(h->pps_buffers + i);
1930 static av_cold int h264_decode_end(AVCodecContext *avctx)
1932 H264Context *h = avctx->priv_data;
1934 ff_h264_remove_all_refs(h);
1935 ff_h264_free_context(h);
1937 ff_h264_unref_picture(h, &h->cur_pic);
1938 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1943 #define OFFSET(x) offsetof(H264Context, x)
1944 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1945 static const AVOption h264_options[] = {
1946 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1947 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1948 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VD },
1952 static const AVClass h264_class = {
1953 .class_name = "H264 Decoder",
1954 .item_name = av_default_item_name,
1955 .option = h264_options,
1956 .version = LIBAVUTIL_VERSION_INT,
1959 static const AVProfile profiles[] = {
1960 { FF_PROFILE_H264_BASELINE, "Baseline" },
1961 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1962 { FF_PROFILE_H264_MAIN, "Main" },
1963 { FF_PROFILE_H264_EXTENDED, "Extended" },
1964 { FF_PROFILE_H264_HIGH, "High" },
1965 { FF_PROFILE_H264_HIGH_10, "High 10" },
1966 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1967 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1968 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1969 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1970 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1971 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1972 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1973 { FF_PROFILE_UNKNOWN },
1976 AVCodec ff_h264_decoder = {
1978 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1979 .type = AVMEDIA_TYPE_VIDEO,
1980 .id = AV_CODEC_ID_H264,
1981 .priv_data_size = sizeof(H264Context),
1982 .init = ff_h264_decode_init,
1983 .close = h264_decode_end,
1984 .decode = h264_decode_frame,
1985 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1986 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1987 CODEC_CAP_FRAME_THREADS,
1989 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1990 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1991 .profiles = NULL_IF_CONFIG_SMALL(profiles),
1992 .priv_class = &h264_class,
1995 #if CONFIG_H264_VDPAU_DECODER
1996 static const AVClass h264_vdpau_class = {
1997 .class_name = "H264 VDPAU Decoder",
1998 .item_name = av_default_item_name,
1999 .option = h264_options,
2000 .version = LIBAVUTIL_VERSION_INT,
2003 AVCodec ff_h264_vdpau_decoder = {
2004 .name = "h264_vdpau",
2005 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
2006 .type = AVMEDIA_TYPE_VIDEO,
2007 .id = AV_CODEC_ID_H264,
2008 .priv_data_size = sizeof(H264Context),
2009 .init = ff_h264_decode_init,
2010 .close = h264_decode_end,
2011 .decode = h264_decode_frame,
2012 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2014 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2016 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2017 .priv_class = &h264_vdpau_class,