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 *cur = &h->cur_pic.f;
86 AVFrame *last = sl->ref_list[0][0].f.data[0] ? &sl->ref_list[0][0].f : NULL;
87 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
88 int vshift = desc->log2_chroma_h;
89 const int field_pic = h->picture_structure != PICT_FRAME;
95 height = FFMIN(height, avctx->height - y);
97 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
100 if (avctx->draw_horiz_band) {
102 int offset[AV_NUM_DATA_POINTERS];
105 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
106 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
113 offset[0] = y * src->linesize[0];
115 offset[2] = (y >> vshift) * src->linesize[1];
116 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
121 avctx->draw_horiz_band(avctx, src, offset,
122 y, h->picture_structure, height);
127 * Check if the top & left blocks are available if needed and
128 * change the dc mode so it only uses the available blocks.
130 int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
132 static const int8_t top[12] = {
133 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
135 static const int8_t left[12] = {
136 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
140 if (!(sl->top_samples_available & 0x8000)) {
141 for (i = 0; i < 4; i++) {
142 int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
144 av_log(h->avctx, AV_LOG_ERROR,
145 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
146 status, sl->mb_x, sl->mb_y);
147 return AVERROR_INVALIDDATA;
149 sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
154 if ((sl->left_samples_available & 0x8888) != 0x8888) {
155 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
156 for (i = 0; i < 4; i++)
157 if (!(sl->left_samples_available & mask[i])) {
158 int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
160 av_log(h->avctx, AV_LOG_ERROR,
161 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
162 status, sl->mb_x, sl->mb_y);
163 return AVERROR_INVALIDDATA;
165 sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
171 } // FIXME cleanup like ff_h264_check_intra_pred_mode
174 * Check if the top & left blocks are available if needed and
175 * change the dc mode so it only uses the available blocks.
177 int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
178 int mode, int is_chroma)
180 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
181 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
184 av_log(h->avctx, AV_LOG_ERROR,
185 "out of range intra chroma pred mode at %d %d\n",
187 return AVERROR_INVALIDDATA;
190 if (!(sl->top_samples_available & 0x8000)) {
193 av_log(h->avctx, AV_LOG_ERROR,
194 "top block unavailable for requested intra mode at %d %d\n",
196 return AVERROR_INVALIDDATA;
200 if ((sl->left_samples_available & 0x8080) != 0x8080) {
202 if (is_chroma && (sl->left_samples_available & 0x8080)) {
203 // mad cow disease mode, aka MBAFF + constrained_intra_pred
204 mode = ALZHEIMER_DC_L0T_PRED8x8 +
205 (!(sl->left_samples_available & 0x8000)) +
206 2 * (mode == DC_128_PRED8x8);
209 av_log(h->avctx, AV_LOG_ERROR,
210 "left block unavailable for requested intra mode at %d %d\n",
212 return AVERROR_INVALIDDATA;
219 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
220 int *dst_length, int *consumed, int length)
225 // src[0]&0x80; // forbidden bit
226 h->nal_ref_idc = src[0] >> 5;
227 h->nal_unit_type = src[0] & 0x1F;
232 #define STARTCODE_TEST \
233 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
234 if (src[i + 2] != 3) { \
235 /* startcode, so we must be past the end */ \
241 #if HAVE_FAST_UNALIGNED
242 #define FIND_FIRST_ZERO \
243 if (i > 0 && !src[i]) \
249 for (i = 0; i + 1 < length; i += 9) {
250 if (!((~AV_RN64A(src + i) &
251 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
252 0x8000800080008080ULL))
259 for (i = 0; i + 1 < length; i += 5) {
260 if (!((~AV_RN32A(src + i) &
261 (AV_RN32A(src + i) - 0x01000101U)) &
270 for (i = 0; i + 1 < length; i += 2) {
273 if (i > 0 && src[i - 1] == 0)
279 if (i >= length - 1) { // no escaped 0
280 *dst_length = length;
281 *consumed = length + 1; // +1 for the header
285 av_fast_malloc(&h->rbsp_buffer, &h->rbsp_buffer_size,
286 length + FF_INPUT_BUFFER_PADDING_SIZE);
287 dst = h->rbsp_buffer;
294 while (si + 2 < length) {
295 // remove escapes (very rare 1:2^22)
296 if (src[si + 2] > 3) {
297 dst[di++] = src[si++];
298 dst[di++] = src[si++];
299 } else if (src[si] == 0 && src[si + 1] == 0) {
300 if (src[si + 2] == 3) { // escape
305 } else // next start code
309 dst[di++] = src[si++];
312 dst[di++] = src[si++];
315 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
318 *consumed = si + 1; // +1 for the header
319 /* FIXME store exact number of bits in the getbitcontext
320 * (it is needed for decoding) */
325 * Identify the exact end of the bitstream
326 * @return the length of the trailing, or 0 if damaged
328 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
333 tprintf(h->avctx, "rbsp trailing %X\n", v);
335 for (r = 1; r < 9; r++) {
343 void ff_h264_free_tables(H264Context *h, int free_rbsp)
348 av_freep(&h->intra4x4_pred_mode);
349 av_freep(&h->chroma_pred_mode_table);
350 av_freep(&h->cbp_table);
351 av_freep(&h->mvd_table[0]);
352 av_freep(&h->mvd_table[1]);
353 av_freep(&h->direct_table);
354 av_freep(&h->non_zero_count);
355 av_freep(&h->slice_table_base);
356 h->slice_table = NULL;
357 av_freep(&h->list_counts);
359 av_freep(&h->mb2b_xy);
360 av_freep(&h->mb2br_xy);
362 av_buffer_pool_uninit(&h->qscale_table_pool);
363 av_buffer_pool_uninit(&h->mb_type_pool);
364 av_buffer_pool_uninit(&h->motion_val_pool);
365 av_buffer_pool_uninit(&h->ref_index_pool);
367 if (free_rbsp && h->DPB) {
368 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
369 ff_h264_unref_picture(h, &h->DPB[i]);
372 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
373 h->DPB[i].needs_realloc = 1;
376 h->cur_pic_ptr = NULL;
378 for (i = 0; i < H264_MAX_THREADS; i++) {
379 hx = h->thread_context[i];
382 av_freep(&hx->dc_val_base);
383 av_freep(&hx->er.mb_index2xy);
384 av_freep(&hx->er.error_status_table);
385 av_freep(&hx->er.er_temp_buffer);
388 av_freep(&hx->rbsp_buffer);
389 hx->rbsp_buffer_size = 0;
392 av_freep(&h->thread_context[i]);
395 for (i = 0; i < h->nb_slice_ctx; i++) {
396 H264SliceContext *sl = &h->slice_ctx[i];
398 av_freep(&sl->bipred_scratchpad);
399 av_freep(&sl->edge_emu_buffer);
400 av_freep(&sl->top_borders[0]);
401 av_freep(&sl->top_borders[1]);
403 sl->bipred_scratchpad_allocated = 0;
404 sl->edge_emu_buffer_allocated = 0;
405 sl->top_borders_allocated[0] = 0;
406 sl->top_borders_allocated[1] = 0;
410 int ff_h264_alloc_tables(H264Context *h)
412 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
413 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
416 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
417 row_mb_num * 8 * sizeof(uint8_t), fail)
418 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
420 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
421 big_mb_num * 48 * sizeof(uint8_t), fail)
422 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
423 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
424 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
425 big_mb_num * sizeof(uint16_t), fail)
426 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
427 big_mb_num * sizeof(uint8_t), fail)
428 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
429 16 * row_mb_num * sizeof(uint8_t), fail);
430 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
431 16 * row_mb_num * sizeof(uint8_t), fail);
432 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
433 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
435 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
436 4 * big_mb_num * sizeof(uint8_t), fail);
437 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
438 big_mb_num * sizeof(uint8_t), fail)
440 memset(h->slice_table_base, -1,
441 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
442 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
444 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
445 big_mb_num * sizeof(uint32_t), fail);
446 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
447 big_mb_num * sizeof(uint32_t), fail);
448 for (y = 0; y < h->mb_height; y++)
449 for (x = 0; x < h->mb_width; x++) {
450 const int mb_xy = x + y * h->mb_stride;
451 const int b_xy = 4 * x + 4 * y * h->b_stride;
453 h->mb2b_xy[mb_xy] = b_xy;
454 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
457 if (!h->dequant4_coeff[0])
458 h264_init_dequant_tables(h);
461 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
464 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
465 av_frame_unref(&h->DPB[i].f);
466 av_frame_unref(&h->cur_pic.f);
472 ff_h264_free_tables(h, 1);
473 return AVERROR(ENOMEM);
478 * Allocate buffers which are not shared amongst multiple threads.
480 int ff_h264_context_init(H264Context *h)
482 ERContext *er = &h->er;
483 int mb_array_size = h->mb_height * h->mb_stride;
484 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
485 int c_size = h->mb_stride * (h->mb_height + 1);
486 int yc_size = y_size + 2 * c_size;
489 for (i = 0; i < h->nb_slice_ctx; i++) {
490 h->slice_ctx[i].ref_cache[0][scan8[5] + 1] =
491 h->slice_ctx[i].ref_cache[0][scan8[7] + 1] =
492 h->slice_ctx[i].ref_cache[0][scan8[13] + 1] =
493 h->slice_ctx[i].ref_cache[1][scan8[5] + 1] =
494 h->slice_ctx[i].ref_cache[1][scan8[7] + 1] =
495 h->slice_ctx[i].ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
498 if (CONFIG_ERROR_RESILIENCE) {
500 er->avctx = h->avctx;
501 er->decode_mb = h264_er_decode_mb;
503 er->quarter_sample = 1;
505 er->mb_num = h->mb_num;
506 er->mb_width = h->mb_width;
507 er->mb_height = h->mb_height;
508 er->mb_stride = h->mb_stride;
509 er->b8_stride = h->mb_width * 2 + 1;
511 // error resilience code looks cleaner with this
512 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
513 (h->mb_num + 1) * sizeof(int), fail);
515 for (y = 0; y < h->mb_height; y++)
516 for (x = 0; x < h->mb_width; x++)
517 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
519 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
520 h->mb_stride + h->mb_width;
522 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
523 mb_array_size * sizeof(uint8_t), fail);
525 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
526 h->mb_height * h->mb_stride, fail);
528 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,
529 yc_size * sizeof(int16_t), fail);
530 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
531 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
532 er->dc_val[2] = er->dc_val[1] + c_size;
533 for (i = 0; i < yc_size; i++)
534 h->dc_val_base[i] = 1024;
540 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
543 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
544 int parse_extradata);
546 int ff_h264_decode_extradata(H264Context *h)
548 AVCodecContext *avctx = h->avctx;
551 if (avctx->extradata[0] == 1) {
553 unsigned char *p = avctx->extradata;
557 if (avctx->extradata_size < 7) {
558 av_log(avctx, AV_LOG_ERROR,
559 "avcC %d too short\n", avctx->extradata_size);
560 return AVERROR_INVALIDDATA;
562 /* sps and pps in the avcC always have length coded with 2 bytes,
563 * so put a fake nal_length_size = 2 while parsing them */
564 h->nal_length_size = 2;
565 // Decode sps from avcC
566 cnt = *(p + 5) & 0x1f; // Number of sps
568 for (i = 0; i < cnt; i++) {
569 nalsize = AV_RB16(p) + 2;
570 if (p - avctx->extradata + nalsize > avctx->extradata_size)
571 return AVERROR_INVALIDDATA;
572 ret = decode_nal_units(h, p, nalsize, 1);
574 av_log(avctx, AV_LOG_ERROR,
575 "Decoding sps %d from avcC failed\n", i);
580 // Decode pps from avcC
581 cnt = *(p++); // Number of pps
582 for (i = 0; i < cnt; i++) {
583 nalsize = AV_RB16(p) + 2;
584 if (p - avctx->extradata + nalsize > avctx->extradata_size)
585 return AVERROR_INVALIDDATA;
586 ret = decode_nal_units(h, p, nalsize, 1);
588 av_log(avctx, AV_LOG_ERROR,
589 "Decoding pps %d from avcC failed\n", i);
594 // Store right nal length size that will be used to parse all other nals
595 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
598 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
605 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
607 H264Context *h = avctx->priv_data;
613 h->bit_depth_luma = 8;
614 h->chroma_format_idc = 1;
616 ff_h264dsp_init(&h->h264dsp, 8, 1);
617 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
618 ff_h264qpel_init(&h->h264qpel, 8);
619 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
621 h->dequant_coeff_pps = -1;
623 /* needed so that IDCT permutation is known early */
624 ff_videodsp_init(&h->vdsp, 8);
626 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
627 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
629 h->picture_structure = PICT_FRAME;
630 h->slice_context_count = 1;
631 h->workaround_bugs = avctx->workaround_bugs;
632 h->flags = avctx->flags;
635 // s->decode_mb = ff_h263_decode_mb;
636 if (!avctx->has_b_frames)
639 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
641 ff_h264_decode_init_vlc();
643 ff_init_cabac_states();
646 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
648 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
649 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
652 return AVERROR(ENOMEM);
655 h->thread_context[0] = h;
656 for (i = 0; i < h->nb_slice_ctx; i++)
657 h->slice_ctx[i].h264 = h->thread_context[0];
659 h->outputed_poc = h->next_outputed_poc = INT_MIN;
660 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
661 h->last_pocs[i] = INT_MIN;
662 h->prev_poc_msb = 1 << 16;
664 ff_h264_reset_sei(h);
665 h->recovery_frame = -1;
666 h->frame_recovered = 0;
667 if (avctx->codec_id == AV_CODEC_ID_H264) {
668 if (avctx->ticks_per_frame == 1)
669 h->avctx->framerate.num *= 2;
670 avctx->ticks_per_frame = 2;
673 if (avctx->extradata_size > 0 && avctx->extradata) {
674 ret = ff_h264_decode_extradata(h);
676 ff_h264_free_context(h);
681 if (h->sps.bitstream_restriction_flag &&
682 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
683 h->avctx->has_b_frames = h->sps.num_reorder_frames;
687 avctx->internal->allocate_progress = 1;
692 static int decode_init_thread_copy(AVCodecContext *avctx)
694 H264Context *h = avctx->priv_data;
697 if (!avctx->internal->is_copy)
699 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
700 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
702 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
703 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
706 return AVERROR(ENOMEM);
709 for (i = 0; i < h->nb_slice_ctx; i++)
710 h->slice_ctx[i].h264 = h;
713 h->rbsp_buffer = NULL;
714 h->rbsp_buffer_size = 0;
715 h->context_initialized = 0;
721 * Run setup operations that must be run after slice header decoding.
722 * This includes finding the next displayed frame.
724 * @param h h264 master context
725 * @param setup_finished enough NALs have been read that we can call
726 * ff_thread_finish_setup()
728 static void decode_postinit(H264Context *h, int setup_finished)
730 H264Picture *out = h->cur_pic_ptr;
731 H264Picture *cur = h->cur_pic_ptr;
732 int i, pics, out_of_order, out_idx;
733 int invalid = 0, cnt = 0;
735 h->cur_pic_ptr->f.pict_type = h->pict_type;
737 if (h->next_output_pic)
740 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
741 /* FIXME: if we have two PAFF fields in one packet, we can't start
742 * the next thread here. If we have one field per packet, we can.
743 * The check in decode_nal_units() is not good enough to find this
744 * yet, so we assume the worst for now. */
745 // if (setup_finished)
746 // ff_thread_finish_setup(h->avctx);
750 cur->f.interlaced_frame = 0;
751 cur->f.repeat_pict = 0;
753 /* Signal interlacing information externally. */
754 /* Prioritize picture timing SEI information over used
755 * decoding process if it exists. */
757 if (h->sps.pic_struct_present_flag) {
758 switch (h->sei_pic_struct) {
759 case SEI_PIC_STRUCT_FRAME:
761 case SEI_PIC_STRUCT_TOP_FIELD:
762 case SEI_PIC_STRUCT_BOTTOM_FIELD:
763 cur->f.interlaced_frame = 1;
765 case SEI_PIC_STRUCT_TOP_BOTTOM:
766 case SEI_PIC_STRUCT_BOTTOM_TOP:
767 if (FIELD_OR_MBAFF_PICTURE(h))
768 cur->f.interlaced_frame = 1;
770 // try to flag soft telecine progressive
771 cur->f.interlaced_frame = h->prev_interlaced_frame;
773 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
774 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
775 /* Signal the possibility of telecined film externally
776 * (pic_struct 5,6). From these hints, let the applications
777 * decide if they apply deinterlacing. */
778 cur->f.repeat_pict = 1;
780 case SEI_PIC_STRUCT_FRAME_DOUBLING:
781 cur->f.repeat_pict = 2;
783 case SEI_PIC_STRUCT_FRAME_TRIPLING:
784 cur->f.repeat_pict = 4;
788 if ((h->sei_ct_type & 3) &&
789 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
790 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
792 /* Derive interlacing flag from used decoding process. */
793 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
795 h->prev_interlaced_frame = cur->f.interlaced_frame;
797 if (cur->field_poc[0] != cur->field_poc[1]) {
798 /* Derive top_field_first from field pocs. */
799 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
801 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
802 /* Use picture timing SEI information. Even if it is a
803 * information of a past frame, better than nothing. */
804 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
805 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
806 cur->f.top_field_first = 1;
808 cur->f.top_field_first = 0;
810 /* Most likely progressive */
811 cur->f.top_field_first = 0;
815 if (h->sei_frame_packing_present &&
816 h->frame_packing_arrangement_type >= 0 &&
817 h->frame_packing_arrangement_type <= 6 &&
818 h->content_interpretation_type > 0 &&
819 h->content_interpretation_type < 3) {
820 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
824 switch (h->frame_packing_arrangement_type) {
826 stereo->type = AV_STEREO3D_CHECKERBOARD;
829 stereo->type = AV_STEREO3D_COLUMNS;
832 stereo->type = AV_STEREO3D_LINES;
835 if (h->quincunx_subsampling)
836 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
838 stereo->type = AV_STEREO3D_SIDEBYSIDE;
841 stereo->type = AV_STEREO3D_TOPBOTTOM;
844 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
847 stereo->type = AV_STEREO3D_2D;
851 if (h->content_interpretation_type == 2)
852 stereo->flags = AV_STEREO3D_FLAG_INVERT;
855 if (h->sei_display_orientation_present &&
856 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
857 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
858 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
859 AV_FRAME_DATA_DISPLAYMATRIX,
860 sizeof(int32_t) * 9);
864 av_display_rotation_set((int32_t *)rotation->data, angle);
865 av_display_matrix_flip((int32_t *)rotation->data,
866 h->sei_hflip, h->sei_vflip);
869 // FIXME do something with unavailable reference frames
871 /* Sort B-frames into display order */
873 if (h->sps.bitstream_restriction_flag &&
874 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
875 h->avctx->has_b_frames = h->sps.num_reorder_frames;
879 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
880 !h->sps.bitstream_restriction_flag) {
881 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
886 while (h->delayed_pic[pics])
889 assert(pics <= MAX_DELAYED_PIC_COUNT);
891 h->delayed_pic[pics++] = cur;
892 if (cur->reference == 0)
893 cur->reference = DELAYED_PIC_REF;
895 /* Frame reordering. This code takes pictures from coding order and sorts
896 * them by their incremental POC value into display order. It supports POC
897 * gaps, MMCO reset codes and random resets.
898 * A "display group" can start either with a IDR frame (f.key_frame = 1),
899 * and/or can be closed down with a MMCO reset code. In sequences where
900 * there is no delay, we can't detect that (since the frame was already
901 * output to the user), so we also set h->mmco_reset to detect the MMCO
903 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
904 * we increase the delay between input and output. All frames affected by
905 * the lag (e.g. those that should have been output before another frame
906 * that we already returned to the user) will be dropped. This is a bug
907 * that we will fix later. */
908 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
909 cnt += out->poc < h->last_pocs[i];
910 invalid += out->poc == INT_MIN;
912 if (!h->mmco_reset && !cur->f.key_frame &&
913 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
916 h->delayed_pic[pics - 2]->mmco_reset = 2;
918 if (h->mmco_reset || cur->f.key_frame) {
919 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
920 h->last_pocs[i] = INT_MIN;
922 invalid = MAX_DELAYED_PIC_COUNT;
924 out = h->delayed_pic[0];
926 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
928 !h->delayed_pic[i - 1]->mmco_reset &&
929 !h->delayed_pic[i]->f.key_frame;
931 if (h->delayed_pic[i]->poc < out->poc) {
932 out = h->delayed_pic[i];
935 if (h->avctx->has_b_frames == 0 &&
936 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
937 h->next_outputed_poc = INT_MIN;
938 out_of_order = !out->f.key_frame && !h->mmco_reset &&
939 (out->poc < h->next_outputed_poc);
941 if (h->sps.bitstream_restriction_flag &&
942 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
943 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
944 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
945 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
946 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
949 } else if (h->low_delay &&
950 ((h->next_outputed_poc != INT_MIN &&
951 out->poc > h->next_outputed_poc + 2) ||
952 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
954 h->avctx->has_b_frames++;
957 if (pics > h->avctx->has_b_frames) {
958 out->reference &= ~DELAYED_PIC_REF;
959 // for frame threading, the owner must be the second field's thread or
960 // else the first thread can release the picture and reuse it unsafely
961 for (i = out_idx; h->delayed_pic[i]; i++)
962 h->delayed_pic[i] = h->delayed_pic[i + 1];
964 memmove(h->last_pocs, &h->last_pocs[1],
965 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
966 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
967 if (!out_of_order && pics > h->avctx->has_b_frames) {
968 h->next_output_pic = out;
969 if (out->mmco_reset) {
971 h->next_outputed_poc = out->poc;
972 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
974 h->next_outputed_poc = INT_MIN;
977 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
978 h->next_outputed_poc = INT_MIN;
980 h->next_outputed_poc = out->poc;
985 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
988 if (h->next_output_pic) {
989 if (h->next_output_pic->recovered) {
990 // We have reached an recovery point and all frames after it in
991 // display order are "recovered".
992 h->frame_recovered |= FRAME_RECOVERED_SEI;
994 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
997 if (setup_finished && !h->avctx->hwaccel)
998 ff_thread_finish_setup(h->avctx);
1001 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
1004 int luma_def, chroma_def;
1007 sl->use_weight_chroma = 0;
1008 sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
1009 if (h->sps.chroma_format_idc)
1010 sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
1011 luma_def = 1 << sl->luma_log2_weight_denom;
1012 chroma_def = 1 << sl->chroma_log2_weight_denom;
1014 for (list = 0; list < 2; list++) {
1015 sl->luma_weight_flag[list] = 0;
1016 sl->chroma_weight_flag[list] = 0;
1017 for (i = 0; i < sl->ref_count[list]; i++) {
1018 int luma_weight_flag, chroma_weight_flag;
1020 luma_weight_flag = get_bits1(&sl->gb);
1021 if (luma_weight_flag) {
1022 sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
1023 sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
1024 if (sl->luma_weight[i][list][0] != luma_def ||
1025 sl->luma_weight[i][list][1] != 0) {
1027 sl->luma_weight_flag[list] = 1;
1030 sl->luma_weight[i][list][0] = luma_def;
1031 sl->luma_weight[i][list][1] = 0;
1034 if (h->sps.chroma_format_idc) {
1035 chroma_weight_flag = get_bits1(&sl->gb);
1036 if (chroma_weight_flag) {
1038 for (j = 0; j < 2; j++) {
1039 sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
1040 sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
1041 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1042 sl->chroma_weight[i][list][j][1] != 0) {
1043 sl->use_weight_chroma = 1;
1044 sl->chroma_weight_flag[list] = 1;
1049 for (j = 0; j < 2; j++) {
1050 sl->chroma_weight[i][list][j][0] = chroma_def;
1051 sl->chroma_weight[i][list][j][1] = 0;
1056 if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
1059 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1064 * instantaneous decoder refresh.
1066 static void idr(H264Context *h)
1068 ff_h264_remove_all_refs(h);
1070 h->prev_frame_num_offset =
1072 h->prev_poc_lsb = 0;
1075 /* forget old pics after a seek */
1076 void ff_h264_flush_change(H264Context *h)
1079 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1080 h->last_pocs[i] = INT_MIN;
1081 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1082 h->prev_interlaced_frame = 1;
1085 h->cur_pic_ptr->reference = 0;
1087 ff_h264_reset_sei(h);
1088 h->recovery_frame = -1;
1089 h->frame_recovered = 0;
1092 /* forget old pics after a seek */
1093 static void flush_dpb(AVCodecContext *avctx)
1095 H264Context *h = avctx->priv_data;
1098 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1100 ff_h264_flush_change(h);
1103 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1104 ff_h264_unref_picture(h, &h->DPB[i]);
1105 h->cur_pic_ptr = NULL;
1106 ff_h264_unref_picture(h, &h->cur_pic);
1110 ff_h264_free_tables(h, 1);
1111 h->context_initialized = 0;
1114 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1116 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1119 h->frame_num_offset = h->prev_frame_num_offset;
1120 if (h->frame_num < h->prev_frame_num)
1121 h->frame_num_offset += max_frame_num;
1123 if (h->sps.poc_type == 0) {
1124 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1126 if (h->poc_lsb < h->prev_poc_lsb &&
1127 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1128 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1129 else if (h->poc_lsb > h->prev_poc_lsb &&
1130 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1131 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1133 h->poc_msb = h->prev_poc_msb;
1135 field_poc[1] = h->poc_msb + h->poc_lsb;
1136 if (h->picture_structure == PICT_FRAME)
1137 field_poc[1] += h->delta_poc_bottom;
1138 } else if (h->sps.poc_type == 1) {
1139 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1142 if (h->sps.poc_cycle_length != 0)
1143 abs_frame_num = h->frame_num_offset + h->frame_num;
1147 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1150 expected_delta_per_poc_cycle = 0;
1151 for (i = 0; i < h->sps.poc_cycle_length; i++)
1152 // FIXME integrate during sps parse
1153 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1155 if (abs_frame_num > 0) {
1156 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1157 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1159 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1160 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1161 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1165 if (h->nal_ref_idc == 0)
1166 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1168 field_poc[0] = expectedpoc + h->delta_poc[0];
1169 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1171 if (h->picture_structure == PICT_FRAME)
1172 field_poc[1] += h->delta_poc[1];
1174 int poc = 2 * (h->frame_num_offset + h->frame_num);
1176 if (!h->nal_ref_idc)
1183 if (h->picture_structure != PICT_BOTTOM_FIELD)
1184 pic_field_poc[0] = field_poc[0];
1185 if (h->picture_structure != PICT_TOP_FIELD)
1186 pic_field_poc[1] = field_poc[1];
1187 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1193 * Compute profile from profile_idc and constraint_set?_flags.
1197 * @return profile as defined by FF_PROFILE_H264_*
1199 int ff_h264_get_profile(SPS *sps)
1201 int profile = sps->profile_idc;
1203 switch (sps->profile_idc) {
1204 case FF_PROFILE_H264_BASELINE:
1205 // constraint_set1_flag set to 1
1206 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1208 case FF_PROFILE_H264_HIGH_10:
1209 case FF_PROFILE_H264_HIGH_422:
1210 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1211 // constraint_set3_flag set to 1
1212 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1219 int ff_h264_set_parameter_from_sps(H264Context *h)
1221 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1222 (h->sps.bitstream_restriction_flag &&
1223 !h->sps.num_reorder_frames)) {
1224 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1225 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1226 "Reenabling low delay requires a codec flush.\n");
1231 if (h->avctx->has_b_frames < 2)
1232 h->avctx->has_b_frames = !h->low_delay;
1234 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1235 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1236 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
1237 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1238 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1239 h->pixel_shift = h->sps.bit_depth_luma > 8;
1241 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1242 h->sps.chroma_format_idc);
1243 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1244 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1245 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1246 h->sps.chroma_format_idc);
1247 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1249 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1250 h->sps.bit_depth_luma);
1251 return AVERROR_INVALIDDATA;
1257 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1259 int ref_count[2], list_count;
1260 int num_ref_idx_active_override_flag, max_refs;
1262 // set defaults, might be overridden a few lines later
1263 ref_count[0] = h->pps.ref_count[0];
1264 ref_count[1] = h->pps.ref_count[1];
1266 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1267 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1268 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1269 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1271 if (num_ref_idx_active_override_flag) {
1272 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1273 if (ref_count[0] < 1)
1274 return AVERROR_INVALIDDATA;
1275 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1276 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1277 if (ref_count[1] < 1)
1278 return AVERROR_INVALIDDATA;
1282 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1288 ref_count[0] = ref_count[1] = 0;
1291 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1293 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1294 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1295 sl->ref_count[0] = sl->ref_count[1] = 0;
1296 return AVERROR_INVALIDDATA;
1299 if (list_count != sl->list_count ||
1300 ref_count[0] != sl->ref_count[0] ||
1301 ref_count[1] != sl->ref_count[1]) {
1302 sl->ref_count[0] = ref_count[0];
1303 sl->ref_count[1] = ref_count[1];
1304 sl->list_count = list_count;
1311 static int find_start_code(const uint8_t *buf, int buf_size,
1312 int buf_index, int next_avc)
1314 // start code prefix search
1315 for (; buf_index + 3 < next_avc; buf_index++)
1316 // This should always succeed in the first iteration.
1317 if (buf[buf_index] == 0 &&
1318 buf[buf_index + 1] == 0 &&
1319 buf[buf_index + 2] == 1)
1322 if (buf_index + 3 >= buf_size)
1325 return buf_index + 3;
1328 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1329 int buf_size, int *buf_index)
1333 if (*buf_index >= buf_size - h->nal_length_size)
1336 for (i = 0; i < h->nal_length_size; i++)
1337 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1338 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1339 av_log(h->avctx, AV_LOG_ERROR,
1340 "AVC: nal size %d\n", nalsize);
1346 static int get_bit_length(H264Context *h, const uint8_t *buf,
1347 const uint8_t *ptr, int dst_length,
1348 int i, int next_avc)
1350 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1351 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1352 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1353 h->workaround_bugs |= FF_BUG_TRUNCATED;
1355 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1356 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1362 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1365 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1367 int next_avc = h->is_avc ? 0 : buf_size;
1370 int nals_needed = 0;
1375 int dst_length, bit_length, consumed;
1378 if (buf_index >= next_avc) {
1379 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1382 next_avc = buf_index + nalsize;
1384 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1385 if (buf_index >= buf_size)
1389 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1390 next_avc - buf_index);
1392 if (!ptr || dst_length < 0)
1393 return AVERROR_INVALIDDATA;
1395 buf_index += consumed;
1397 bit_length = get_bit_length(h, buf, ptr, dst_length,
1398 buf_index, next_avc);
1401 /* packets can sometimes contain multiple PPS/SPS,
1402 * e.g. two PAFF field pictures in one packet, or a demuxer
1403 * which splits NALs strangely if so, when frame threading we
1404 * can't start the next thread until we've read all of them */
1405 switch (h->nal_unit_type) {
1408 nals_needed = nal_index;
1413 init_get_bits(&gb, ptr, bit_length);
1414 if (!get_ue_golomb(&gb))
1415 nals_needed = nal_index;
1422 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1423 int parse_extradata)
1425 AVCodecContext *const avctx = h->avctx;
1426 H264Context *hx; ///< thread context
1427 H264SliceContext *sl;
1429 unsigned context_count;
1431 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1435 h->max_contexts = h->slice_context_count;
1436 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1437 h->current_slice = 0;
1438 if (!h->first_field)
1439 h->cur_pic_ptr = NULL;
1440 ff_h264_reset_sei(h);
1443 if (avctx->active_thread_type & FF_THREAD_FRAME)
1444 nals_needed = get_last_needed_nal(h, buf, buf_size);
1449 next_avc = h->is_avc ? 0 : buf_size;
1459 if (buf_index >= next_avc) {
1460 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1463 next_avc = buf_index + nalsize;
1465 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1466 if (buf_index >= buf_size)
1468 if (buf_index >= next_avc)
1472 hx = h->thread_context[context_count];
1473 sl = &h->slice_ctx[context_count];
1475 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1476 &consumed, next_avc - buf_index);
1477 if (!ptr || dst_length < 0) {
1482 bit_length = get_bit_length(h, buf, ptr, dst_length,
1483 buf_index + consumed, next_avc);
1485 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1486 av_log(h->avctx, AV_LOG_DEBUG,
1487 "NAL %d at %d/%d length %d\n",
1488 hx->nal_unit_type, buf_index, buf_size, dst_length);
1490 if (h->is_avc && (nalsize != consumed) && nalsize)
1491 av_log(h->avctx, AV_LOG_DEBUG,
1492 "AVC: Consumed only %d bytes instead of %d\n",
1495 buf_index += consumed;
1498 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1499 h->nal_ref_idc == 0 &&
1500 h->nal_unit_type != NAL_SEI)
1504 /* Ignore every NAL unit type except PPS and SPS during extradata
1505 * parsing. Decoding slices is not possible in codec init
1507 if (parse_extradata && HAVE_THREADS &&
1508 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1509 (hx->nal_unit_type != NAL_PPS &&
1510 hx->nal_unit_type != NAL_SPS)) {
1511 if (hx->nal_unit_type < NAL_AUD ||
1512 hx->nal_unit_type > NAL_AUXILIARY_SLICE)
1513 av_log(avctx, AV_LOG_INFO,
1514 "Ignoring NAL unit %d during extradata parsing\n",
1516 hx->nal_unit_type = NAL_FF_IGNORE;
1519 switch (hx->nal_unit_type) {
1521 if (h->nal_unit_type != NAL_IDR_SLICE) {
1522 av_log(h->avctx, AV_LOG_ERROR,
1523 "Invalid mix of idr and non-idr slices\n");
1527 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1529 init_get_bits(&sl->gb, ptr, bit_length);
1531 if ((err = ff_h264_decode_slice_header(hx, sl, h)))
1534 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1535 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1536 ((1 << h->sps.log2_max_frame_num) - 1);
1539 h->cur_pic_ptr->f.key_frame |=
1540 (hx->nal_unit_type == NAL_IDR_SLICE) ||
1541 (h->sei_recovery_frame_cnt >= 0);
1543 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1544 h->recovery_frame == h->frame_num) {
1545 h->recovery_frame = -1;
1546 h->cur_pic_ptr->recovered = 1;
1548 // If we have an IDR, all frames after it in decoded order are
1550 if (hx->nal_unit_type == NAL_IDR_SLICE)
1551 h->frame_recovered |= FRAME_RECOVERED_IDR;
1552 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1554 if (h->current_slice == 1) {
1555 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1556 decode_postinit(h, nal_index >= nals_needed);
1558 if (h->avctx->hwaccel &&
1559 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1563 if (sl->redundant_pic_count == 0 &&
1564 (avctx->skip_frame < AVDISCARD_NONREF ||
1566 (avctx->skip_frame < AVDISCARD_BIDIR ||
1567 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1568 (avctx->skip_frame < AVDISCARD_NONKEY ||
1569 sl->slice_type_nos == AV_PICTURE_TYPE_I) &&
1570 avctx->skip_frame < AVDISCARD_ALL) {
1571 if (avctx->hwaccel) {
1572 ret = avctx->hwaccel->decode_slice(avctx,
1573 &buf[buf_index - consumed],
1584 avpriv_request_sample(avctx, "data partitioning");
1585 ret = AVERROR(ENOSYS);
1589 init_get_bits(&h->gb, ptr, bit_length);
1590 ret = ff_h264_decode_sei(h);
1591 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1595 init_get_bits(&h->gb, ptr, bit_length);
1596 ret = ff_h264_decode_seq_parameter_set(h);
1597 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
1598 av_log(h->avctx, AV_LOG_DEBUG,
1599 "SPS decoding failure, trying again with the complete NAL\n");
1600 init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
1602 ff_h264_decode_seq_parameter_set(h);
1605 ret = ff_h264_set_parameter_from_sps(h);
1611 init_get_bits(&h->gb, ptr, bit_length);
1612 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1613 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1617 case NAL_END_SEQUENCE:
1618 case NAL_END_STREAM:
1619 case NAL_FILLER_DATA:
1621 case NAL_AUXILIARY_SLICE:
1626 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1627 hx->nal_unit_type, bit_length);
1630 if (context_count == h->max_contexts) {
1631 ret = ff_h264_execute_decode_slices(h, context_count);
1632 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1638 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1639 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1640 } else if (err == 1) {
1641 /* Slice could not be decoded in parallel mode, copy down
1642 * NAL unit stuff to context 0 and restart. Note that
1643 * rbsp_buffer is not transferred, but since we no longer
1644 * run in parallel mode this should not be an issue. */
1645 h->nal_unit_type = hx->nal_unit_type;
1646 h->nal_ref_idc = hx->nal_ref_idc;
1648 sl = &h->slice_ctx[0];
1653 if (context_count) {
1654 ret = ff_h264_execute_decode_slices(h, context_count);
1655 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1662 if (h->cur_pic_ptr && !h->droppable) {
1663 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1664 h->picture_structure == PICT_BOTTOM_FIELD);
1667 return (ret < 0) ? ret : buf_index;
1671 * Return the number of bytes consumed for building the current frame.
1673 static int get_consumed_bytes(int pos, int buf_size)
1676 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1677 if (pos + 10 > buf_size)
1678 pos = buf_size; // oops ;)
1683 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1686 int ret = av_frame_ref(dst, src);
1693 for (i = 0; i < 3; i++) {
1694 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1695 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1696 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1697 (h->sps.crop_top >> vshift) * dst->linesize[i];
1698 dst->data[i] += off;
1703 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1704 int *got_frame, AVPacket *avpkt)
1706 const uint8_t *buf = avpkt->data;
1707 int buf_size = avpkt->size;
1708 H264Context *h = avctx->priv_data;
1709 AVFrame *pict = data;
1713 h->flags = avctx->flags;
1715 /* end of stream, output what is still in the buffers */
1717 if (buf_size == 0) {
1721 h->cur_pic_ptr = NULL;
1723 // FIXME factorize this with the output code below
1724 out = h->delayed_pic[0];
1727 h->delayed_pic[i] &&
1728 !h->delayed_pic[i]->f.key_frame &&
1729 !h->delayed_pic[i]->mmco_reset;
1731 if (h->delayed_pic[i]->poc < out->poc) {
1732 out = h->delayed_pic[i];
1736 for (i = out_idx; h->delayed_pic[i]; i++)
1737 h->delayed_pic[i] = h->delayed_pic[i + 1];
1740 ret = output_frame(h, pict, &out->f);
1749 buf_index = decode_nal_units(h, buf, buf_size, 0);
1751 return AVERROR_INVALIDDATA;
1753 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1758 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1759 if (avctx->skip_frame >= AVDISCARD_NONREF)
1761 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1762 return AVERROR_INVALIDDATA;
1765 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1766 (h->mb_y >= h->mb_height && h->mb_height)) {
1767 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1768 decode_postinit(h, 1);
1770 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1773 if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
1774 h->next_output_pic->recovered)) {
1775 if (!h->next_output_pic->recovered)
1776 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1778 ret = output_frame(h, pict, &h->next_output_pic->f);
1785 assert(pict->buf[0] || !*got_frame);
1787 return get_consumed_bytes(buf_index, buf_size);
1790 av_cold void ff_h264_free_context(H264Context *h)
1794 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1796 av_freep(&h->slice_ctx);
1797 h->nb_slice_ctx = 0;
1799 for (i = 0; i < MAX_SPS_COUNT; i++)
1800 av_freep(h->sps_buffers + i);
1802 for (i = 0; i < MAX_PPS_COUNT; i++)
1803 av_freep(h->pps_buffers + i);
1806 static av_cold int h264_decode_end(AVCodecContext *avctx)
1808 H264Context *h = avctx->priv_data;
1810 ff_h264_free_context(h);
1812 ff_h264_unref_picture(h, &h->cur_pic);
1817 static const AVProfile profiles[] = {
1818 { FF_PROFILE_H264_BASELINE, "Baseline" },
1819 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1820 { FF_PROFILE_H264_MAIN, "Main" },
1821 { FF_PROFILE_H264_EXTENDED, "Extended" },
1822 { FF_PROFILE_H264_HIGH, "High" },
1823 { FF_PROFILE_H264_HIGH_10, "High 10" },
1824 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1825 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1826 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1827 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1828 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1829 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1830 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1831 { FF_PROFILE_UNKNOWN },
1834 AVCodec ff_h264_decoder = {
1836 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1837 .type = AVMEDIA_TYPE_VIDEO,
1838 .id = AV_CODEC_ID_H264,
1839 .priv_data_size = sizeof(H264Context),
1840 .init = ff_h264_decode_init,
1841 .close = h264_decode_end,
1842 .decode = h264_decode_frame,
1843 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1844 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1845 CODEC_CAP_FRAME_THREADS,
1847 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1848 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1849 .profiles = NULL_IF_CONFIG_SMALL(profiles),