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 Libav.
7 * Libav 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 * Libav 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 Libav; 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 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/stereo3d.h"
32 #include "libavutil/timer.h"
35 #include "cabac_functions.h"
36 #include "error_resilience.h"
40 #include "h264chroma.h"
41 #include "h264_mvpred.h"
45 #include "mpegutils.h"
46 #include "rectangle.h"
52 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
54 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
56 int mb_x, int mb_y, int mb_intra, int mb_skipped)
58 H264Context *h = opaque;
59 H264SliceContext *sl = &h->slice_ctx[0];
63 sl->mb_xy = mb_x + mb_y * h->mb_stride;
64 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
66 /* FIXME: It is possible albeit uncommon that slice references
67 * differ between slices. We take the easy approach and ignore
68 * it for now. If this turns out to have any relevance in
69 * practice then correct remapping should be added. */
70 if (ref >= sl->ref_count[0])
72 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
74 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
75 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
76 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
77 assert(!FRAME_MBAFF(h));
78 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
81 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
84 AVCodecContext *avctx = h->avctx;
85 const AVFrame *src = &h->cur_pic.f;
86 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
87 int vshift = desc->log2_chroma_h;
88 const int field_pic = h->picture_structure != PICT_FRAME;
94 height = FFMIN(height, avctx->height - y);
96 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
99 if (avctx->draw_horiz_band) {
100 int offset[AV_NUM_DATA_POINTERS];
103 offset[0] = y * src->linesize[0];
105 offset[2] = (y >> vshift) * src->linesize[1];
106 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
111 avctx->draw_horiz_band(avctx, src, offset,
112 y, h->picture_structure, height);
117 * Check if the top & left blocks are available if needed and
118 * change the dc mode so it only uses the available blocks.
120 int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
122 static const int8_t top[12] = {
123 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
125 static const int8_t left[12] = {
126 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
130 if (!(sl->top_samples_available & 0x8000)) {
131 for (i = 0; i < 4; i++) {
132 int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
134 av_log(h->avctx, AV_LOG_ERROR,
135 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
136 status, sl->mb_x, sl->mb_y);
137 return AVERROR_INVALIDDATA;
139 sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
144 if ((sl->left_samples_available & 0x8888) != 0x8888) {
145 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
146 for (i = 0; i < 4; i++)
147 if (!(sl->left_samples_available & mask[i])) {
148 int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
150 av_log(h->avctx, AV_LOG_ERROR,
151 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
152 status, sl->mb_x, sl->mb_y);
153 return AVERROR_INVALIDDATA;
155 sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
161 } // FIXME cleanup like ff_h264_check_intra_pred_mode
164 * Check if the top & left blocks are available if needed and
165 * change the dc mode so it only uses the available blocks.
167 int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
168 int mode, int is_chroma)
170 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
171 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
174 av_log(h->avctx, AV_LOG_ERROR,
175 "out of range intra chroma pred mode at %d %d\n",
177 return AVERROR_INVALIDDATA;
180 if (!(sl->top_samples_available & 0x8000)) {
183 av_log(h->avctx, AV_LOG_ERROR,
184 "top block unavailable for requested intra mode at %d %d\n",
186 return AVERROR_INVALIDDATA;
190 if ((sl->left_samples_available & 0x8080) != 0x8080) {
192 if (is_chroma && (sl->left_samples_available & 0x8080)) {
193 // mad cow disease mode, aka MBAFF + constrained_intra_pred
194 mode = ALZHEIMER_DC_L0T_PRED8x8 +
195 (!(sl->left_samples_available & 0x8000)) +
196 2 * (mode == DC_128_PRED8x8);
199 av_log(h->avctx, AV_LOG_ERROR,
200 "left block unavailable for requested intra mode at %d %d\n",
202 return AVERROR_INVALIDDATA;
209 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
211 int *dst_length, int *consumed, int length)
216 // src[0]&0x80; // forbidden bit
217 h->nal_ref_idc = src[0] >> 5;
218 h->nal_unit_type = src[0] & 0x1F;
223 #define STARTCODE_TEST \
224 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
225 if (src[i + 2] != 3) { \
226 /* startcode, so we must be past the end */ \
232 #if HAVE_FAST_UNALIGNED
233 #define FIND_FIRST_ZERO \
234 if (i > 0 && !src[i]) \
240 for (i = 0; i + 1 < length; i += 9) {
241 if (!((~AV_RN64A(src + i) &
242 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
243 0x8000800080008080ULL))
250 for (i = 0; i + 1 < length; i += 5) {
251 if (!((~AV_RN32A(src + i) &
252 (AV_RN32A(src + i) - 0x01000101U)) &
261 for (i = 0; i + 1 < length; i += 2) {
264 if (i > 0 && src[i - 1] == 0)
270 if (i >= length - 1) { // no escaped 0
271 *dst_length = length;
272 *consumed = length + 1; // +1 for the header
276 av_fast_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size,
277 length + FF_INPUT_BUFFER_PADDING_SIZE);
278 dst = sl->rbsp_buffer;
285 while (si + 2 < length) {
286 // remove escapes (very rare 1:2^22)
287 if (src[si + 2] > 3) {
288 dst[di++] = src[si++];
289 dst[di++] = src[si++];
290 } else if (src[si] == 0 && src[si + 1] == 0) {
291 if (src[si + 2] == 3) { // escape
296 } else // next start code
300 dst[di++] = src[si++];
303 dst[di++] = src[si++];
306 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
309 *consumed = si + 1; // +1 for the header
310 /* FIXME store exact number of bits in the getbitcontext
311 * (it is needed for decoding) */
316 * Identify the exact end of the bitstream
317 * @return the length of the trailing, or 0 if damaged
319 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
324 tprintf(h->avctx, "rbsp trailing %X\n", v);
326 for (r = 1; r < 9; r++) {
334 void ff_h264_free_tables(H264Context *h, int free_rbsp)
338 av_freep(&h->intra4x4_pred_mode);
339 av_freep(&h->chroma_pred_mode_table);
340 av_freep(&h->cbp_table);
341 av_freep(&h->mvd_table[0]);
342 av_freep(&h->mvd_table[1]);
343 av_freep(&h->direct_table);
344 av_freep(&h->non_zero_count);
345 av_freep(&h->slice_table_base);
346 h->slice_table = NULL;
347 av_freep(&h->list_counts);
349 av_freep(&h->mb2b_xy);
350 av_freep(&h->mb2br_xy);
352 av_buffer_pool_uninit(&h->qscale_table_pool);
353 av_buffer_pool_uninit(&h->mb_type_pool);
354 av_buffer_pool_uninit(&h->motion_val_pool);
355 av_buffer_pool_uninit(&h->ref_index_pool);
357 if (free_rbsp && h->DPB) {
358 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
359 ff_h264_unref_picture(h, &h->DPB[i]);
362 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
363 h->DPB[i].needs_realloc = 1;
366 h->cur_pic_ptr = NULL;
368 for (i = 0; i < h->nb_slice_ctx; i++) {
369 H264SliceContext *sl = &h->slice_ctx[i];
371 av_freep(&sl->dc_val_base);
372 av_freep(&sl->er.mb_index2xy);
373 av_freep(&sl->er.error_status_table);
374 av_freep(&sl->er.er_temp_buffer);
376 av_freep(&sl->bipred_scratchpad);
377 av_freep(&sl->edge_emu_buffer);
378 av_freep(&sl->top_borders[0]);
379 av_freep(&sl->top_borders[1]);
381 sl->bipred_scratchpad_allocated = 0;
382 sl->edge_emu_buffer_allocated = 0;
383 sl->top_borders_allocated[0] = 0;
384 sl->top_borders_allocated[1] = 0;
387 av_freep(&sl->rbsp_buffer);
388 sl->rbsp_buffer_size = 0;
393 int ff_h264_alloc_tables(H264Context *h)
395 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
396 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
399 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
400 row_mb_num * 8 * sizeof(uint8_t), fail)
401 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
403 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
404 big_mb_num * 48 * sizeof(uint8_t), fail)
405 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
406 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
407 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
408 big_mb_num * sizeof(uint16_t), fail)
409 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
410 big_mb_num * sizeof(uint8_t), fail)
411 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
412 16 * row_mb_num * sizeof(uint8_t), fail);
413 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
414 16 * row_mb_num * sizeof(uint8_t), fail);
415 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
416 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
418 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
419 4 * big_mb_num * sizeof(uint8_t), fail);
420 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
421 big_mb_num * sizeof(uint8_t), fail)
423 memset(h->slice_table_base, -1,
424 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
425 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
427 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
428 big_mb_num * sizeof(uint32_t), fail);
429 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
430 big_mb_num * sizeof(uint32_t), fail);
431 for (y = 0; y < h->mb_height; y++)
432 for (x = 0; x < h->mb_width; x++) {
433 const int mb_xy = x + y * h->mb_stride;
434 const int b_xy = 4 * x + 4 * y * h->b_stride;
436 h->mb2b_xy[mb_xy] = b_xy;
437 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
440 if (!h->dequant4_coeff[0])
441 h264_init_dequant_tables(h);
444 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
447 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
448 av_frame_unref(&h->DPB[i].f);
449 av_frame_unref(&h->cur_pic.f);
455 ff_h264_free_tables(h, 1);
456 return AVERROR(ENOMEM);
461 * Allocate buffers which are not shared amongst multiple threads.
463 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
465 ERContext *er = &sl->er;
466 int mb_array_size = h->mb_height * h->mb_stride;
467 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
468 int c_size = h->mb_stride * (h->mb_height + 1);
469 int yc_size = y_size + 2 * c_size;
472 sl->ref_cache[0][scan8[5] + 1] =
473 sl->ref_cache[0][scan8[7] + 1] =
474 sl->ref_cache[0][scan8[13] + 1] =
475 sl->ref_cache[1][scan8[5] + 1] =
476 sl->ref_cache[1][scan8[7] + 1] =
477 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
479 if (CONFIG_ERROR_RESILIENCE) {
481 er->avctx = h->avctx;
482 er->decode_mb = h264_er_decode_mb;
484 er->quarter_sample = 1;
486 er->mb_num = h->mb_num;
487 er->mb_width = h->mb_width;
488 er->mb_height = h->mb_height;
489 er->mb_stride = h->mb_stride;
490 er->b8_stride = h->mb_width * 2 + 1;
492 // error resilience code looks cleaner with this
493 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
494 (h->mb_num + 1) * sizeof(int), fail);
496 for (y = 0; y < h->mb_height; y++)
497 for (x = 0; x < h->mb_width; x++)
498 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
500 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
501 h->mb_stride + h->mb_width;
503 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
504 mb_array_size * sizeof(uint8_t), fail);
506 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
507 h->mb_height * h->mb_stride, fail);
509 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
510 yc_size * sizeof(int16_t), fail);
511 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
512 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
513 er->dc_val[2] = er->dc_val[1] + c_size;
514 for (i = 0; i < yc_size; i++)
515 sl->dc_val_base[i] = 1024;
521 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
524 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
525 int parse_extradata);
527 int ff_h264_decode_extradata(H264Context *h)
529 AVCodecContext *avctx = h->avctx;
532 if (avctx->extradata[0] == 1) {
534 unsigned char *p = avctx->extradata;
538 if (avctx->extradata_size < 7) {
539 av_log(avctx, AV_LOG_ERROR,
540 "avcC %d too short\n", avctx->extradata_size);
541 return AVERROR_INVALIDDATA;
543 /* sps and pps in the avcC always have length coded with 2 bytes,
544 * so put a fake nal_length_size = 2 while parsing them */
545 h->nal_length_size = 2;
546 // Decode sps from avcC
547 cnt = *(p + 5) & 0x1f; // Number of sps
549 for (i = 0; i < cnt; i++) {
550 nalsize = AV_RB16(p) + 2;
551 if (p - avctx->extradata + nalsize > avctx->extradata_size)
552 return AVERROR_INVALIDDATA;
553 ret = decode_nal_units(h, p, nalsize, 1);
555 av_log(avctx, AV_LOG_ERROR,
556 "Decoding sps %d from avcC failed\n", i);
561 // Decode pps from avcC
562 cnt = *(p++); // Number of pps
563 for (i = 0; i < cnt; i++) {
564 nalsize = AV_RB16(p) + 2;
565 if (p - avctx->extradata + nalsize > avctx->extradata_size)
566 return AVERROR_INVALIDDATA;
567 ret = decode_nal_units(h, p, nalsize, 1);
569 av_log(avctx, AV_LOG_ERROR,
570 "Decoding pps %d from avcC failed\n", i);
575 // Store right nal length size that will be used to parse all other nals
576 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
579 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
586 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
588 H264Context *h = avctx->priv_data;
594 h->bit_depth_luma = 8;
595 h->chroma_format_idc = 1;
597 ff_h264dsp_init(&h->h264dsp, 8, 1);
598 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
599 ff_h264qpel_init(&h->h264qpel, 8);
600 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
602 h->dequant_coeff_pps = -1;
604 /* needed so that IDCT permutation is known early */
605 ff_videodsp_init(&h->vdsp, 8);
607 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
608 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
610 h->picture_structure = PICT_FRAME;
611 h->slice_context_count = 1;
612 h->workaround_bugs = avctx->workaround_bugs;
613 h->flags = avctx->flags;
616 // s->decode_mb = ff_h263_decode_mb;
617 if (!avctx->has_b_frames)
620 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
622 ff_h264_decode_init_vlc();
624 ff_init_cabac_states();
627 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
629 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
630 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
633 return AVERROR(ENOMEM);
636 for (i = 0; i < h->nb_slice_ctx; i++)
637 h->slice_ctx[i].h264 = h;
639 h->outputed_poc = h->next_outputed_poc = INT_MIN;
640 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
641 h->last_pocs[i] = INT_MIN;
642 h->prev_poc_msb = 1 << 16;
644 ff_h264_reset_sei(h);
645 h->recovery_frame = -1;
646 h->frame_recovered = 0;
647 if (avctx->codec_id == AV_CODEC_ID_H264) {
648 if (avctx->ticks_per_frame == 1)
649 h->avctx->framerate.num *= 2;
650 avctx->ticks_per_frame = 2;
653 if (avctx->extradata_size > 0 && avctx->extradata) {
654 ret = ff_h264_decode_extradata(h);
656 ff_h264_free_context(h);
661 if (h->sps.bitstream_restriction_flag &&
662 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
663 h->avctx->has_b_frames = h->sps.num_reorder_frames;
667 avctx->internal->allocate_progress = 1;
672 static int decode_init_thread_copy(AVCodecContext *avctx)
674 H264Context *h = avctx->priv_data;
677 if (!avctx->internal->is_copy)
679 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
680 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
682 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
683 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
686 return AVERROR(ENOMEM);
689 for (i = 0; i < h->nb_slice_ctx; i++)
690 h->slice_ctx[i].h264 = h;
693 h->context_initialized = 0;
699 * Run setup operations that must be run after slice header decoding.
700 * This includes finding the next displayed frame.
702 * @param h h264 master context
703 * @param setup_finished enough NALs have been read that we can call
704 * ff_thread_finish_setup()
706 static void decode_postinit(H264Context *h, int setup_finished)
708 H264Picture *out = h->cur_pic_ptr;
709 H264Picture *cur = h->cur_pic_ptr;
710 int i, pics, out_of_order, out_idx;
711 int invalid = 0, cnt = 0;
713 h->cur_pic_ptr->f.pict_type = h->pict_type;
715 if (h->next_output_pic)
718 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
719 /* FIXME: if we have two PAFF fields in one packet, we can't start
720 * the next thread here. If we have one field per packet, we can.
721 * The check in decode_nal_units() is not good enough to find this
722 * yet, so we assume the worst for now. */
723 // if (setup_finished)
724 // ff_thread_finish_setup(h->avctx);
728 cur->f.interlaced_frame = 0;
729 cur->f.repeat_pict = 0;
731 /* Signal interlacing information externally. */
732 /* Prioritize picture timing SEI information over used
733 * decoding process if it exists. */
735 if (h->sps.pic_struct_present_flag) {
736 switch (h->sei_pic_struct) {
737 case SEI_PIC_STRUCT_FRAME:
739 case SEI_PIC_STRUCT_TOP_FIELD:
740 case SEI_PIC_STRUCT_BOTTOM_FIELD:
741 cur->f.interlaced_frame = 1;
743 case SEI_PIC_STRUCT_TOP_BOTTOM:
744 case SEI_PIC_STRUCT_BOTTOM_TOP:
745 if (FIELD_OR_MBAFF_PICTURE(h))
746 cur->f.interlaced_frame = 1;
748 // try to flag soft telecine progressive
749 cur->f.interlaced_frame = h->prev_interlaced_frame;
751 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
752 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
753 /* Signal the possibility of telecined film externally
754 * (pic_struct 5,6). From these hints, let the applications
755 * decide if they apply deinterlacing. */
756 cur->f.repeat_pict = 1;
758 case SEI_PIC_STRUCT_FRAME_DOUBLING:
759 cur->f.repeat_pict = 2;
761 case SEI_PIC_STRUCT_FRAME_TRIPLING:
762 cur->f.repeat_pict = 4;
766 if ((h->sei_ct_type & 3) &&
767 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
768 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
770 /* Derive interlacing flag from used decoding process. */
771 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
773 h->prev_interlaced_frame = cur->f.interlaced_frame;
775 if (cur->field_poc[0] != cur->field_poc[1]) {
776 /* Derive top_field_first from field pocs. */
777 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
779 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
780 /* Use picture timing SEI information. Even if it is a
781 * information of a past frame, better than nothing. */
782 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
783 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
784 cur->f.top_field_first = 1;
786 cur->f.top_field_first = 0;
788 /* Most likely progressive */
789 cur->f.top_field_first = 0;
793 if (h->sei_frame_packing_present &&
794 h->frame_packing_arrangement_type >= 0 &&
795 h->frame_packing_arrangement_type <= 6 &&
796 h->content_interpretation_type > 0 &&
797 h->content_interpretation_type < 3) {
798 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
802 switch (h->frame_packing_arrangement_type) {
804 stereo->type = AV_STEREO3D_CHECKERBOARD;
807 stereo->type = AV_STEREO3D_COLUMNS;
810 stereo->type = AV_STEREO3D_LINES;
813 if (h->quincunx_subsampling)
814 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
816 stereo->type = AV_STEREO3D_SIDEBYSIDE;
819 stereo->type = AV_STEREO3D_TOPBOTTOM;
822 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
825 stereo->type = AV_STEREO3D_2D;
829 if (h->content_interpretation_type == 2)
830 stereo->flags = AV_STEREO3D_FLAG_INVERT;
833 if (h->sei_display_orientation_present &&
834 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
835 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
836 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
837 AV_FRAME_DATA_DISPLAYMATRIX,
838 sizeof(int32_t) * 9);
842 av_display_rotation_set((int32_t *)rotation->data, angle);
843 av_display_matrix_flip((int32_t *)rotation->data,
844 h->sei_hflip, h->sei_vflip);
847 // FIXME do something with unavailable reference frames
849 /* Sort B-frames into display order */
851 if (h->sps.bitstream_restriction_flag &&
852 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
853 h->avctx->has_b_frames = h->sps.num_reorder_frames;
857 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
858 !h->sps.bitstream_restriction_flag) {
859 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
864 while (h->delayed_pic[pics])
867 assert(pics <= MAX_DELAYED_PIC_COUNT);
869 h->delayed_pic[pics++] = cur;
870 if (cur->reference == 0)
871 cur->reference = DELAYED_PIC_REF;
873 /* Frame reordering. This code takes pictures from coding order and sorts
874 * them by their incremental POC value into display order. It supports POC
875 * gaps, MMCO reset codes and random resets.
876 * A "display group" can start either with a IDR frame (f.key_frame = 1),
877 * and/or can be closed down with a MMCO reset code. In sequences where
878 * there is no delay, we can't detect that (since the frame was already
879 * output to the user), so we also set h->mmco_reset to detect the MMCO
881 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
882 * we increase the delay between input and output. All frames affected by
883 * the lag (e.g. those that should have been output before another frame
884 * that we already returned to the user) will be dropped. This is a bug
885 * that we will fix later. */
886 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
887 cnt += out->poc < h->last_pocs[i];
888 invalid += out->poc == INT_MIN;
890 if (!h->mmco_reset && !cur->f.key_frame &&
891 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
894 h->delayed_pic[pics - 2]->mmco_reset = 2;
896 if (h->mmco_reset || cur->f.key_frame) {
897 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
898 h->last_pocs[i] = INT_MIN;
900 invalid = MAX_DELAYED_PIC_COUNT;
902 out = h->delayed_pic[0];
904 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
906 !h->delayed_pic[i - 1]->mmco_reset &&
907 !h->delayed_pic[i]->f.key_frame;
909 if (h->delayed_pic[i]->poc < out->poc) {
910 out = h->delayed_pic[i];
913 if (h->avctx->has_b_frames == 0 &&
914 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
915 h->next_outputed_poc = INT_MIN;
916 out_of_order = !out->f.key_frame && !h->mmco_reset &&
917 (out->poc < h->next_outputed_poc);
919 if (h->sps.bitstream_restriction_flag &&
920 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
921 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
922 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
923 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
924 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
927 } else if (h->low_delay &&
928 ((h->next_outputed_poc != INT_MIN &&
929 out->poc > h->next_outputed_poc + 2) ||
930 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
932 h->avctx->has_b_frames++;
935 if (pics > h->avctx->has_b_frames) {
936 out->reference &= ~DELAYED_PIC_REF;
937 // for frame threading, the owner must be the second field's thread or
938 // else the first thread can release the picture and reuse it unsafely
939 for (i = out_idx; h->delayed_pic[i]; i++)
940 h->delayed_pic[i] = h->delayed_pic[i + 1];
942 memmove(h->last_pocs, &h->last_pocs[1],
943 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
944 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
945 if (!out_of_order && pics > h->avctx->has_b_frames) {
946 h->next_output_pic = out;
947 if (out->mmco_reset) {
949 h->next_outputed_poc = out->poc;
950 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
952 h->next_outputed_poc = INT_MIN;
955 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
956 h->next_outputed_poc = INT_MIN;
958 h->next_outputed_poc = out->poc;
963 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
966 if (h->next_output_pic) {
967 if (h->next_output_pic->recovered) {
968 // We have reached an recovery point and all frames after it in
969 // display order are "recovered".
970 h->frame_recovered |= FRAME_RECOVERED_SEI;
972 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
975 if (setup_finished && !h->avctx->hwaccel)
976 ff_thread_finish_setup(h->avctx);
979 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
982 int luma_def, chroma_def;
985 sl->use_weight_chroma = 0;
986 sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
987 if (h->sps.chroma_format_idc)
988 sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
989 luma_def = 1 << sl->luma_log2_weight_denom;
990 chroma_def = 1 << sl->chroma_log2_weight_denom;
992 for (list = 0; list < 2; list++) {
993 sl->luma_weight_flag[list] = 0;
994 sl->chroma_weight_flag[list] = 0;
995 for (i = 0; i < sl->ref_count[list]; i++) {
996 int luma_weight_flag, chroma_weight_flag;
998 luma_weight_flag = get_bits1(&sl->gb);
999 if (luma_weight_flag) {
1000 sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
1001 sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
1002 if (sl->luma_weight[i][list][0] != luma_def ||
1003 sl->luma_weight[i][list][1] != 0) {
1005 sl->luma_weight_flag[list] = 1;
1008 sl->luma_weight[i][list][0] = luma_def;
1009 sl->luma_weight[i][list][1] = 0;
1012 if (h->sps.chroma_format_idc) {
1013 chroma_weight_flag = get_bits1(&sl->gb);
1014 if (chroma_weight_flag) {
1016 for (j = 0; j < 2; j++) {
1017 sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
1018 sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
1019 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1020 sl->chroma_weight[i][list][j][1] != 0) {
1021 sl->use_weight_chroma = 1;
1022 sl->chroma_weight_flag[list] = 1;
1027 for (j = 0; j < 2; j++) {
1028 sl->chroma_weight[i][list][j][0] = chroma_def;
1029 sl->chroma_weight[i][list][j][1] = 0;
1034 if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
1037 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1042 * instantaneous decoder refresh.
1044 static void idr(H264Context *h)
1046 ff_h264_remove_all_refs(h);
1048 h->prev_frame_num_offset =
1050 h->prev_poc_lsb = 0;
1053 /* forget old pics after a seek */
1054 void ff_h264_flush_change(H264Context *h)
1057 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1058 h->last_pocs[i] = INT_MIN;
1059 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1060 h->prev_interlaced_frame = 1;
1063 h->cur_pic_ptr->reference = 0;
1065 ff_h264_reset_sei(h);
1066 h->recovery_frame = -1;
1067 h->frame_recovered = 0;
1070 /* forget old pics after a seek */
1071 static void flush_dpb(AVCodecContext *avctx)
1073 H264Context *h = avctx->priv_data;
1076 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1078 ff_h264_flush_change(h);
1081 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1082 ff_h264_unref_picture(h, &h->DPB[i]);
1083 h->cur_pic_ptr = NULL;
1084 ff_h264_unref_picture(h, &h->cur_pic);
1088 ff_h264_free_tables(h, 1);
1089 h->context_initialized = 0;
1092 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1094 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1097 h->frame_num_offset = h->prev_frame_num_offset;
1098 if (h->frame_num < h->prev_frame_num)
1099 h->frame_num_offset += max_frame_num;
1101 if (h->sps.poc_type == 0) {
1102 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1104 if (h->poc_lsb < h->prev_poc_lsb &&
1105 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1106 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1107 else if (h->poc_lsb > h->prev_poc_lsb &&
1108 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1109 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1111 h->poc_msb = h->prev_poc_msb;
1113 field_poc[1] = h->poc_msb + h->poc_lsb;
1114 if (h->picture_structure == PICT_FRAME)
1115 field_poc[1] += h->delta_poc_bottom;
1116 } else if (h->sps.poc_type == 1) {
1117 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1120 if (h->sps.poc_cycle_length != 0)
1121 abs_frame_num = h->frame_num_offset + h->frame_num;
1125 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1128 expected_delta_per_poc_cycle = 0;
1129 for (i = 0; i < h->sps.poc_cycle_length; i++)
1130 // FIXME integrate during sps parse
1131 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1133 if (abs_frame_num > 0) {
1134 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1135 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1137 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1138 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1139 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1143 if (h->nal_ref_idc == 0)
1144 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1146 field_poc[0] = expectedpoc + h->delta_poc[0];
1147 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1149 if (h->picture_structure == PICT_FRAME)
1150 field_poc[1] += h->delta_poc[1];
1152 int poc = 2 * (h->frame_num_offset + h->frame_num);
1154 if (!h->nal_ref_idc)
1161 if (h->picture_structure != PICT_BOTTOM_FIELD)
1162 pic_field_poc[0] = field_poc[0];
1163 if (h->picture_structure != PICT_TOP_FIELD)
1164 pic_field_poc[1] = field_poc[1];
1165 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1171 * Compute profile from profile_idc and constraint_set?_flags.
1175 * @return profile as defined by FF_PROFILE_H264_*
1177 int ff_h264_get_profile(SPS *sps)
1179 int profile = sps->profile_idc;
1181 switch (sps->profile_idc) {
1182 case FF_PROFILE_H264_BASELINE:
1183 // constraint_set1_flag set to 1
1184 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1186 case FF_PROFILE_H264_HIGH_10:
1187 case FF_PROFILE_H264_HIGH_422:
1188 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1189 // constraint_set3_flag set to 1
1190 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1197 int ff_h264_set_parameter_from_sps(H264Context *h)
1199 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1200 (h->sps.bitstream_restriction_flag &&
1201 !h->sps.num_reorder_frames)) {
1202 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1203 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1204 "Reenabling low delay requires a codec flush.\n");
1209 if (h->avctx->has_b_frames < 2)
1210 h->avctx->has_b_frames = !h->low_delay;
1212 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1213 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1214 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
1215 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1216 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1217 h->pixel_shift = h->sps.bit_depth_luma > 8;
1219 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1220 h->sps.chroma_format_idc);
1221 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1222 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1223 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1224 h->sps.chroma_format_idc);
1225 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1227 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1228 h->sps.bit_depth_luma);
1229 return AVERROR_INVALIDDATA;
1235 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1237 int ref_count[2], list_count;
1238 int num_ref_idx_active_override_flag, max_refs;
1240 // set defaults, might be overridden a few lines later
1241 ref_count[0] = h->pps.ref_count[0];
1242 ref_count[1] = h->pps.ref_count[1];
1244 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1245 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1246 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1247 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1249 if (num_ref_idx_active_override_flag) {
1250 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1251 if (ref_count[0] < 1)
1252 return AVERROR_INVALIDDATA;
1253 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1254 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1255 if (ref_count[1] < 1)
1256 return AVERROR_INVALIDDATA;
1260 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1266 ref_count[0] = ref_count[1] = 0;
1269 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1271 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1272 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1273 sl->ref_count[0] = sl->ref_count[1] = 0;
1274 return AVERROR_INVALIDDATA;
1277 if (list_count != sl->list_count ||
1278 ref_count[0] != sl->ref_count[0] ||
1279 ref_count[1] != sl->ref_count[1]) {
1280 sl->ref_count[0] = ref_count[0];
1281 sl->ref_count[1] = ref_count[1];
1282 sl->list_count = list_count;
1289 static int find_start_code(const uint8_t *buf, int buf_size,
1290 int buf_index, int next_avc)
1292 // start code prefix search
1293 for (; buf_index + 3 < next_avc; buf_index++)
1294 // This should always succeed in the first iteration.
1295 if (buf[buf_index] == 0 &&
1296 buf[buf_index + 1] == 0 &&
1297 buf[buf_index + 2] == 1)
1300 if (buf_index + 3 >= buf_size)
1303 return buf_index + 3;
1306 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1307 int buf_size, int *buf_index)
1311 if (*buf_index >= buf_size - h->nal_length_size)
1314 for (i = 0; i < h->nal_length_size; i++)
1315 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1316 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1317 av_log(h->avctx, AV_LOG_ERROR,
1318 "AVC: nal size %d\n", nalsize);
1324 static int get_bit_length(H264Context *h, const uint8_t *buf,
1325 const uint8_t *ptr, int dst_length,
1326 int i, int next_avc)
1328 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1329 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1330 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1331 h->workaround_bugs |= FF_BUG_TRUNCATED;
1333 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1334 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1340 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1343 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1345 int next_avc = h->is_avc ? 0 : buf_size;
1348 int nals_needed = 0;
1353 int dst_length, bit_length, consumed;
1356 if (buf_index >= next_avc) {
1357 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1360 next_avc = buf_index + nalsize;
1362 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1363 if (buf_index >= buf_size)
1367 ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1368 next_avc - buf_index);
1370 if (!ptr || dst_length < 0)
1371 return AVERROR_INVALIDDATA;
1373 buf_index += consumed;
1375 bit_length = get_bit_length(h, buf, ptr, dst_length,
1376 buf_index, next_avc);
1379 /* packets can sometimes contain multiple PPS/SPS,
1380 * e.g. two PAFF field pictures in one packet, or a demuxer
1381 * which splits NALs strangely if so, when frame threading we
1382 * can't start the next thread until we've read all of them */
1383 switch (h->nal_unit_type) {
1386 nals_needed = nal_index;
1391 init_get_bits(&gb, ptr, bit_length);
1392 if (!get_ue_golomb(&gb))
1393 nals_needed = nal_index;
1400 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1401 int parse_extradata)
1403 AVCodecContext *const avctx = h->avctx;
1404 H264SliceContext *sl;
1406 unsigned context_count;
1408 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1412 h->max_contexts = h->slice_context_count;
1413 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1414 h->current_slice = 0;
1415 if (!h->first_field)
1416 h->cur_pic_ptr = NULL;
1417 ff_h264_reset_sei(h);
1420 if (avctx->active_thread_type & FF_THREAD_FRAME)
1421 nals_needed = get_last_needed_nal(h, buf, buf_size);
1426 next_avc = h->is_avc ? 0 : buf_size;
1436 if (buf_index >= next_avc) {
1437 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1440 next_avc = buf_index + nalsize;
1442 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1443 if (buf_index >= buf_size)
1445 if (buf_index >= next_avc)
1449 sl = &h->slice_ctx[context_count];
1451 ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1452 &consumed, next_avc - buf_index);
1453 if (!ptr || dst_length < 0) {
1458 bit_length = get_bit_length(h, buf, ptr, dst_length,
1459 buf_index + consumed, next_avc);
1461 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1462 av_log(h->avctx, AV_LOG_DEBUG,
1463 "NAL %d at %d/%d length %d\n",
1464 h->nal_unit_type, buf_index, buf_size, dst_length);
1466 if (h->is_avc && (nalsize != consumed) && nalsize)
1467 av_log(h->avctx, AV_LOG_DEBUG,
1468 "AVC: Consumed only %d bytes instead of %d\n",
1471 buf_index += consumed;
1474 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1475 h->nal_ref_idc == 0 &&
1476 h->nal_unit_type != NAL_SEI)
1480 /* Ignore every NAL unit type except PPS and SPS during extradata
1481 * parsing. Decoding slices is not possible in codec init
1483 if (parse_extradata && HAVE_THREADS &&
1484 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1485 (h->nal_unit_type != NAL_PPS &&
1486 h->nal_unit_type != NAL_SPS)) {
1487 if (h->nal_unit_type < NAL_AUD ||
1488 h->nal_unit_type > NAL_AUXILIARY_SLICE)
1489 av_log(avctx, AV_LOG_INFO,
1490 "Ignoring NAL unit %d during extradata parsing\n",
1492 h->nal_unit_type = NAL_FF_IGNORE;
1495 switch (h->nal_unit_type) {
1497 if (h->nal_unit_type != NAL_IDR_SLICE) {
1498 av_log(h->avctx, AV_LOG_ERROR,
1499 "Invalid mix of idr and non-idr slices\n");
1503 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1505 init_get_bits(&sl->gb, ptr, bit_length);
1507 if ((err = ff_h264_decode_slice_header(h, sl)))
1510 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1511 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1512 ((1 << h->sps.log2_max_frame_num) - 1);
1515 h->cur_pic_ptr->f.key_frame |=
1516 (h->nal_unit_type == NAL_IDR_SLICE) ||
1517 (h->sei_recovery_frame_cnt >= 0);
1519 if (h->nal_unit_type == NAL_IDR_SLICE ||
1520 h->recovery_frame == h->frame_num) {
1521 h->recovery_frame = -1;
1522 h->cur_pic_ptr->recovered = 1;
1524 // If we have an IDR, all frames after it in decoded order are
1526 if (h->nal_unit_type == NAL_IDR_SLICE)
1527 h->frame_recovered |= FRAME_RECOVERED_IDR;
1528 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1530 if (h->current_slice == 1) {
1531 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1532 decode_postinit(h, nal_index >= nals_needed);
1534 if (h->avctx->hwaccel &&
1535 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1539 if (sl->redundant_pic_count == 0 &&
1540 (avctx->skip_frame < AVDISCARD_NONREF ||
1542 (avctx->skip_frame < AVDISCARD_BIDIR ||
1543 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1544 (avctx->skip_frame < AVDISCARD_NONKEY ||
1545 sl->slice_type_nos == AV_PICTURE_TYPE_I) &&
1546 avctx->skip_frame < AVDISCARD_ALL) {
1547 if (avctx->hwaccel) {
1548 ret = avctx->hwaccel->decode_slice(avctx,
1549 &buf[buf_index - consumed],
1560 avpriv_request_sample(avctx, "data partitioning");
1561 ret = AVERROR(ENOSYS);
1565 init_get_bits(&h->gb, ptr, bit_length);
1566 ret = ff_h264_decode_sei(h);
1567 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1571 init_get_bits(&h->gb, ptr, bit_length);
1572 ret = ff_h264_decode_seq_parameter_set(h);
1573 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
1574 av_log(h->avctx, AV_LOG_DEBUG,
1575 "SPS decoding failure, trying again with the complete NAL\n");
1576 init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
1578 ff_h264_decode_seq_parameter_set(h);
1581 ret = ff_h264_set_parameter_from_sps(h);
1587 init_get_bits(&h->gb, ptr, bit_length);
1588 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1589 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1593 case NAL_END_SEQUENCE:
1594 case NAL_END_STREAM:
1595 case NAL_FILLER_DATA:
1597 case NAL_AUXILIARY_SLICE:
1602 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1603 h->nal_unit_type, bit_length);
1606 if (context_count == h->max_contexts) {
1607 ret = ff_h264_execute_decode_slices(h, context_count);
1608 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1614 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1615 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1616 } else if (err == 1) {
1617 /* Slice could not be decoded in parallel mode, restart. Note
1618 * that rbsp_buffer is not transferred, but since we no longer
1619 * run in parallel mode this should not be an issue. */
1620 sl = &h->slice_ctx[0];
1625 if (context_count) {
1626 ret = ff_h264_execute_decode_slices(h, context_count);
1627 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1634 if (h->cur_pic_ptr && !h->droppable) {
1635 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1636 h->picture_structure == PICT_BOTTOM_FIELD);
1639 return (ret < 0) ? ret : buf_index;
1643 * Return the number of bytes consumed for building the current frame.
1645 static int get_consumed_bytes(int pos, int buf_size)
1648 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1649 if (pos + 10 > buf_size)
1650 pos = buf_size; // oops ;)
1655 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1658 int ret = av_frame_ref(dst, src);
1665 for (i = 0; i < 3; i++) {
1666 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1667 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1668 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1669 (h->sps.crop_top >> vshift) * dst->linesize[i];
1670 dst->data[i] += off;
1675 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1676 int *got_frame, AVPacket *avpkt)
1678 const uint8_t *buf = avpkt->data;
1679 int buf_size = avpkt->size;
1680 H264Context *h = avctx->priv_data;
1681 AVFrame *pict = data;
1685 h->flags = avctx->flags;
1687 /* end of stream, output what is still in the buffers */
1689 if (buf_size == 0) {
1693 h->cur_pic_ptr = NULL;
1695 // FIXME factorize this with the output code below
1696 out = h->delayed_pic[0];
1699 h->delayed_pic[i] &&
1700 !h->delayed_pic[i]->f.key_frame &&
1701 !h->delayed_pic[i]->mmco_reset;
1703 if (h->delayed_pic[i]->poc < out->poc) {
1704 out = h->delayed_pic[i];
1708 for (i = out_idx; h->delayed_pic[i]; i++)
1709 h->delayed_pic[i] = h->delayed_pic[i + 1];
1712 ret = output_frame(h, pict, &out->f);
1721 buf_index = decode_nal_units(h, buf, buf_size, 0);
1723 return AVERROR_INVALIDDATA;
1725 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1730 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1731 if (avctx->skip_frame >= AVDISCARD_NONREF)
1733 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1734 return AVERROR_INVALIDDATA;
1737 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1738 (h->mb_y >= h->mb_height && h->mb_height)) {
1739 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1740 decode_postinit(h, 1);
1742 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1745 if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
1746 h->next_output_pic->recovered)) {
1747 if (!h->next_output_pic->recovered)
1748 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1750 ret = output_frame(h, pict, &h->next_output_pic->f);
1757 assert(pict->buf[0] || !*got_frame);
1759 return get_consumed_bytes(buf_index, buf_size);
1762 av_cold void ff_h264_free_context(H264Context *h)
1766 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1768 av_freep(&h->slice_ctx);
1769 h->nb_slice_ctx = 0;
1771 for (i = 0; i < MAX_SPS_COUNT; i++)
1772 av_freep(h->sps_buffers + i);
1774 for (i = 0; i < MAX_PPS_COUNT; i++)
1775 av_freep(h->pps_buffers + i);
1778 static av_cold int h264_decode_end(AVCodecContext *avctx)
1780 H264Context *h = avctx->priv_data;
1782 ff_h264_free_context(h);
1784 ff_h264_unref_picture(h, &h->cur_pic);
1789 static const AVProfile profiles[] = {
1790 { FF_PROFILE_H264_BASELINE, "Baseline" },
1791 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1792 { FF_PROFILE_H264_MAIN, "Main" },
1793 { FF_PROFILE_H264_EXTENDED, "Extended" },
1794 { FF_PROFILE_H264_HIGH, "High" },
1795 { FF_PROFILE_H264_HIGH_10, "High 10" },
1796 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1797 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1798 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1799 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1800 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1801 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1802 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1803 { FF_PROFILE_UNKNOWN },
1806 AVCodec ff_h264_decoder = {
1808 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1809 .type = AVMEDIA_TYPE_VIDEO,
1810 .id = AV_CODEC_ID_H264,
1811 .priv_data_size = sizeof(H264Context),
1812 .init = ff_h264_decode_init,
1813 .close = h264_decode_end,
1814 .decode = h264_decode_frame,
1815 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1816 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1817 CODEC_CAP_FRAME_THREADS,
1819 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1820 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1821 .profiles = NULL_IF_CONFIG_SMALL(profiles),