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 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
57 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
59 H264Context *h = avctx->priv_data;
60 return h ? h->sps.num_reorder_frames : 0;
63 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
65 int mb_x, int mb_y, int mb_intra, int mb_skipped)
67 H264Context *h = opaque;
68 H264SliceContext *sl = &h->slice_ctx[0];
72 sl->mb_xy = mb_x + mb_y * h->mb_stride;
73 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
75 /* FIXME: It is possible albeit uncommon that slice references
76 * differ between slices. We take the easy approach and ignore
77 * it for now. If this turns out to have any relevance in
78 * practice then correct remapping should be added. */
79 if (ref >= sl->ref_count[0])
81 if (!sl->ref_list[0][ref].data[0]) {
82 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
85 if ((sl->ref_list[0][ref].reference&3) != 3) {
86 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
89 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
91 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
92 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
93 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
95 sl->mb_field_decoding_flag = 0;
96 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
99 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
102 AVCodecContext *avctx = h->avctx;
103 const AVFrame *src = h->cur_pic.f;
104 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
105 int vshift = desc->log2_chroma_h;
106 const int field_pic = h->picture_structure != PICT_FRAME;
112 height = FFMIN(height, avctx->height - y);
114 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
117 if (avctx->draw_horiz_band) {
118 int offset[AV_NUM_DATA_POINTERS];
121 offset[0] = y * src->linesize[0];
123 offset[2] = (y >> vshift) * src->linesize[1];
124 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
129 avctx->draw_horiz_band(avctx, src, offset,
130 y, h->picture_structure, height);
135 * Check if the top & left blocks are available if needed and
136 * change the dc mode so it only uses the available blocks.
138 int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
140 static const int8_t top[12] = {
141 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
143 static const int8_t left[12] = {
144 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
148 if (!(sl->top_samples_available & 0x8000)) {
149 for (i = 0; i < 4; i++) {
150 int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
152 av_log(h->avctx, AV_LOG_ERROR,
153 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
154 status, sl->mb_x, sl->mb_y);
155 return AVERROR_INVALIDDATA;
157 sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
162 if ((sl->left_samples_available & 0x8888) != 0x8888) {
163 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
164 for (i = 0; i < 4; i++)
165 if (!(sl->left_samples_available & mask[i])) {
166 int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
168 av_log(h->avctx, AV_LOG_ERROR,
169 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
170 status, sl->mb_x, sl->mb_y);
171 return AVERROR_INVALIDDATA;
173 sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
179 } // FIXME cleanup like ff_h264_check_intra_pred_mode
182 * Check if the top & left blocks are available if needed and
183 * change the dc mode so it only uses the available blocks.
185 int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
186 int mode, int is_chroma)
188 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
189 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
192 av_log(h->avctx, AV_LOG_ERROR,
193 "out of range intra chroma pred mode at %d %d\n",
195 return AVERROR_INVALIDDATA;
198 if (!(sl->top_samples_available & 0x8000)) {
201 av_log(h->avctx, AV_LOG_ERROR,
202 "top block unavailable for requested intra mode at %d %d\n",
204 return AVERROR_INVALIDDATA;
208 if ((sl->left_samples_available & 0x8080) != 0x8080) {
211 av_log(h->avctx, AV_LOG_ERROR,
212 "left block unavailable for requested intra mode at %d %d\n",
214 return AVERROR_INVALIDDATA;
216 if (is_chroma && (sl->left_samples_available & 0x8080)) {
217 // mad cow disease mode, aka MBAFF + constrained_intra_pred
218 mode = ALZHEIMER_DC_L0T_PRED8x8 +
219 (!(sl->left_samples_available & 0x8000)) +
220 2 * (mode == DC_128_PRED8x8);
227 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
229 int *dst_length, int *consumed, int length)
234 // src[0]&0x80; // forbidden bit
235 h->nal_ref_idc = src[0] >> 5;
236 h->nal_unit_type = src[0] & 0x1F;
241 #define STARTCODE_TEST \
242 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
243 if (src[i + 2] != 3 && src[i + 2] != 0) { \
244 /* startcode, so we must be past the end */ \
250 #if HAVE_FAST_UNALIGNED
251 #define FIND_FIRST_ZERO \
252 if (i > 0 && !src[i]) \
258 for (i = 0; i + 1 < length; i += 9) {
259 if (!((~AV_RN64A(src + i) &
260 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
261 0x8000800080008080ULL))
268 for (i = 0; i + 1 < length; i += 5) {
269 if (!((~AV_RN32A(src + i) &
270 (AV_RN32A(src + i) - 0x01000101U)) &
279 for (i = 0; i + 1 < length; i += 2) {
282 if (i > 0 && src[i - 1] == 0)
288 av_fast_padded_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size, length+MAX_MBPAIR_SIZE);
289 dst = sl->rbsp_buffer;
294 if(i>=length-1){ //no escaped 0
296 *consumed= length+1; //+1 for the header
297 if(h->avctx->flags2 & AV_CODEC_FLAG2_FAST){
300 memcpy(dst, src, length);
307 while (si + 2 < length) {
308 // remove escapes (very rare 1:2^22)
309 if (src[si + 2] > 3) {
310 dst[di++] = src[si++];
311 dst[di++] = src[si++];
312 } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {
313 if (src[si + 2] == 3) { // escape
318 } else // next start code
322 dst[di++] = src[si++];
325 dst[di++] = src[si++];
328 memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
331 *consumed = si + 1; // +1 for the header
332 /* FIXME store exact number of bits in the getbitcontext
333 * (it is needed for decoding) */
338 * Identify the exact end of the bitstream
339 * @return the length of the trailing, or 0 if damaged
341 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
346 ff_tlog(h->avctx, "rbsp trailing %X\n", v);
348 for (r = 1; r < 9; r++) {
356 void ff_h264_free_tables(H264Context *h)
360 av_freep(&h->intra4x4_pred_mode);
361 av_freep(&h->chroma_pred_mode_table);
362 av_freep(&h->cbp_table);
363 av_freep(&h->mvd_table[0]);
364 av_freep(&h->mvd_table[1]);
365 av_freep(&h->direct_table);
366 av_freep(&h->non_zero_count);
367 av_freep(&h->slice_table_base);
368 h->slice_table = NULL;
369 av_freep(&h->list_counts);
371 av_freep(&h->mb2b_xy);
372 av_freep(&h->mb2br_xy);
374 av_buffer_pool_uninit(&h->qscale_table_pool);
375 av_buffer_pool_uninit(&h->mb_type_pool);
376 av_buffer_pool_uninit(&h->motion_val_pool);
377 av_buffer_pool_uninit(&h->ref_index_pool);
379 for (i = 0; i < h->nb_slice_ctx; i++) {
380 H264SliceContext *sl = &h->slice_ctx[i];
382 av_freep(&sl->dc_val_base);
383 av_freep(&sl->er.mb_index2xy);
384 av_freep(&sl->er.error_status_table);
385 av_freep(&sl->er.er_temp_buffer);
387 av_freep(&sl->bipred_scratchpad);
388 av_freep(&sl->edge_emu_buffer);
389 av_freep(&sl->top_borders[0]);
390 av_freep(&sl->top_borders[1]);
392 sl->bipred_scratchpad_allocated = 0;
393 sl->edge_emu_buffer_allocated = 0;
394 sl->top_borders_allocated[0] = 0;
395 sl->top_borders_allocated[1] = 0;
399 int ff_h264_alloc_tables(H264Context *h)
401 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
402 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
405 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
406 row_mb_num, 8 * sizeof(uint8_t), fail)
407 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
409 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
410 big_mb_num * 48 * sizeof(uint8_t), fail)
411 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
412 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
413 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
414 big_mb_num * sizeof(uint16_t), fail)
415 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
416 big_mb_num * sizeof(uint8_t), fail)
417 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
418 row_mb_num, 16 * sizeof(uint8_t), fail);
419 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
420 row_mb_num, 16 * sizeof(uint8_t), fail);
421 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
422 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
424 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
425 4 * big_mb_num * sizeof(uint8_t), fail);
426 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
427 big_mb_num * sizeof(uint8_t), fail)
429 memset(h->slice_table_base, -1,
430 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
431 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
433 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
434 big_mb_num * sizeof(uint32_t), fail);
435 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
436 big_mb_num * sizeof(uint32_t), fail);
437 for (y = 0; y < h->mb_height; y++)
438 for (x = 0; x < h->mb_width; x++) {
439 const int mb_xy = x + y * h->mb_stride;
440 const int b_xy = 4 * x + 4 * y * h->b_stride;
442 h->mb2b_xy[mb_xy] = b_xy;
443 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
446 if (!h->dequant4_coeff[0])
447 ff_h264_init_dequant_tables(h);
452 ff_h264_free_tables(h);
453 return AVERROR(ENOMEM);
458 * Allocate buffers which are not shared amongst multiple threads.
460 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
462 ERContext *er = &sl->er;
463 int mb_array_size = h->mb_height * h->mb_stride;
464 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
465 int c_size = h->mb_stride * (h->mb_height + 1);
466 int yc_size = y_size + 2 * c_size;
469 sl->ref_cache[0][scan8[5] + 1] =
470 sl->ref_cache[0][scan8[7] + 1] =
471 sl->ref_cache[0][scan8[13] + 1] =
472 sl->ref_cache[1][scan8[5] + 1] =
473 sl->ref_cache[1][scan8[7] + 1] =
474 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
476 if (sl != h->slice_ctx) {
477 memset(er, 0, sizeof(*er));
479 if (CONFIG_ERROR_RESILIENCE) {
482 er->avctx = h->avctx;
483 er->decode_mb = h264_er_decode_mb;
485 er->quarter_sample = 1;
487 er->mb_num = h->mb_num;
488 er->mb_width = h->mb_width;
489 er->mb_height = h->mb_height;
490 er->mb_stride = h->mb_stride;
491 er->b8_stride = h->mb_width * 2 + 1;
493 // error resilience code looks cleaner with this
494 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
495 (h->mb_num + 1) * sizeof(int), fail);
497 for (y = 0; y < h->mb_height; y++)
498 for (x = 0; x < h->mb_width; x++)
499 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
501 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
502 h->mb_stride + h->mb_width;
504 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
505 mb_array_size * sizeof(uint8_t), fail);
507 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
508 h->mb_height * h->mb_stride, fail);
510 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
511 yc_size * sizeof(int16_t), fail);
512 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
513 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
514 er->dc_val[2] = er->dc_val[1] + c_size;
515 for (i = 0; i < yc_size; i++)
516 sl->dc_val_base[i] = 1024;
522 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
525 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
526 int parse_extradata);
528 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
530 AVCodecContext *avctx = h->avctx;
533 if (!buf || size <= 0)
538 const unsigned char *p = buf;
543 av_log(avctx, AV_LOG_ERROR,
544 "avcC %d too short\n", size);
545 return AVERROR_INVALIDDATA;
547 /* sps and pps in the avcC always have length coded with 2 bytes,
548 * so put a fake nal_length_size = 2 while parsing them */
549 h->nal_length_size = 2;
550 // Decode sps from avcC
551 cnt = *(p + 5) & 0x1f; // Number of sps
553 for (i = 0; i < cnt; i++) {
554 nalsize = AV_RB16(p) + 2;
555 if(nalsize > size - (p-buf))
556 return AVERROR_INVALIDDATA;
557 ret = decode_nal_units(h, p, nalsize, 1);
559 av_log(avctx, AV_LOG_ERROR,
560 "Decoding sps %d from avcC failed\n", i);
565 // Decode pps from avcC
566 cnt = *(p++); // Number of pps
567 for (i = 0; i < cnt; i++) {
568 nalsize = AV_RB16(p) + 2;
569 if(nalsize > size - (p-buf))
570 return AVERROR_INVALIDDATA;
571 ret = decode_nal_units(h, p, nalsize, 1);
573 av_log(avctx, AV_LOG_ERROR,
574 "Decoding pps %d from avcC failed\n", i);
579 // Store right nal length size that will be used to parse all other nals
580 h->nal_length_size = (buf[4] & 0x03) + 1;
583 ret = decode_nal_units(h, buf, size, 1);
590 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
595 h->backup_width = -1;
596 h->backup_height = -1;
597 h->backup_pix_fmt = AV_PIX_FMT_NONE;
598 h->dequant_coeff_pps = -1;
599 h->current_sps_id = -1;
600 h->cur_chroma_format_idc = -1;
602 h->picture_structure = PICT_FRAME;
603 h->slice_context_count = 1;
604 h->workaround_bugs = avctx->workaround_bugs;
605 h->flags = avctx->flags;
606 h->prev_poc_msb = 1 << 16;
608 h->recovery_frame = -1;
609 h->frame_recovered = 0;
610 h->prev_frame_num = -1;
611 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
613 h->next_outputed_poc = INT_MIN;
614 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
615 h->last_pocs[i] = INT_MIN;
617 ff_h264_reset_sei(h);
619 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
621 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
622 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
625 return AVERROR(ENOMEM);
628 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
629 h->DPB[i].f = av_frame_alloc();
631 return AVERROR(ENOMEM);
634 h->cur_pic.f = av_frame_alloc();
636 return AVERROR(ENOMEM);
638 h->last_pic_for_ec.f = av_frame_alloc();
639 if (!h->last_pic_for_ec.f)
640 return AVERROR(ENOMEM);
642 for (i = 0; i < h->nb_slice_ctx; i++)
643 h->slice_ctx[i].h264 = h;
648 static AVOnce h264_vlc_init = AV_ONCE_INIT;
650 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
652 H264Context *h = avctx->priv_data;
655 ret = h264_init_context(avctx, h);
660 if (!avctx->has_b_frames)
663 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
665 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
666 return AVERROR_UNKNOWN;
669 if (avctx->codec_id == AV_CODEC_ID_H264) {
670 if (avctx->ticks_per_frame == 1) {
671 if(h->avctx->time_base.den < INT_MAX/2) {
672 h->avctx->time_base.den *= 2;
674 h->avctx->time_base.num /= 2;
676 avctx->ticks_per_frame = 2;
679 if (avctx->extradata_size > 0 && avctx->extradata) {
680 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
682 ff_h264_free_context(h);
687 if (h->sps.bitstream_restriction_flag &&
688 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
689 h->avctx->has_b_frames = h->sps.num_reorder_frames;
693 avctx->internal->allocate_progress = 1;
695 ff_h264_flush_change(h);
697 if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
700 if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
701 av_log(avctx, AV_LOG_WARNING,
702 "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
703 "Use it at your own risk\n");
710 static int decode_init_thread_copy(AVCodecContext *avctx)
712 H264Context *h = avctx->priv_data;
715 if (!avctx->internal->is_copy)
718 memset(h, 0, sizeof(*h));
720 ret = h264_init_context(avctx, h);
724 h->context_initialized = 0;
731 * Run setup operations that must be run after slice header decoding.
732 * This includes finding the next displayed frame.
734 * @param h h264 master context
735 * @param setup_finished enough NALs have been read that we can call
736 * ff_thread_finish_setup()
738 static void decode_postinit(H264Context *h, int setup_finished)
740 H264Picture *out = h->cur_pic_ptr;
741 H264Picture *cur = h->cur_pic_ptr;
742 int i, pics, out_of_order, out_idx;
744 h->cur_pic_ptr->f->pict_type = h->pict_type;
746 if (h->next_output_pic)
749 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
750 /* FIXME: if we have two PAFF fields in one packet, we can't start
751 * the next thread here. If we have one field per packet, we can.
752 * The check in decode_nal_units() is not good enough to find this
753 * yet, so we assume the worst for now. */
754 // if (setup_finished)
755 // ff_thread_finish_setup(h->avctx);
756 if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
758 if (h->avctx->hwaccel || h->missing_fields <=1)
762 cur->f->interlaced_frame = 0;
763 cur->f->repeat_pict = 0;
765 /* Signal interlacing information externally. */
766 /* Prioritize picture timing SEI information over used
767 * decoding process if it exists. */
769 if (h->sps.pic_struct_present_flag) {
770 switch (h->sei_pic_struct) {
771 case SEI_PIC_STRUCT_FRAME:
773 case SEI_PIC_STRUCT_TOP_FIELD:
774 case SEI_PIC_STRUCT_BOTTOM_FIELD:
775 cur->f->interlaced_frame = 1;
777 case SEI_PIC_STRUCT_TOP_BOTTOM:
778 case SEI_PIC_STRUCT_BOTTOM_TOP:
779 if (FIELD_OR_MBAFF_PICTURE(h))
780 cur->f->interlaced_frame = 1;
782 // try to flag soft telecine progressive
783 cur->f->interlaced_frame = h->prev_interlaced_frame;
785 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
786 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
787 /* Signal the possibility of telecined film externally
788 * (pic_struct 5,6). From these hints, let the applications
789 * decide if they apply deinterlacing. */
790 cur->f->repeat_pict = 1;
792 case SEI_PIC_STRUCT_FRAME_DOUBLING:
793 cur->f->repeat_pict = 2;
795 case SEI_PIC_STRUCT_FRAME_TRIPLING:
796 cur->f->repeat_pict = 4;
800 if ((h->sei_ct_type & 3) &&
801 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
802 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
804 /* Derive interlacing flag from used decoding process. */
805 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
807 h->prev_interlaced_frame = cur->f->interlaced_frame;
809 if (cur->field_poc[0] != cur->field_poc[1]) {
810 /* Derive top_field_first from field pocs. */
811 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
813 if (h->sps.pic_struct_present_flag) {
814 /* Use picture timing SEI information. Even if it is a
815 * information of a past frame, better than nothing. */
816 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
817 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
818 cur->f->top_field_first = 1;
820 cur->f->top_field_first = 0;
821 } else if (cur->f->interlaced_frame) {
822 /* Default to top field first when pic_struct_present_flag
823 * is not set but interlaced frame detected */
824 cur->f->top_field_first = 1;
826 /* Most likely progressive */
827 cur->f->top_field_first = 0;
831 if (h->sei_frame_packing_present &&
832 h->frame_packing_arrangement_type >= 0 &&
833 h->frame_packing_arrangement_type <= 6 &&
834 h->content_interpretation_type > 0 &&
835 h->content_interpretation_type < 3) {
836 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
838 switch (h->frame_packing_arrangement_type) {
840 stereo->type = AV_STEREO3D_CHECKERBOARD;
843 stereo->type = AV_STEREO3D_COLUMNS;
846 stereo->type = AV_STEREO3D_LINES;
849 if (h->quincunx_subsampling)
850 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
852 stereo->type = AV_STEREO3D_SIDEBYSIDE;
855 stereo->type = AV_STEREO3D_TOPBOTTOM;
858 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
861 stereo->type = AV_STEREO3D_2D;
865 if (h->content_interpretation_type == 2)
866 stereo->flags = AV_STEREO3D_FLAG_INVERT;
870 if (h->sei_display_orientation_present &&
871 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
872 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
873 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
874 AV_FRAME_DATA_DISPLAYMATRIX,
875 sizeof(int32_t) * 9);
877 av_display_rotation_set((int32_t *)rotation->data, angle);
878 av_display_matrix_flip((int32_t *)rotation->data,
879 h->sei_hflip, h->sei_vflip);
883 if (h->sei_reguserdata_afd_present) {
884 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
888 *sd->data = h->active_format_description;
889 h->sei_reguserdata_afd_present = 0;
893 if (h->a53_caption) {
894 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
895 AV_FRAME_DATA_A53_CC,
896 h->a53_caption_size);
898 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
899 av_freep(&h->a53_caption);
900 h->a53_caption_size = 0;
901 h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
904 cur->mmco_reset = h->mmco_reset;
907 // FIXME do something with unavailable reference frames
909 /* Sort B-frames into display order */
910 if (h->sps.bitstream_restriction_flag ||
911 h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
912 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
914 h->low_delay = !h->avctx->has_b_frames;
916 for (i = 0; 1; i++) {
917 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
919 h->last_pocs[i-1] = cur->poc;
922 h->last_pocs[i-1]= h->last_pocs[i];
925 out_of_order = MAX_DELAYED_PIC_COUNT - i;
926 if( cur->f->pict_type == AV_PICTURE_TYPE_B
927 || (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))
928 out_of_order = FFMAX(out_of_order, 1);
929 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
930 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
931 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
932 h->last_pocs[i] = INT_MIN;
933 h->last_pocs[0] = cur->poc;
935 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
936 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
937 h->avctx->has_b_frames = out_of_order;
942 while (h->delayed_pic[pics])
945 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
947 h->delayed_pic[pics++] = cur;
948 if (cur->reference == 0)
949 cur->reference = DELAYED_PIC_REF;
951 out = h->delayed_pic[0];
953 for (i = 1; h->delayed_pic[i] &&
954 !h->delayed_pic[i]->f->key_frame &&
955 !h->delayed_pic[i]->mmco_reset;
957 if (h->delayed_pic[i]->poc < out->poc) {
958 out = h->delayed_pic[i];
961 if (h->avctx->has_b_frames == 0 &&
962 (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
963 h->next_outputed_poc = INT_MIN;
964 out_of_order = out->poc < h->next_outputed_poc;
966 if (out_of_order || pics > h->avctx->has_b_frames) {
967 out->reference &= ~DELAYED_PIC_REF;
968 // for frame threading, the owner must be the second field's thread or
969 // else the first thread can release the picture and reuse it unsafely
970 for (i = out_idx; h->delayed_pic[i]; i++)
971 h->delayed_pic[i] = h->delayed_pic[i + 1];
973 if (!out_of_order && pics > h->avctx->has_b_frames) {
974 h->next_output_pic = out;
975 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
976 h->next_outputed_poc = INT_MIN;
978 h->next_outputed_poc = out->poc;
980 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
983 if (h->next_output_pic) {
984 if (h->next_output_pic->recovered) {
985 // We have reached an recovery point and all frames after it in
986 // display order are "recovered".
987 h->frame_recovered |= FRAME_RECOVERED_SEI;
989 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
992 if (setup_finished && !h->avctx->hwaccel) {
993 ff_thread_finish_setup(h->avctx);
995 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
996 h->setup_finished = 1;
1000 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
1003 int luma_def, chroma_def;
1006 sl->use_weight_chroma = 0;
1007 sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
1008 if (h->sps.chroma_format_idc)
1009 sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
1011 if (sl->luma_log2_weight_denom > 7U) {
1012 av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
1013 sl->luma_log2_weight_denom = 0;
1015 if (sl->chroma_log2_weight_denom > 7U) {
1016 av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
1017 sl->chroma_log2_weight_denom = 0;
1020 luma_def = 1 << sl->luma_log2_weight_denom;
1021 chroma_def = 1 << sl->chroma_log2_weight_denom;
1023 for (list = 0; list < 2; list++) {
1024 sl->luma_weight_flag[list] = 0;
1025 sl->chroma_weight_flag[list] = 0;
1026 for (i = 0; i < sl->ref_count[list]; i++) {
1027 int luma_weight_flag, chroma_weight_flag;
1029 luma_weight_flag = get_bits1(&sl->gb);
1030 if (luma_weight_flag) {
1031 sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
1032 sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
1033 if (sl->luma_weight[i][list][0] != luma_def ||
1034 sl->luma_weight[i][list][1] != 0) {
1036 sl->luma_weight_flag[list] = 1;
1039 sl->luma_weight[i][list][0] = luma_def;
1040 sl->luma_weight[i][list][1] = 0;
1043 if (h->sps.chroma_format_idc) {
1044 chroma_weight_flag = get_bits1(&sl->gb);
1045 if (chroma_weight_flag) {
1047 for (j = 0; j < 2; j++) {
1048 sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
1049 sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
1050 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1051 sl->chroma_weight[i][list][j][1] != 0) {
1052 sl->use_weight_chroma = 1;
1053 sl->chroma_weight_flag[list] = 1;
1058 for (j = 0; j < 2; j++) {
1059 sl->chroma_weight[i][list][j][0] = chroma_def;
1060 sl->chroma_weight[i][list][j][1] = 0;
1065 if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
1068 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1073 * instantaneous decoder refresh.
1075 static void idr(H264Context *h)
1078 ff_h264_remove_all_refs(h);
1080 h->prev_frame_num_offset = 0;
1081 h->prev_poc_msb = 1<<16;
1082 h->prev_poc_lsb = 0;
1083 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1084 h->last_pocs[i] = INT_MIN;
1087 /* forget old pics after a seek */
1088 void ff_h264_flush_change(H264Context *h)
1092 h->next_outputed_poc = INT_MIN;
1093 h->prev_interlaced_frame = 1;
1096 h->prev_frame_num = -1;
1097 if (h->cur_pic_ptr) {
1098 h->cur_pic_ptr->reference = 0;
1099 for (j=i=0; h->delayed_pic[i]; i++)
1100 if (h->delayed_pic[i] != h->cur_pic_ptr)
1101 h->delayed_pic[j++] = h->delayed_pic[i];
1102 h->delayed_pic[j] = NULL;
1104 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1107 ff_h264_reset_sei(h);
1108 h->recovery_frame = -1;
1109 h->frame_recovered = 0;
1110 h->current_slice = 0;
1112 for (i = 0; i < h->nb_slice_ctx; i++)
1113 h->slice_ctx[i].list_count = 0;
1116 /* forget old pics after a seek */
1117 static void flush_dpb(AVCodecContext *avctx)
1119 H264Context *h = avctx->priv_data;
1122 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1124 ff_h264_flush_change(h);
1126 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1127 ff_h264_unref_picture(h, &h->DPB[i]);
1128 h->cur_pic_ptr = NULL;
1129 ff_h264_unref_picture(h, &h->cur_pic);
1133 ff_h264_free_tables(h);
1134 h->context_initialized = 0;
1137 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1139 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1142 h->frame_num_offset = h->prev_frame_num_offset;
1143 if (h->frame_num < h->prev_frame_num)
1144 h->frame_num_offset += max_frame_num;
1146 if (h->sps.poc_type == 0) {
1147 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1149 if (h->poc_lsb < h->prev_poc_lsb &&
1150 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1151 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1152 else if (h->poc_lsb > h->prev_poc_lsb &&
1153 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1154 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1156 h->poc_msb = h->prev_poc_msb;
1158 field_poc[1] = h->poc_msb + h->poc_lsb;
1159 if (h->picture_structure == PICT_FRAME)
1160 field_poc[1] += h->delta_poc_bottom;
1161 } else if (h->sps.poc_type == 1) {
1162 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1165 if (h->sps.poc_cycle_length != 0)
1166 abs_frame_num = h->frame_num_offset + h->frame_num;
1170 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1173 expected_delta_per_poc_cycle = 0;
1174 for (i = 0; i < h->sps.poc_cycle_length; i++)
1175 // FIXME integrate during sps parse
1176 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1178 if (abs_frame_num > 0) {
1179 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1180 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1182 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1183 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1184 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1188 if (h->nal_ref_idc == 0)
1189 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1191 field_poc[0] = expectedpoc + h->delta_poc[0];
1192 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1194 if (h->picture_structure == PICT_FRAME)
1195 field_poc[1] += h->delta_poc[1];
1197 int poc = 2 * (h->frame_num_offset + h->frame_num);
1199 if (!h->nal_ref_idc)
1206 if (h->picture_structure != PICT_BOTTOM_FIELD)
1207 pic_field_poc[0] = field_poc[0];
1208 if (h->picture_structure != PICT_TOP_FIELD)
1209 pic_field_poc[1] = field_poc[1];
1210 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1216 * Compute profile from profile_idc and constraint_set?_flags.
1220 * @return profile as defined by FF_PROFILE_H264_*
1222 int ff_h264_get_profile(SPS *sps)
1224 int profile = sps->profile_idc;
1226 switch (sps->profile_idc) {
1227 case FF_PROFILE_H264_BASELINE:
1228 // constraint_set1_flag set to 1
1229 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1231 case FF_PROFILE_H264_HIGH_10:
1232 case FF_PROFILE_H264_HIGH_422:
1233 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1234 // constraint_set3_flag set to 1
1235 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1242 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1244 int ref_count[2], list_count;
1245 int num_ref_idx_active_override_flag;
1247 // set defaults, might be overridden a few lines later
1248 ref_count[0] = h->pps.ref_count[0];
1249 ref_count[1] = h->pps.ref_count[1];
1251 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1253 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1255 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1256 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1257 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1259 if (num_ref_idx_active_override_flag) {
1260 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1261 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1262 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1264 // full range is spec-ok in this case, even for frames
1268 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1269 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]);
1270 sl->ref_count[0] = sl->ref_count[1] = 0;
1272 return AVERROR_INVALIDDATA;
1275 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1281 ref_count[0] = ref_count[1] = 0;
1284 if (list_count != sl->list_count ||
1285 ref_count[0] != sl->ref_count[0] ||
1286 ref_count[1] != sl->ref_count[1]) {
1287 sl->ref_count[0] = ref_count[0];
1288 sl->ref_count[1] = ref_count[1];
1289 sl->list_count = list_count;
1296 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1298 static int get_bit_length(H264Context *h, const uint8_t *buf,
1299 const uint8_t *ptr, int dst_length,
1300 int i, int next_avc)
1302 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1303 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1304 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1305 h->workaround_bugs |= FF_BUG_TRUNCATED;
1307 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1308 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1314 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1317 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1319 int next_avc = h->is_avc ? 0 : buf_size;
1322 int nals_needed = 0;
1323 int first_slice = 0;
1328 int dst_length, bit_length, consumed;
1331 if (buf_index >= next_avc) {
1332 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1335 next_avc = buf_index + nalsize;
1337 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1338 if (buf_index >= buf_size)
1340 if (buf_index >= next_avc)
1344 ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1345 next_avc - buf_index);
1347 if (!ptr || dst_length < 0)
1348 return AVERROR_INVALIDDATA;
1350 buf_index += consumed;
1352 bit_length = get_bit_length(h, buf, ptr, dst_length,
1353 buf_index, next_avc);
1356 /* packets can sometimes contain multiple PPS/SPS,
1357 * e.g. two PAFF field pictures in one packet, or a demuxer
1358 * which splits NALs strangely if so, when frame threading we
1359 * can't start the next thread until we've read all of them */
1360 switch (h->nal_unit_type) {
1363 nals_needed = nal_index;
1368 init_get_bits(&gb, ptr, bit_length);
1369 if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
1371 first_slice != h->nal_unit_type)
1372 nals_needed = nal_index;
1374 first_slice = h->nal_unit_type;
1381 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1382 int parse_extradata)
1384 AVCodecContext *const avctx = h->avctx;
1385 H264SliceContext *sl;
1387 unsigned context_count;
1389 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1394 h->nal_unit_type= 0;
1396 if(!h->slice_context_count)
1397 h->slice_context_count= 1;
1398 h->max_contexts = h->slice_context_count;
1399 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1400 h->current_slice = 0;
1401 if (!h->first_field)
1402 h->cur_pic_ptr = NULL;
1403 ff_h264_reset_sei(h);
1406 if (h->nal_length_size == 4) {
1407 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1409 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1413 if (avctx->active_thread_type & FF_THREAD_FRAME)
1414 nals_needed = get_last_needed_nal(h, buf, buf_size);
1419 next_avc = h->is_avc ? 0 : buf_size;
1429 if (buf_index >= next_avc) {
1430 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1433 next_avc = buf_index + nalsize;
1435 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1436 if (buf_index >= buf_size)
1438 if (buf_index >= next_avc)
1442 sl = &h->slice_ctx[context_count];
1444 ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1445 &consumed, next_avc - buf_index);
1446 if (!ptr || dst_length < 0) {
1451 bit_length = get_bit_length(h, buf, ptr, dst_length,
1452 buf_index + consumed, next_avc);
1454 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1455 av_log(h->avctx, AV_LOG_DEBUG,
1456 "NAL %d/%d at %d/%d length %d\n",
1457 h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
1459 if (h->is_avc && (nalsize != consumed) && nalsize)
1460 av_log(h->avctx, AV_LOG_DEBUG,
1461 "AVC: Consumed only %d bytes instead of %d\n",
1464 buf_index += consumed;
1467 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1468 h->nal_ref_idc == 0 &&
1469 h->nal_unit_type != NAL_SEI)
1473 /* Ignore per frame NAL unit type during extradata
1474 * parsing. Decoding slices is not possible in codec init
1476 if (parse_extradata) {
1477 switch (h->nal_unit_type) {
1483 av_log(h->avctx, AV_LOG_WARNING,
1484 "Ignoring NAL %d in global header/extradata\n",
1486 // fall through to next case
1487 case NAL_AUXILIARY_SLICE:
1488 h->nal_unit_type = NAL_FF_IGNORE;
1494 switch (h->nal_unit_type) {
1496 if ((ptr[0] & 0xFC) == 0x98) {
1497 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1498 h->next_outputed_poc = INT_MIN;
1502 if (h->nal_unit_type != NAL_IDR_SLICE) {
1503 av_log(h->avctx, AV_LOG_ERROR,
1504 "Invalid mix of idr and non-idr slices\n");
1509 if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
1510 av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
1511 ret = AVERROR_INVALIDDATA;
1514 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1517 h->has_recovery_point = 1;
1519 init_get_bits(&sl->gb, ptr, bit_length);
1521 if ( nals_needed >= nal_index
1522 || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
1525 if ((err = ff_h264_decode_slice_header(h, sl)))
1528 if (h->sei_recovery_frame_cnt >= 0) {
1529 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1530 h->valid_recovery_point = 1;
1532 if ( h->recovery_frame < 0
1533 || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
1534 h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
1536 if (!h->valid_recovery_point)
1537 h->recovery_frame = h->frame_num;
1541 h->cur_pic_ptr->f->key_frame |=
1542 (h->nal_unit_type == NAL_IDR_SLICE);
1544 if (h->nal_unit_type == NAL_IDR_SLICE ||
1545 h->recovery_frame == h->frame_num) {
1546 h->recovery_frame = -1;
1547 h->cur_pic_ptr->recovered = 1;
1549 // If we have an IDR, all frames after it in decoded order are
1551 if (h->nal_unit_type == NAL_IDR_SLICE)
1552 h->frame_recovered |= FRAME_RECOVERED_IDR;
1554 h->cur_pic_ptr->recovered |= h->frame_recovered;
1556 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1559 if (h->current_slice == 1) {
1560 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1561 decode_postinit(h, nal_index >= nals_needed);
1563 if (h->avctx->hwaccel &&
1564 (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
1566 #if FF_API_CAP_VDPAU
1567 if (CONFIG_H264_VDPAU_DECODER &&
1568 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
1569 ff_vdpau_h264_picture_start(h);
1573 if (sl->redundant_pic_count == 0) {
1574 if (avctx->hwaccel) {
1575 ret = avctx->hwaccel->decode_slice(avctx,
1576 &buf[buf_index - consumed],
1580 #if FF_API_CAP_VDPAU
1581 } else if (CONFIG_H264_VDPAU_DECODER &&
1582 h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
1583 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1585 sizeof(start_code));
1586 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
1587 &buf[buf_index - consumed],
1597 avpriv_request_sample(avctx, "data partitioning");
1600 init_get_bits(&h->gb, ptr, bit_length);
1601 ret = ff_h264_decode_sei(h);
1602 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1606 init_get_bits(&h->gb, ptr, bit_length);
1607 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1609 if (h->is_avc ? nalsize : 1) {
1610 av_log(h->avctx, AV_LOG_DEBUG,
1611 "SPS decoding failure, trying again with the complete NAL\n");
1613 av_assert0(next_avc - buf_index + consumed == nalsize);
1614 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1616 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1617 8*(next_avc - buf_index + consumed - 1));
1618 if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
1621 init_get_bits(&h->gb, ptr, bit_length);
1622 ff_h264_decode_seq_parameter_set(h, 1);
1626 init_get_bits(&h->gb, ptr, bit_length);
1627 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1628 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1632 case NAL_END_SEQUENCE:
1633 case NAL_END_STREAM:
1634 case NAL_FILLER_DATA:
1636 case NAL_AUXILIARY_SLICE:
1641 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1642 h->nal_unit_type, bit_length);
1645 if (context_count == h->max_contexts) {
1646 ret = ff_h264_execute_decode_slices(h, context_count);
1647 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1652 if (err < 0 || err == SLICE_SKIPED) {
1654 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1655 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1656 } else if (err == SLICE_SINGLETHREAD) {
1657 if (context_count > 1) {
1658 ret = ff_h264_execute_decode_slices(h, context_count - 1);
1659 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1663 /* Slice could not be decoded in parallel mode, restart. Note
1664 * that rbsp_buffer is not transferred, but since we no longer
1665 * run in parallel mode this should not be an issue. */
1666 sl = &h->slice_ctx[0];
1671 if (context_count) {
1672 ret = ff_h264_execute_decode_slices(h, context_count);
1673 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1680 if (h->cur_pic_ptr && !h->droppable) {
1681 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1682 h->picture_structure == PICT_BOTTOM_FIELD);
1685 return (ret < 0) ? ret : buf_index;
1689 * Return the number of bytes consumed for building the current frame.
1691 static int get_consumed_bytes(int pos, int buf_size)
1694 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1695 if (pos + 10 > buf_size)
1696 pos = buf_size; // oops ;)
1701 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1703 AVFrame *src = srcp->f;
1704 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1706 int ret = av_frame_ref(dst, src);
1710 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1712 h->backup_width = h->avctx->width;
1713 h->backup_height = h->avctx->height;
1714 h->backup_pix_fmt = h->avctx->pix_fmt;
1716 h->avctx->width = dst->width;
1717 h->avctx->height = dst->height;
1718 h->avctx->pix_fmt = dst->format;
1720 if (srcp->sei_recovery_frame_cnt == 0)
1725 for (i = 0; i < desc->nb_components; i++) {
1726 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1727 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1728 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1729 (srcp->crop_top >> vshift) * dst->linesize[i];
1730 dst->data[i] += off;
1735 static int is_extra(const uint8_t *buf, int buf_size)
1737 int cnt= buf[5]&0x1f;
1738 const uint8_t *p= buf+6;
1740 int nalsize= AV_RB16(p) + 2;
1741 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1749 int nalsize= AV_RB16(p) + 2;
1750 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1757 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1758 int *got_frame, AVPacket *avpkt)
1760 const uint8_t *buf = avpkt->data;
1761 int buf_size = avpkt->size;
1762 H264Context *h = avctx->priv_data;
1763 AVFrame *pict = data;
1769 h->flags = avctx->flags;
1770 h->setup_finished = 0;
1772 if (h->backup_width != -1) {
1773 avctx->width = h->backup_width;
1774 h->backup_width = -1;
1776 if (h->backup_height != -1) {
1777 avctx->height = h->backup_height;
1778 h->backup_height = -1;
1780 if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
1781 avctx->pix_fmt = h->backup_pix_fmt;
1782 h->backup_pix_fmt = AV_PIX_FMT_NONE;
1785 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1787 /* end of stream, output what is still in the buffers */
1788 if (buf_size == 0) {
1791 h->cur_pic_ptr = NULL;
1794 // FIXME factorize this with the output code below
1795 out = h->delayed_pic[0];
1798 h->delayed_pic[i] &&
1799 !h->delayed_pic[i]->f->key_frame &&
1800 !h->delayed_pic[i]->mmco_reset;
1802 if (h->delayed_pic[i]->poc < out->poc) {
1803 out = h->delayed_pic[i];
1807 for (i = out_idx; h->delayed_pic[i]; i++)
1808 h->delayed_pic[i] = h->delayed_pic[i + 1];
1811 out->reference &= ~DELAYED_PIC_REF;
1812 ret = output_frame(h, pict, out);
1820 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1822 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1823 if (is_extra(side, side_size))
1824 ff_h264_decode_extradata(h, side, side_size);
1826 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1827 if (is_extra(buf, buf_size))
1828 return ff_h264_decode_extradata(h, buf, buf_size);
1831 buf_index = decode_nal_units(h, buf, buf_size, 0);
1833 return AVERROR_INVALIDDATA;
1835 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1836 av_assert0(buf_index <= buf_size);
1840 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1841 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1842 buf_size >= 4 && !memcmp("Q264", buf, 4))
1844 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1845 return AVERROR_INVALIDDATA;
1848 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1849 (h->mb_y >= h->mb_height && h->mb_height)) {
1850 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1851 decode_postinit(h, 1);
1853 if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
1856 /* Wait for second field. */
1858 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1859 (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
1860 h->next_output_pic->recovered)) {
1861 if (!h->next_output_pic->recovered)
1862 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1864 if (!h->avctx->hwaccel &&
1865 (h->next_output_pic->field_poc[0] == INT_MAX ||
1866 h->next_output_pic->field_poc[1] == INT_MAX)
1869 AVFrame *f = h->next_output_pic->f;
1870 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1871 uint8_t *dst_data[4];
1873 const uint8_t *src_data[4];
1875 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1877 for (p = 0; p<4; p++) {
1878 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1879 src_data[p] = f->data[p] + field *f->linesize[p];
1880 linesizes[p] = 2*f->linesize[p];
1883 av_image_copy(dst_data, linesizes, src_data, linesizes,
1884 f->format, f->width, f->height>>1);
1887 ret = output_frame(h, pict, h->next_output_pic);
1891 if (CONFIG_MPEGVIDEO) {
1892 ff_print_debug_info2(h->avctx, pict, NULL,
1893 h->next_output_pic->mb_type,
1894 h->next_output_pic->qscale_table,
1895 h->next_output_pic->motion_val,
1897 h->mb_width, h->mb_height, h->mb_stride, 1);
1902 av_assert0(pict->buf[0] || !*got_frame);
1904 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1906 return get_consumed_bytes(buf_index, buf_size);
1909 av_cold void ff_h264_free_context(H264Context *h)
1913 ff_h264_free_tables(h);
1915 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1916 ff_h264_unref_picture(h, &h->DPB[i]);
1917 av_frame_free(&h->DPB[i].f);
1919 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1921 h->cur_pic_ptr = NULL;
1923 for (i = 0; i < h->nb_slice_ctx; i++)
1924 av_freep(&h->slice_ctx[i].rbsp_buffer);
1925 av_freep(&h->slice_ctx);
1926 h->nb_slice_ctx = 0;
1928 for (i = 0; i < MAX_SPS_COUNT; i++)
1929 av_freep(h->sps_buffers + i);
1931 for (i = 0; i < MAX_PPS_COUNT; i++)
1932 av_freep(h->pps_buffers + i);
1935 static av_cold int h264_decode_end(AVCodecContext *avctx)
1937 H264Context *h = avctx->priv_data;
1939 ff_h264_remove_all_refs(h);
1940 ff_h264_free_context(h);
1942 ff_h264_unref_picture(h, &h->cur_pic);
1943 av_frame_free(&h->cur_pic.f);
1944 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1945 av_frame_free(&h->last_pic_for_ec.f);
1950 #define OFFSET(x) offsetof(H264Context, x)
1951 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1952 static const AVOption h264_options[] = {
1953 {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
1954 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1955 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
1959 static const AVClass h264_class = {
1960 .class_name = "H264 Decoder",
1961 .item_name = av_default_item_name,
1962 .option = h264_options,
1963 .version = LIBAVUTIL_VERSION_INT,
1966 AVCodec ff_h264_decoder = {
1968 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1969 .type = AVMEDIA_TYPE_VIDEO,
1970 .id = AV_CODEC_ID_H264,
1971 .priv_data_size = sizeof(H264Context),
1972 .init = ff_h264_decode_init,
1973 .close = h264_decode_end,
1974 .decode = h264_decode_frame,
1975 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1976 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1977 AV_CODEC_CAP_FRAME_THREADS,
1978 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1980 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1981 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1982 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1983 .priv_class = &h264_class,
1986 #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
1987 static const AVClass h264_vdpau_class = {
1988 .class_name = "H264 VDPAU Decoder",
1989 .item_name = av_default_item_name,
1990 .option = h264_options,
1991 .version = LIBAVUTIL_VERSION_INT,
1994 AVCodec ff_h264_vdpau_decoder = {
1995 .name = "h264_vdpau",
1996 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
1997 .type = AVMEDIA_TYPE_VIDEO,
1998 .id = AV_CODEC_ID_H264,
1999 .priv_data_size = sizeof(H264Context),
2000 .init = ff_h264_decode_init,
2001 .close = h264_decode_end,
2002 .decode = h264_decode_frame,
2003 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
2005 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2007 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
2008 .priv_class = &h264_vdpau_class,