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;
62 h->mb_xy = mb_x + mb_y * h->mb_stride;
63 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
65 /* FIXME: It is possible albeit uncommon that slice references
66 * differ between slices. We take the easy approach and ignore
67 * it for now. If this turns out to have any relevance in
68 * practice then correct remapping should be added. */
69 if (ref >= h->ref_count[0])
71 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
73 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
74 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
75 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
76 assert(!FRAME_MBAFF(h));
77 ff_h264_hl_decode_mb(h);
80 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
82 AVCodecContext *avctx = h->avctx;
83 AVFrame *cur = &h->cur_pic.f;
84 AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
85 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
86 int vshift = desc->log2_chroma_h;
87 const int field_pic = h->picture_structure != PICT_FRAME;
93 height = FFMIN(height, avctx->height - y);
95 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
98 if (avctx->draw_horiz_band) {
100 int offset[AV_NUM_DATA_POINTERS];
103 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
104 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
111 offset[0] = y * src->linesize[0];
113 offset[2] = (y >> vshift) * src->linesize[1];
114 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
119 avctx->draw_horiz_band(avctx, src, offset,
120 y, h->picture_structure, height);
125 * Check if the top & left blocks are available if needed and
126 * change the dc mode so it only uses the available blocks.
128 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
130 static const int8_t top[12] = {
131 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
133 static const int8_t left[12] = {
134 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
138 if (!(h->top_samples_available & 0x8000)) {
139 for (i = 0; i < 4; i++) {
140 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
142 av_log(h->avctx, AV_LOG_ERROR,
143 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
144 status, h->mb_x, h->mb_y);
145 return AVERROR_INVALIDDATA;
147 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
152 if ((h->left_samples_available & 0x8888) != 0x8888) {
153 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
154 for (i = 0; i < 4; i++)
155 if (!(h->left_samples_available & mask[i])) {
156 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
158 av_log(h->avctx, AV_LOG_ERROR,
159 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
160 status, h->mb_x, h->mb_y);
161 return AVERROR_INVALIDDATA;
163 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
169 } // FIXME cleanup like ff_h264_check_intra_pred_mode
172 * Check if the top & left blocks are available if needed and
173 * change the dc mode so it only uses the available blocks.
175 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
177 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
178 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
181 av_log(h->avctx, AV_LOG_ERROR,
182 "out of range intra chroma pred mode at %d %d\n",
184 return AVERROR_INVALIDDATA;
187 if (!(h->top_samples_available & 0x8000)) {
190 av_log(h->avctx, AV_LOG_ERROR,
191 "top block unavailable for requested intra mode at %d %d\n",
193 return AVERROR_INVALIDDATA;
197 if ((h->left_samples_available & 0x8080) != 0x8080) {
199 if (is_chroma && (h->left_samples_available & 0x8080)) {
200 // mad cow disease mode, aka MBAFF + constrained_intra_pred
201 mode = ALZHEIMER_DC_L0T_PRED8x8 +
202 (!(h->left_samples_available & 0x8000)) +
203 2 * (mode == DC_128_PRED8x8);
206 av_log(h->avctx, AV_LOG_ERROR,
207 "left block unavailable for requested intra mode at %d %d\n",
209 return AVERROR_INVALIDDATA;
216 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
217 int *dst_length, int *consumed, int length)
223 // src[0]&0x80; // forbidden bit
224 h->nal_ref_idc = src[0] >> 5;
225 h->nal_unit_type = src[0] & 0x1F;
230 #define STARTCODE_TEST \
231 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
232 if (src[i + 2] != 3) { \
233 /* startcode, so we must be past the end */ \
239 #if HAVE_FAST_UNALIGNED
240 #define FIND_FIRST_ZERO \
241 if (i > 0 && !src[i]) \
247 for (i = 0; i + 1 < length; i += 9) {
248 if (!((~AV_RN64A(src + i) &
249 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
250 0x8000800080008080ULL))
257 for (i = 0; i + 1 < length; i += 5) {
258 if (!((~AV_RN32A(src + i) &
259 (AV_RN32A(src + i) - 0x01000101U)) &
268 for (i = 0; i + 1 < length; i += 2) {
271 if (i > 0 && src[i - 1] == 0)
277 if (i >= length - 1) { // no escaped 0
278 *dst_length = length;
279 *consumed = length + 1; // +1 for the header
283 // use second escape buffer for inter data
284 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
285 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
286 length + FF_INPUT_BUFFER_PADDING_SIZE);
287 dst = h->rbsp_buffer[bufidx];
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->top_borders[1]);
383 av_freep(&hx->top_borders[0]);
384 av_freep(&hx->bipred_scratchpad);
385 av_freep(&hx->edge_emu_buffer);
386 av_freep(&hx->dc_val_base);
387 av_freep(&hx->er.mb_index2xy);
388 av_freep(&hx->er.error_status_table);
389 av_freep(&hx->er.er_temp_buffer);
390 av_freep(&hx->er.mbintra_table);
391 av_freep(&hx->er.mbskip_table);
394 av_freep(&hx->rbsp_buffer[1]);
395 av_freep(&hx->rbsp_buffer[0]);
396 hx->rbsp_buffer_size[0] = 0;
397 hx->rbsp_buffer_size[1] = 0;
400 av_freep(&h->thread_context[i]);
404 int ff_h264_alloc_tables(H264Context *h)
406 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
407 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
410 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
411 row_mb_num * 8 * sizeof(uint8_t), fail)
412 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
413 big_mb_num * 48 * sizeof(uint8_t), fail)
414 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
415 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
416 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
417 big_mb_num * sizeof(uint16_t), fail)
418 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
419 big_mb_num * sizeof(uint8_t), fail)
420 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
421 16 * row_mb_num * sizeof(uint8_t), fail);
422 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
423 16 * row_mb_num * sizeof(uint8_t), fail);
424 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
425 4 * big_mb_num * sizeof(uint8_t), fail);
426 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
427 big_mb_num * sizeof(uint8_t), fail)
429 memset(h->slice_table_base, -1,
430 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
431 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
433 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
434 big_mb_num * sizeof(uint32_t), fail);
435 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
436 big_mb_num * sizeof(uint32_t), fail);
437 for (y = 0; y < h->mb_height; y++)
438 for (x = 0; x < h->mb_width; x++) {
439 const int mb_xy = x + y * h->mb_stride;
440 const int b_xy = 4 * x + 4 * y * h->b_stride;
442 h->mb2b_xy[mb_xy] = b_xy;
443 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
446 if (!h->dequant4_coeff[0])
447 h264_init_dequant_tables(h);
450 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
453 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
454 av_frame_unref(&h->DPB[i].f);
455 av_frame_unref(&h->cur_pic.f);
461 ff_h264_free_tables(h, 1);
462 return AVERROR(ENOMEM);
467 * Allocate buffers which are not shared amongst multiple threads.
469 int ff_h264_context_init(H264Context *h)
471 ERContext *er = &h->er;
472 int mb_array_size = h->mb_height * h->mb_stride;
473 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
474 int c_size = h->mb_stride * (h->mb_height + 1);
475 int yc_size = y_size + 2 * c_size;
478 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
479 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
480 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
481 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
483 h->ref_cache[0][scan8[5] + 1] =
484 h->ref_cache[0][scan8[7] + 1] =
485 h->ref_cache[0][scan8[13] + 1] =
486 h->ref_cache[1][scan8[5] + 1] =
487 h->ref_cache[1][scan8[7] + 1] =
488 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
490 if (CONFIG_ERROR_RESILIENCE) {
492 er->avctx = h->avctx;
493 er->decode_mb = h264_er_decode_mb;
495 er->quarter_sample = 1;
497 er->mb_num = h->mb_num;
498 er->mb_width = h->mb_width;
499 er->mb_height = h->mb_height;
500 er->mb_stride = h->mb_stride;
501 er->b8_stride = h->mb_width * 2 + 1;
503 // error resilience code looks cleaner with this
504 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
505 (h->mb_num + 1) * sizeof(int), fail);
507 for (y = 0; y < h->mb_height; y++)
508 for (x = 0; x < h->mb_width; x++)
509 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
511 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
512 h->mb_stride + h->mb_width;
514 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
515 mb_array_size * sizeof(uint8_t), fail);
517 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
518 memset(er->mbintra_table, 1, mb_array_size);
520 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
522 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
523 h->mb_height * h->mb_stride, fail);
525 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,
526 yc_size * sizeof(int16_t), fail);
527 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
528 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
529 er->dc_val[2] = er->dc_val[1] + c_size;
530 for (i = 0; i < yc_size; i++)
531 h->dc_val_base[i] = 1024;
537 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
540 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
541 int parse_extradata);
543 int ff_h264_decode_extradata(H264Context *h)
545 AVCodecContext *avctx = h->avctx;
548 if (avctx->extradata[0] == 1) {
550 unsigned char *p = avctx->extradata;
554 if (avctx->extradata_size < 7) {
555 av_log(avctx, AV_LOG_ERROR,
556 "avcC %d too short\n", avctx->extradata_size);
557 return AVERROR_INVALIDDATA;
559 /* sps and pps in the avcC always have length coded with 2 bytes,
560 * so put a fake nal_length_size = 2 while parsing them */
561 h->nal_length_size = 2;
562 // Decode sps from avcC
563 cnt = *(p + 5) & 0x1f; // Number of sps
565 for (i = 0; i < cnt; i++) {
566 nalsize = AV_RB16(p) + 2;
567 if (p - avctx->extradata + nalsize > avctx->extradata_size)
568 return AVERROR_INVALIDDATA;
569 ret = decode_nal_units(h, p, nalsize, 1);
571 av_log(avctx, AV_LOG_ERROR,
572 "Decoding sps %d from avcC failed\n", i);
577 // Decode pps from avcC
578 cnt = *(p++); // Number of pps
579 for (i = 0; i < cnt; i++) {
580 nalsize = AV_RB16(p) + 2;
581 if (p - avctx->extradata + nalsize > avctx->extradata_size)
582 return AVERROR_INVALIDDATA;
583 ret = decode_nal_units(h, p, nalsize, 1);
585 av_log(avctx, AV_LOG_ERROR,
586 "Decoding pps %d from avcC failed\n", i);
591 // Store right nal length size that will be used to parse all other nals
592 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
595 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
602 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
604 H264Context *h = avctx->priv_data;
610 h->bit_depth_luma = 8;
611 h->chroma_format_idc = 1;
613 ff_h264dsp_init(&h->h264dsp, 8, 1);
614 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
615 ff_h264qpel_init(&h->h264qpel, 8);
616 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
618 h->dequant_coeff_pps = -1;
620 /* needed so that IDCT permutation is known early */
621 ff_videodsp_init(&h->vdsp, 8);
623 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
624 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
626 h->picture_structure = PICT_FRAME;
627 h->slice_context_count = 1;
628 h->workaround_bugs = avctx->workaround_bugs;
629 h->flags = avctx->flags;
632 // s->decode_mb = ff_h263_decode_mb;
633 if (!avctx->has_b_frames)
636 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
638 ff_h264_decode_init_vlc();
640 ff_init_cabac_states();
643 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
645 h->thread_context[0] = h;
646 h->outputed_poc = h->next_outputed_poc = INT_MIN;
647 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
648 h->last_pocs[i] = INT_MIN;
649 h->prev_poc_msb = 1 << 16;
651 ff_h264_reset_sei(h);
652 h->recovery_frame = -1;
653 h->frame_recovered = 0;
654 if (avctx->codec_id == AV_CODEC_ID_H264) {
655 if (avctx->ticks_per_frame == 1)
656 h->avctx->framerate.num *= 2;
657 avctx->ticks_per_frame = 2;
660 if (avctx->extradata_size > 0 && avctx->extradata) {
661 ret = ff_h264_decode_extradata(h);
663 ff_h264_free_context(h);
668 if (h->sps.bitstream_restriction_flag &&
669 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
670 h->avctx->has_b_frames = h->sps.num_reorder_frames;
674 avctx->internal->allocate_progress = 1;
679 static int decode_init_thread_copy(AVCodecContext *avctx)
681 H264Context *h = avctx->priv_data;
683 if (!avctx->internal->is_copy)
685 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
686 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
688 h->rbsp_buffer[0] = NULL;
689 h->rbsp_buffer[1] = NULL;
690 h->rbsp_buffer_size[0] = 0;
691 h->rbsp_buffer_size[1] = 0;
692 h->context_initialized = 0;
698 * Run setup operations that must be run after slice header decoding.
699 * This includes finding the next displayed frame.
701 * @param h h264 master context
702 * @param setup_finished enough NALs have been read that we can call
703 * ff_thread_finish_setup()
705 static void decode_postinit(H264Context *h, int setup_finished)
707 H264Picture *out = h->cur_pic_ptr;
708 H264Picture *cur = h->cur_pic_ptr;
709 int i, pics, out_of_order, out_idx;
710 int invalid = 0, cnt = 0;
712 h->cur_pic_ptr->f.pict_type = h->pict_type;
714 if (h->next_output_pic)
717 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
718 /* FIXME: if we have two PAFF fields in one packet, we can't start
719 * the next thread here. If we have one field per packet, we can.
720 * The check in decode_nal_units() is not good enough to find this
721 * yet, so we assume the worst for now. */
722 // if (setup_finished)
723 // ff_thread_finish_setup(h->avctx);
727 cur->f.interlaced_frame = 0;
728 cur->f.repeat_pict = 0;
730 /* Signal interlacing information externally. */
731 /* Prioritize picture timing SEI information over used
732 * decoding process if it exists. */
734 if (h->sps.pic_struct_present_flag) {
735 switch (h->sei_pic_struct) {
736 case SEI_PIC_STRUCT_FRAME:
738 case SEI_PIC_STRUCT_TOP_FIELD:
739 case SEI_PIC_STRUCT_BOTTOM_FIELD:
740 cur->f.interlaced_frame = 1;
742 case SEI_PIC_STRUCT_TOP_BOTTOM:
743 case SEI_PIC_STRUCT_BOTTOM_TOP:
744 if (FIELD_OR_MBAFF_PICTURE(h))
745 cur->f.interlaced_frame = 1;
747 // try to flag soft telecine progressive
748 cur->f.interlaced_frame = h->prev_interlaced_frame;
750 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
751 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
752 /* Signal the possibility of telecined film externally
753 * (pic_struct 5,6). From these hints, let the applications
754 * decide if they apply deinterlacing. */
755 cur->f.repeat_pict = 1;
757 case SEI_PIC_STRUCT_FRAME_DOUBLING:
758 cur->f.repeat_pict = 2;
760 case SEI_PIC_STRUCT_FRAME_TRIPLING:
761 cur->f.repeat_pict = 4;
765 if ((h->sei_ct_type & 3) &&
766 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
767 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
769 /* Derive interlacing flag from used decoding process. */
770 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
772 h->prev_interlaced_frame = cur->f.interlaced_frame;
774 if (cur->field_poc[0] != cur->field_poc[1]) {
775 /* Derive top_field_first from field pocs. */
776 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
778 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
779 /* Use picture timing SEI information. Even if it is a
780 * information of a past frame, better than nothing. */
781 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
782 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
783 cur->f.top_field_first = 1;
785 cur->f.top_field_first = 0;
787 /* Most likely progressive */
788 cur->f.top_field_first = 0;
792 if (h->sei_frame_packing_present &&
793 h->frame_packing_arrangement_type >= 0 &&
794 h->frame_packing_arrangement_type <= 6 &&
795 h->content_interpretation_type > 0 &&
796 h->content_interpretation_type < 3) {
797 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
801 switch (h->frame_packing_arrangement_type) {
803 stereo->type = AV_STEREO3D_CHECKERBOARD;
806 stereo->type = AV_STEREO3D_COLUMNS;
809 stereo->type = AV_STEREO3D_LINES;
812 if (h->quincunx_subsampling)
813 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
815 stereo->type = AV_STEREO3D_SIDEBYSIDE;
818 stereo->type = AV_STEREO3D_TOPBOTTOM;
821 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
824 stereo->type = AV_STEREO3D_2D;
828 if (h->content_interpretation_type == 2)
829 stereo->flags = AV_STEREO3D_FLAG_INVERT;
832 if (h->sei_display_orientation_present &&
833 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
834 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
835 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
836 AV_FRAME_DATA_DISPLAYMATRIX,
837 sizeof(int32_t) * 9);
841 av_display_rotation_set((int32_t *)rotation->data, angle);
842 av_display_matrix_flip((int32_t *)rotation->data,
843 h->sei_hflip, h->sei_vflip);
846 // FIXME do something with unavailable reference frames
848 /* Sort B-frames into display order */
850 if (h->sps.bitstream_restriction_flag &&
851 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
852 h->avctx->has_b_frames = h->sps.num_reorder_frames;
856 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
857 !h->sps.bitstream_restriction_flag) {
858 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
863 while (h->delayed_pic[pics])
866 assert(pics <= MAX_DELAYED_PIC_COUNT);
868 h->delayed_pic[pics++] = cur;
869 if (cur->reference == 0)
870 cur->reference = DELAYED_PIC_REF;
872 /* Frame reordering. This code takes pictures from coding order and sorts
873 * them by their incremental POC value into display order. It supports POC
874 * gaps, MMCO reset codes and random resets.
875 * A "display group" can start either with a IDR frame (f.key_frame = 1),
876 * and/or can be closed down with a MMCO reset code. In sequences where
877 * there is no delay, we can't detect that (since the frame was already
878 * output to the user), so we also set h->mmco_reset to detect the MMCO
880 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
881 * we increase the delay between input and output. All frames affected by
882 * the lag (e.g. those that should have been output before another frame
883 * that we already returned to the user) will be dropped. This is a bug
884 * that we will fix later. */
885 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
886 cnt += out->poc < h->last_pocs[i];
887 invalid += out->poc == INT_MIN;
889 if (!h->mmco_reset && !cur->f.key_frame &&
890 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
893 h->delayed_pic[pics - 2]->mmco_reset = 2;
895 if (h->mmco_reset || cur->f.key_frame) {
896 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
897 h->last_pocs[i] = INT_MIN;
899 invalid = MAX_DELAYED_PIC_COUNT;
901 out = h->delayed_pic[0];
903 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
905 !h->delayed_pic[i - 1]->mmco_reset &&
906 !h->delayed_pic[i]->f.key_frame;
908 if (h->delayed_pic[i]->poc < out->poc) {
909 out = h->delayed_pic[i];
912 if (h->avctx->has_b_frames == 0 &&
913 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
914 h->next_outputed_poc = INT_MIN;
915 out_of_order = !out->f.key_frame && !h->mmco_reset &&
916 (out->poc < h->next_outputed_poc);
918 if (h->sps.bitstream_restriction_flag &&
919 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
920 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
921 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
922 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
923 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
926 } else if (h->low_delay &&
927 ((h->next_outputed_poc != INT_MIN &&
928 out->poc > h->next_outputed_poc + 2) ||
929 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
931 h->avctx->has_b_frames++;
934 if (pics > h->avctx->has_b_frames) {
935 out->reference &= ~DELAYED_PIC_REF;
936 // for frame threading, the owner must be the second field's thread or
937 // else the first thread can release the picture and reuse it unsafely
938 for (i = out_idx; h->delayed_pic[i]; i++)
939 h->delayed_pic[i] = h->delayed_pic[i + 1];
941 memmove(h->last_pocs, &h->last_pocs[1],
942 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
943 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
944 if (!out_of_order && pics > h->avctx->has_b_frames) {
945 h->next_output_pic = out;
946 if (out->mmco_reset) {
948 h->next_outputed_poc = out->poc;
949 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
951 h->next_outputed_poc = INT_MIN;
954 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
955 h->next_outputed_poc = INT_MIN;
957 h->next_outputed_poc = out->poc;
962 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
965 if (h->next_output_pic) {
966 if (h->next_output_pic->recovered) {
967 // We have reached an recovery point and all frames after it in
968 // display order are "recovered".
969 h->frame_recovered |= FRAME_RECOVERED_SEI;
971 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
974 if (setup_finished && !h->avctx->hwaccel)
975 ff_thread_finish_setup(h->avctx);
978 int ff_pred_weight_table(H264Context *h)
981 int luma_def, chroma_def;
984 h->use_weight_chroma = 0;
985 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
986 if (h->sps.chroma_format_idc)
987 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
988 luma_def = 1 << h->luma_log2_weight_denom;
989 chroma_def = 1 << h->chroma_log2_weight_denom;
991 for (list = 0; list < 2; list++) {
992 h->luma_weight_flag[list] = 0;
993 h->chroma_weight_flag[list] = 0;
994 for (i = 0; i < h->ref_count[list]; i++) {
995 int luma_weight_flag, chroma_weight_flag;
997 luma_weight_flag = get_bits1(&h->gb);
998 if (luma_weight_flag) {
999 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
1000 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
1001 if (h->luma_weight[i][list][0] != luma_def ||
1002 h->luma_weight[i][list][1] != 0) {
1004 h->luma_weight_flag[list] = 1;
1007 h->luma_weight[i][list][0] = luma_def;
1008 h->luma_weight[i][list][1] = 0;
1011 if (h->sps.chroma_format_idc) {
1012 chroma_weight_flag = get_bits1(&h->gb);
1013 if (chroma_weight_flag) {
1015 for (j = 0; j < 2; j++) {
1016 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1017 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1018 if (h->chroma_weight[i][list][j][0] != chroma_def ||
1019 h->chroma_weight[i][list][j][1] != 0) {
1020 h->use_weight_chroma = 1;
1021 h->chroma_weight_flag[list] = 1;
1026 for (j = 0; j < 2; j++) {
1027 h->chroma_weight[i][list][j][0] = chroma_def;
1028 h->chroma_weight[i][list][j][1] = 0;
1033 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1036 h->use_weight = h->use_weight || h->use_weight_chroma;
1041 * instantaneous decoder refresh.
1043 static void idr(H264Context *h)
1045 ff_h264_remove_all_refs(h);
1047 h->prev_frame_num_offset =
1049 h->prev_poc_lsb = 0;
1052 /* forget old pics after a seek */
1053 void ff_h264_flush_change(H264Context *h)
1056 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1057 h->last_pocs[i] = INT_MIN;
1058 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1059 h->prev_interlaced_frame = 1;
1062 h->cur_pic_ptr->reference = 0;
1064 ff_h264_reset_sei(h);
1065 h->recovery_frame = -1;
1066 h->frame_recovered = 0;
1069 /* forget old pics after a seek */
1070 static void flush_dpb(AVCodecContext *avctx)
1072 H264Context *h = avctx->priv_data;
1075 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1077 ff_h264_flush_change(h);
1080 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1081 ff_h264_unref_picture(h, &h->DPB[i]);
1082 h->cur_pic_ptr = NULL;
1083 ff_h264_unref_picture(h, &h->cur_pic);
1085 h->mb_x = h->mb_y = 0;
1087 ff_h264_free_tables(h, 1);
1088 h->context_initialized = 0;
1091 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1093 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1096 h->frame_num_offset = h->prev_frame_num_offset;
1097 if (h->frame_num < h->prev_frame_num)
1098 h->frame_num_offset += max_frame_num;
1100 if (h->sps.poc_type == 0) {
1101 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1103 if (h->poc_lsb < h->prev_poc_lsb &&
1104 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1105 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1106 else if (h->poc_lsb > h->prev_poc_lsb &&
1107 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1108 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1110 h->poc_msb = h->prev_poc_msb;
1112 field_poc[1] = h->poc_msb + h->poc_lsb;
1113 if (h->picture_structure == PICT_FRAME)
1114 field_poc[1] += h->delta_poc_bottom;
1115 } else if (h->sps.poc_type == 1) {
1116 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1119 if (h->sps.poc_cycle_length != 0)
1120 abs_frame_num = h->frame_num_offset + h->frame_num;
1124 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1127 expected_delta_per_poc_cycle = 0;
1128 for (i = 0; i < h->sps.poc_cycle_length; i++)
1129 // FIXME integrate during sps parse
1130 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1132 if (abs_frame_num > 0) {
1133 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1134 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1136 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1137 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1138 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1142 if (h->nal_ref_idc == 0)
1143 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1145 field_poc[0] = expectedpoc + h->delta_poc[0];
1146 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1148 if (h->picture_structure == PICT_FRAME)
1149 field_poc[1] += h->delta_poc[1];
1151 int poc = 2 * (h->frame_num_offset + h->frame_num);
1153 if (!h->nal_ref_idc)
1160 if (h->picture_structure != PICT_BOTTOM_FIELD)
1161 pic_field_poc[0] = field_poc[0];
1162 if (h->picture_structure != PICT_TOP_FIELD)
1163 pic_field_poc[1] = field_poc[1];
1164 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1170 * Compute profile from profile_idc and constraint_set?_flags.
1174 * @return profile as defined by FF_PROFILE_H264_*
1176 int ff_h264_get_profile(SPS *sps)
1178 int profile = sps->profile_idc;
1180 switch (sps->profile_idc) {
1181 case FF_PROFILE_H264_BASELINE:
1182 // constraint_set1_flag set to 1
1183 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1185 case FF_PROFILE_H264_HIGH_10:
1186 case FF_PROFILE_H264_HIGH_422:
1187 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1188 // constraint_set3_flag set to 1
1189 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1196 int ff_h264_set_parameter_from_sps(H264Context *h)
1198 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1199 (h->sps.bitstream_restriction_flag &&
1200 !h->sps.num_reorder_frames)) {
1201 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1202 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1203 "Reenabling low delay requires a codec flush.\n");
1208 if (h->avctx->has_b_frames < 2)
1209 h->avctx->has_b_frames = !h->low_delay;
1211 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1212 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1213 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
1214 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1215 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1216 h->pixel_shift = h->sps.bit_depth_luma > 8;
1218 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1219 h->sps.chroma_format_idc);
1220 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1221 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1222 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1223 h->sps.chroma_format_idc);
1224 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1226 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1227 h->sps.bit_depth_luma);
1228 return AVERROR_INVALIDDATA;
1234 int ff_set_ref_count(H264Context *h)
1236 int ref_count[2], list_count;
1237 int num_ref_idx_active_override_flag, max_refs;
1239 // set defaults, might be overridden a few lines later
1240 ref_count[0] = h->pps.ref_count[0];
1241 ref_count[1] = h->pps.ref_count[1];
1243 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1244 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1245 h->direct_spatial_mv_pred = get_bits1(&h->gb);
1246 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1248 if (num_ref_idx_active_override_flag) {
1249 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1250 if (ref_count[0] < 1)
1251 return AVERROR_INVALIDDATA;
1252 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1253 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1254 if (ref_count[1] < 1)
1255 return AVERROR_INVALIDDATA;
1259 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1265 ref_count[0] = ref_count[1] = 0;
1268 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1270 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1271 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1272 h->ref_count[0] = h->ref_count[1] = 0;
1273 return AVERROR_INVALIDDATA;
1276 if (list_count != h->list_count ||
1277 ref_count[0] != h->ref_count[0] ||
1278 ref_count[1] != h->ref_count[1]) {
1279 h->ref_count[0] = ref_count[0];
1280 h->ref_count[1] = ref_count[1];
1281 h->list_count = list_count;
1288 static int find_start_code(const uint8_t *buf, int buf_size,
1289 int buf_index, int next_avc)
1291 // start code prefix search
1292 for (; buf_index + 3 < next_avc; buf_index++)
1293 // This should always succeed in the first iteration.
1294 if (buf[buf_index] == 0 &&
1295 buf[buf_index + 1] == 0 &&
1296 buf[buf_index + 2] == 1)
1299 if (buf_index + 3 >= buf_size)
1302 return buf_index + 3;
1305 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1306 int buf_size, int *buf_index)
1310 if (*buf_index >= buf_size - h->nal_length_size)
1313 for (i = 0; i < h->nal_length_size; i++)
1314 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1315 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1316 av_log(h->avctx, AV_LOG_ERROR,
1317 "AVC: nal size %d\n", nalsize);
1323 static int get_bit_length(H264Context *h, const uint8_t *buf,
1324 const uint8_t *ptr, int dst_length,
1325 int i, int next_avc)
1327 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1328 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1329 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1330 h->workaround_bugs |= FF_BUG_TRUNCATED;
1332 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1333 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1339 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1342 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1344 int next_avc = h->is_avc ? 0 : buf_size;
1347 int nals_needed = 0;
1351 int dst_length, bit_length, consumed;
1354 if (buf_index >= next_avc) {
1355 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1358 next_avc = buf_index + nalsize;
1360 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1361 if (buf_index >= buf_size)
1365 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1366 next_avc - buf_index);
1368 if (!ptr || dst_length < 0)
1369 return AVERROR_INVALIDDATA;
1371 buf_index += consumed;
1373 bit_length = get_bit_length(h, buf, ptr, dst_length,
1374 buf_index, next_avc);
1377 /* packets can sometimes contain multiple PPS/SPS,
1378 * e.g. two PAFF field pictures in one packet, or a demuxer
1379 * which splits NALs strangely if so, when frame threading we
1380 * can't start the next thread until we've read all of them */
1381 switch (h->nal_unit_type) {
1384 nals_needed = nal_index;
1389 init_get_bits(&h->gb, ptr, bit_length);
1390 if (!get_ue_golomb(&h->gb))
1391 nals_needed = nal_index;
1398 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1399 int parse_extradata)
1401 AVCodecContext *const avctx = h->avctx;
1402 H264Context *hx; ///< thread context
1404 unsigned context_count;
1406 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1410 h->max_contexts = h->slice_context_count;
1411 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1412 h->current_slice = 0;
1413 if (!h->first_field)
1414 h->cur_pic_ptr = NULL;
1415 ff_h264_reset_sei(h);
1418 if (avctx->active_thread_type & FF_THREAD_FRAME)
1419 nals_needed = get_last_needed_nal(h, buf, buf_size);
1424 next_avc = h->is_avc ? 0 : buf_size;
1434 if (buf_index >= next_avc) {
1435 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1438 next_avc = buf_index + nalsize;
1440 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1441 if (buf_index >= buf_size)
1443 if (buf_index >= next_avc)
1447 hx = h->thread_context[context_count];
1449 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1450 &consumed, next_avc - buf_index);
1451 if (!ptr || dst_length < 0) {
1456 bit_length = get_bit_length(h, buf, ptr, dst_length,
1457 buf_index + consumed, next_avc);
1459 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1460 av_log(h->avctx, AV_LOG_DEBUG,
1461 "NAL %d at %d/%d length %d\n",
1462 hx->nal_unit_type, buf_index, buf_size, dst_length);
1464 if (h->is_avc && (nalsize != consumed) && nalsize)
1465 av_log(h->avctx, AV_LOG_DEBUG,
1466 "AVC: Consumed only %d bytes instead of %d\n",
1469 buf_index += consumed;
1472 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1473 h->nal_ref_idc == 0 &&
1474 h->nal_unit_type != NAL_SEI)
1478 /* Ignore every NAL unit type except PPS and SPS during extradata
1479 * parsing. Decoding slices is not possible in codec init
1481 if (parse_extradata && HAVE_THREADS &&
1482 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1483 (hx->nal_unit_type != NAL_PPS &&
1484 hx->nal_unit_type != NAL_SPS)) {
1485 if (hx->nal_unit_type < NAL_AUD ||
1486 hx->nal_unit_type > NAL_AUXILIARY_SLICE)
1487 av_log(avctx, AV_LOG_INFO,
1488 "Ignoring NAL unit %d during extradata parsing\n",
1490 hx->nal_unit_type = NAL_FF_IGNORE;
1493 switch (hx->nal_unit_type) {
1495 if (h->nal_unit_type != NAL_IDR_SLICE) {
1496 av_log(h->avctx, AV_LOG_ERROR,
1497 "Invalid mix of idr and non-idr slices\n");
1501 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1503 init_get_bits(&hx->gb, ptr, bit_length);
1505 hx->inter_gb_ptr = &hx->gb;
1507 if ((err = ff_h264_decode_slice_header(hx, h)))
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 (hx->nal_unit_type == NAL_IDR_SLICE) ||
1517 (h->sei_recovery_frame_cnt >= 0);
1519 if (hx->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 (hx->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 (hx->redundant_pic_count == 0 &&
1540 (avctx->skip_frame < AVDISCARD_NONREF ||
1542 (avctx->skip_frame < AVDISCARD_BIDIR ||
1543 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1544 (avctx->skip_frame < AVDISCARD_NONKEY ||
1545 hx->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 hx->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 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1616 } else if (err == 1) {
1617 /* Slice could not be decoded in parallel mode, copy down
1618 * NAL unit stuff to context 0 and restart. Note that
1619 * rbsp_buffer is not transferred, but since we no longer
1620 * run in parallel mode this should not be an issue. */
1621 h->nal_unit_type = hx->nal_unit_type;
1622 h->nal_ref_idc = hx->nal_ref_idc;
1628 if (context_count) {
1629 ret = ff_h264_execute_decode_slices(h, context_count);
1630 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1637 if (h->cur_pic_ptr && !h->droppable) {
1638 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1639 h->picture_structure == PICT_BOTTOM_FIELD);
1642 return (ret < 0) ? ret : buf_index;
1646 * Return the number of bytes consumed for building the current frame.
1648 static int get_consumed_bytes(int pos, int buf_size)
1651 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1652 if (pos + 10 > buf_size)
1653 pos = buf_size; // oops ;)
1658 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1661 int ret = av_frame_ref(dst, src);
1668 for (i = 0; i < 3; i++) {
1669 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1670 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1671 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1672 (h->sps.crop_top >> vshift) * dst->linesize[i];
1673 dst->data[i] += off;
1678 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1679 int *got_frame, AVPacket *avpkt)
1681 const uint8_t *buf = avpkt->data;
1682 int buf_size = avpkt->size;
1683 H264Context *h = avctx->priv_data;
1684 AVFrame *pict = data;
1688 h->flags = avctx->flags;
1690 /* end of stream, output what is still in the buffers */
1692 if (buf_size == 0) {
1696 h->cur_pic_ptr = NULL;
1698 // FIXME factorize this with the output code below
1699 out = h->delayed_pic[0];
1702 h->delayed_pic[i] &&
1703 !h->delayed_pic[i]->f.key_frame &&
1704 !h->delayed_pic[i]->mmco_reset;
1706 if (h->delayed_pic[i]->poc < out->poc) {
1707 out = h->delayed_pic[i];
1711 for (i = out_idx; h->delayed_pic[i]; i++)
1712 h->delayed_pic[i] = h->delayed_pic[i + 1];
1715 ret = output_frame(h, pict, &out->f);
1724 buf_index = decode_nal_units(h, buf, buf_size, 0);
1726 return AVERROR_INVALIDDATA;
1728 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1733 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1734 if (avctx->skip_frame >= AVDISCARD_NONREF)
1736 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1737 return AVERROR_INVALIDDATA;
1740 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1741 (h->mb_y >= h->mb_height && h->mb_height)) {
1742 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1743 decode_postinit(h, 1);
1745 ff_h264_field_end(h, 0);
1748 if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
1749 h->next_output_pic->recovered)) {
1750 if (!h->next_output_pic->recovered)
1751 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1753 ret = output_frame(h, pict, &h->next_output_pic->f);
1760 assert(pict->buf[0] || !*got_frame);
1762 return get_consumed_bytes(buf_index, buf_size);
1765 av_cold void ff_h264_free_context(H264Context *h)
1769 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
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),