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));
452 return AVERROR(ENOMEM);
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;
494 er->decode_mb = h264_er_decode_mb;
496 er->quarter_sample = 1;
498 er->mb_num = h->mb_num;
499 er->mb_width = h->mb_width;
500 er->mb_height = h->mb_height;
501 er->mb_stride = h->mb_stride;
502 er->b8_stride = h->mb_width * 2 + 1;
504 // error resilience code looks cleaner with this
505 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
506 (h->mb_num + 1) * sizeof(int), fail);
508 for (y = 0; y < h->mb_height; y++)
509 for (x = 0; x < h->mb_width; x++)
510 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
512 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
513 h->mb_stride + h->mb_width;
515 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
516 mb_array_size * sizeof(uint8_t), fail);
518 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
519 memset(er->mbintra_table, 1, mb_array_size);
521 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
523 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
524 h->mb_height * h->mb_stride, fail);
526 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,
527 yc_size * sizeof(int16_t), fail);
528 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
529 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
530 er->dc_val[2] = er->dc_val[1] + c_size;
531 for (i = 0; i < yc_size; i++)
532 h->dc_val_base[i] = 1024;
538 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
541 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
542 int parse_extradata);
544 int ff_h264_decode_extradata(H264Context *h)
546 AVCodecContext *avctx = h->avctx;
549 if (avctx->extradata[0] == 1) {
551 unsigned char *p = avctx->extradata;
555 if (avctx->extradata_size < 7) {
556 av_log(avctx, AV_LOG_ERROR,
557 "avcC %d too short\n", avctx->extradata_size);
558 return AVERROR_INVALIDDATA;
560 /* sps and pps in the avcC always have length coded with 2 bytes,
561 * so put a fake nal_length_size = 2 while parsing them */
562 h->nal_length_size = 2;
563 // Decode sps from avcC
564 cnt = *(p + 5) & 0x1f; // Number of sps
566 for (i = 0; i < cnt; i++) {
567 nalsize = AV_RB16(p) + 2;
568 if (p - avctx->extradata + nalsize > avctx->extradata_size)
569 return AVERROR_INVALIDDATA;
570 ret = decode_nal_units(h, p, nalsize, 1);
572 av_log(avctx, AV_LOG_ERROR,
573 "Decoding sps %d from avcC failed\n", i);
578 // Decode pps from avcC
579 cnt = *(p++); // Number of pps
580 for (i = 0; i < cnt; i++) {
581 nalsize = AV_RB16(p) + 2;
582 if (p - avctx->extradata + nalsize > avctx->extradata_size)
583 return AVERROR_INVALIDDATA;
584 ret = decode_nal_units(h, p, nalsize, 1);
586 av_log(avctx, AV_LOG_ERROR,
587 "Decoding pps %d from avcC failed\n", i);
592 // Store right nal length size that will be used to parse all other nals
593 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
596 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
603 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
605 H264Context *h = avctx->priv_data;
611 h->bit_depth_luma = 8;
612 h->chroma_format_idc = 1;
614 ff_h264dsp_init(&h->h264dsp, 8, 1);
615 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
616 ff_h264qpel_init(&h->h264qpel, 8);
617 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
619 h->dequant_coeff_pps = -1;
621 /* needed so that IDCT permutation is known early */
622 if (CONFIG_ERROR_RESILIENCE)
623 ff_me_cmp_init(&h->mecc, h->avctx);
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->thread_context[0] = h;
649 h->outputed_poc = h->next_outputed_poc = INT_MIN;
650 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
651 h->last_pocs[i] = INT_MIN;
652 h->prev_poc_msb = 1 << 16;
654 ff_h264_reset_sei(h);
655 h->recovery_frame = -1;
656 h->frame_recovered = 0;
657 if (avctx->codec_id == AV_CODEC_ID_H264) {
658 if (avctx->ticks_per_frame == 1)
659 h->avctx->time_base.den *= 2;
660 avctx->ticks_per_frame = 2;
663 if (avctx->extradata_size > 0 && avctx->extradata) {
664 ret = ff_h264_decode_extradata(h);
669 if (h->sps.bitstream_restriction_flag &&
670 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
671 h->avctx->has_b_frames = h->sps.num_reorder_frames;
675 avctx->internal->allocate_progress = 1;
680 static int decode_init_thread_copy(AVCodecContext *avctx)
682 H264Context *h = avctx->priv_data;
684 if (!avctx->internal->is_copy)
686 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
687 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
689 h->context_initialized = 0;
695 * Run setup operations that must be run after slice header decoding.
696 * This includes finding the next displayed frame.
698 * @param h h264 master context
699 * @param setup_finished enough NALs have been read that we can call
700 * ff_thread_finish_setup()
702 static void decode_postinit(H264Context *h, int setup_finished)
704 H264Picture *out = h->cur_pic_ptr;
705 H264Picture *cur = h->cur_pic_ptr;
706 int i, pics, out_of_order, out_idx;
707 int invalid = 0, cnt = 0;
709 h->cur_pic_ptr->f.pict_type = h->pict_type;
711 if (h->next_output_pic)
714 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
715 /* FIXME: if we have two PAFF fields in one packet, we can't start
716 * the next thread here. If we have one field per packet, we can.
717 * The check in decode_nal_units() is not good enough to find this
718 * yet, so we assume the worst for now. */
719 // if (setup_finished)
720 // ff_thread_finish_setup(h->avctx);
724 cur->f.interlaced_frame = 0;
725 cur->f.repeat_pict = 0;
727 /* Signal interlacing information externally. */
728 /* Prioritize picture timing SEI information over used
729 * decoding process if it exists. */
731 if (h->sps.pic_struct_present_flag) {
732 switch (h->sei_pic_struct) {
733 case SEI_PIC_STRUCT_FRAME:
735 case SEI_PIC_STRUCT_TOP_FIELD:
736 case SEI_PIC_STRUCT_BOTTOM_FIELD:
737 cur->f.interlaced_frame = 1;
739 case SEI_PIC_STRUCT_TOP_BOTTOM:
740 case SEI_PIC_STRUCT_BOTTOM_TOP:
741 if (FIELD_OR_MBAFF_PICTURE(h))
742 cur->f.interlaced_frame = 1;
744 // try to flag soft telecine progressive
745 cur->f.interlaced_frame = h->prev_interlaced_frame;
747 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
748 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
749 /* Signal the possibility of telecined film externally
750 * (pic_struct 5,6). From these hints, let the applications
751 * decide if they apply deinterlacing. */
752 cur->f.repeat_pict = 1;
754 case SEI_PIC_STRUCT_FRAME_DOUBLING:
755 cur->f.repeat_pict = 2;
757 case SEI_PIC_STRUCT_FRAME_TRIPLING:
758 cur->f.repeat_pict = 4;
762 if ((h->sei_ct_type & 3) &&
763 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
764 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
766 /* Derive interlacing flag from used decoding process. */
767 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
769 h->prev_interlaced_frame = cur->f.interlaced_frame;
771 if (cur->field_poc[0] != cur->field_poc[1]) {
772 /* Derive top_field_first from field pocs. */
773 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
775 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
776 /* Use picture timing SEI information. Even if it is a
777 * information of a past frame, better than nothing. */
778 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
779 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
780 cur->f.top_field_first = 1;
782 cur->f.top_field_first = 0;
784 /* Most likely progressive */
785 cur->f.top_field_first = 0;
789 if (h->sei_frame_packing_present &&
790 h->frame_packing_arrangement_type >= 0 &&
791 h->frame_packing_arrangement_type <= 6 &&
792 h->content_interpretation_type > 0 &&
793 h->content_interpretation_type < 3) {
794 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
798 switch (h->frame_packing_arrangement_type) {
800 stereo->type = AV_STEREO3D_CHECKERBOARD;
803 stereo->type = AV_STEREO3D_COLUMNS;
806 stereo->type = AV_STEREO3D_LINES;
809 if (h->quincunx_subsampling)
810 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
812 stereo->type = AV_STEREO3D_SIDEBYSIDE;
815 stereo->type = AV_STEREO3D_TOPBOTTOM;
818 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
821 stereo->type = AV_STEREO3D_2D;
825 if (h->content_interpretation_type == 2)
826 stereo->flags = AV_STEREO3D_FLAG_INVERT;
829 if (h->sei_display_orientation_present &&
830 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
831 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
832 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
833 AV_FRAME_DATA_DISPLAYMATRIX,
834 sizeof(int32_t) * 9);
838 av_display_rotation_set((int32_t *)rotation->data, angle);
839 av_display_matrix_flip((int32_t *)rotation->data,
840 h->sei_vflip, h->sei_hflip);
843 // FIXME do something with unavailable reference frames
845 /* Sort B-frames into display order */
847 if (h->sps.bitstream_restriction_flag &&
848 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
849 h->avctx->has_b_frames = h->sps.num_reorder_frames;
853 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
854 !h->sps.bitstream_restriction_flag) {
855 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
860 while (h->delayed_pic[pics])
863 assert(pics <= MAX_DELAYED_PIC_COUNT);
865 h->delayed_pic[pics++] = cur;
866 if (cur->reference == 0)
867 cur->reference = DELAYED_PIC_REF;
869 /* Frame reordering. This code takes pictures from coding order and sorts
870 * them by their incremental POC value into display order. It supports POC
871 * gaps, MMCO reset codes and random resets.
872 * A "display group" can start either with a IDR frame (f.key_frame = 1),
873 * and/or can be closed down with a MMCO reset code. In sequences where
874 * there is no delay, we can't detect that (since the frame was already
875 * output to the user), so we also set h->mmco_reset to detect the MMCO
877 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
878 * we increase the delay between input and output. All frames affected by
879 * the lag (e.g. those that should have been output before another frame
880 * that we already returned to the user) will be dropped. This is a bug
881 * that we will fix later. */
882 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
883 cnt += out->poc < h->last_pocs[i];
884 invalid += out->poc == INT_MIN;
886 if (!h->mmco_reset && !cur->f.key_frame &&
887 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
890 h->delayed_pic[pics - 2]->mmco_reset = 2;
892 if (h->mmco_reset || cur->f.key_frame) {
893 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
894 h->last_pocs[i] = INT_MIN;
896 invalid = MAX_DELAYED_PIC_COUNT;
898 out = h->delayed_pic[0];
900 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
902 !h->delayed_pic[i - 1]->mmco_reset &&
903 !h->delayed_pic[i]->f.key_frame;
905 if (h->delayed_pic[i]->poc < out->poc) {
906 out = h->delayed_pic[i];
909 if (h->avctx->has_b_frames == 0 &&
910 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
911 h->next_outputed_poc = INT_MIN;
912 out_of_order = !out->f.key_frame && !h->mmco_reset &&
913 (out->poc < h->next_outputed_poc);
915 if (h->sps.bitstream_restriction_flag &&
916 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
917 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
918 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
919 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
920 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
923 } else if (h->low_delay &&
924 ((h->next_outputed_poc != INT_MIN &&
925 out->poc > h->next_outputed_poc + 2) ||
926 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
928 h->avctx->has_b_frames++;
931 if (pics > h->avctx->has_b_frames) {
932 out->reference &= ~DELAYED_PIC_REF;
933 // for frame threading, the owner must be the second field's thread or
934 // else the first thread can release the picture and reuse it unsafely
935 for (i = out_idx; h->delayed_pic[i]; i++)
936 h->delayed_pic[i] = h->delayed_pic[i + 1];
938 memmove(h->last_pocs, &h->last_pocs[1],
939 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
940 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
941 if (!out_of_order && pics > h->avctx->has_b_frames) {
942 h->next_output_pic = out;
943 if (out->mmco_reset) {
945 h->next_outputed_poc = out->poc;
946 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
948 h->next_outputed_poc = INT_MIN;
951 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
952 h->next_outputed_poc = INT_MIN;
954 h->next_outputed_poc = out->poc;
959 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
962 if (h->next_output_pic) {
963 if (h->next_output_pic->recovered) {
964 // We have reached an recovery point and all frames after it in
965 // display order are "recovered".
966 h->frame_recovered |= FRAME_RECOVERED_SEI;
968 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
971 if (setup_finished && !h->avctx->hwaccel)
972 ff_thread_finish_setup(h->avctx);
975 int ff_pred_weight_table(H264Context *h)
978 int luma_def, chroma_def;
981 h->use_weight_chroma = 0;
982 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
983 if (h->sps.chroma_format_idc)
984 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
985 luma_def = 1 << h->luma_log2_weight_denom;
986 chroma_def = 1 << h->chroma_log2_weight_denom;
988 for (list = 0; list < 2; list++) {
989 h->luma_weight_flag[list] = 0;
990 h->chroma_weight_flag[list] = 0;
991 for (i = 0; i < h->ref_count[list]; i++) {
992 int luma_weight_flag, chroma_weight_flag;
994 luma_weight_flag = get_bits1(&h->gb);
995 if (luma_weight_flag) {
996 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
997 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
998 if (h->luma_weight[i][list][0] != luma_def ||
999 h->luma_weight[i][list][1] != 0) {
1001 h->luma_weight_flag[list] = 1;
1004 h->luma_weight[i][list][0] = luma_def;
1005 h->luma_weight[i][list][1] = 0;
1008 if (h->sps.chroma_format_idc) {
1009 chroma_weight_flag = get_bits1(&h->gb);
1010 if (chroma_weight_flag) {
1012 for (j = 0; j < 2; j++) {
1013 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1014 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1015 if (h->chroma_weight[i][list][j][0] != chroma_def ||
1016 h->chroma_weight[i][list][j][1] != 0) {
1017 h->use_weight_chroma = 1;
1018 h->chroma_weight_flag[list] = 1;
1023 for (j = 0; j < 2; j++) {
1024 h->chroma_weight[i][list][j][0] = chroma_def;
1025 h->chroma_weight[i][list][j][1] = 0;
1030 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1033 h->use_weight = h->use_weight || h->use_weight_chroma;
1038 * instantaneous decoder refresh.
1040 static void idr(H264Context *h)
1042 ff_h264_remove_all_refs(h);
1044 h->prev_frame_num_offset =
1046 h->prev_poc_lsb = 0;
1049 /* forget old pics after a seek */
1050 void ff_h264_flush_change(H264Context *h)
1053 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1054 h->last_pocs[i] = INT_MIN;
1055 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1056 h->prev_interlaced_frame = 1;
1059 h->cur_pic_ptr->reference = 0;
1061 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
1062 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
1063 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
1064 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
1065 ff_h264_reset_sei(h);
1066 h->recovery_frame = -1;
1067 h->frame_recovered = 0;
1070 /* forget old pics after a seek */
1071 static void flush_dpb(AVCodecContext *avctx)
1073 H264Context *h = avctx->priv_data;
1076 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1077 if (h->delayed_pic[i])
1078 h->delayed_pic[i]->reference = 0;
1079 h->delayed_pic[i] = NULL;
1082 ff_h264_flush_change(h);
1085 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1086 ff_h264_unref_picture(h, &h->DPB[i]);
1087 h->cur_pic_ptr = NULL;
1088 ff_h264_unref_picture(h, &h->cur_pic);
1090 h->mb_x = h->mb_y = 0;
1092 h->parse_context.state = -1;
1093 h->parse_context.frame_start_found = 0;
1094 h->parse_context.overread = 0;
1095 h->parse_context.overread_index = 0;
1096 h->parse_context.index = 0;
1097 h->parse_context.last_index = 0;
1099 ff_h264_free_tables(h, 1);
1100 h->context_initialized = 0;
1103 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1105 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1108 h->frame_num_offset = h->prev_frame_num_offset;
1109 if (h->frame_num < h->prev_frame_num)
1110 h->frame_num_offset += max_frame_num;
1112 if (h->sps.poc_type == 0) {
1113 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1115 if (h->poc_lsb < h->prev_poc_lsb &&
1116 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1117 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1118 else if (h->poc_lsb > h->prev_poc_lsb &&
1119 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1120 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1122 h->poc_msb = h->prev_poc_msb;
1124 field_poc[1] = h->poc_msb + h->poc_lsb;
1125 if (h->picture_structure == PICT_FRAME)
1126 field_poc[1] += h->delta_poc_bottom;
1127 } else if (h->sps.poc_type == 1) {
1128 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1131 if (h->sps.poc_cycle_length != 0)
1132 abs_frame_num = h->frame_num_offset + h->frame_num;
1136 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1139 expected_delta_per_poc_cycle = 0;
1140 for (i = 0; i < h->sps.poc_cycle_length; i++)
1141 // FIXME integrate during sps parse
1142 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1144 if (abs_frame_num > 0) {
1145 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1146 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1148 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1149 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1150 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1154 if (h->nal_ref_idc == 0)
1155 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1157 field_poc[0] = expectedpoc + h->delta_poc[0];
1158 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1160 if (h->picture_structure == PICT_FRAME)
1161 field_poc[1] += h->delta_poc[1];
1163 int poc = 2 * (h->frame_num_offset + h->frame_num);
1165 if (!h->nal_ref_idc)
1172 if (h->picture_structure != PICT_BOTTOM_FIELD)
1173 pic_field_poc[0] = field_poc[0];
1174 if (h->picture_structure != PICT_TOP_FIELD)
1175 pic_field_poc[1] = field_poc[1];
1176 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1182 * Compute profile from profile_idc and constraint_set?_flags.
1186 * @return profile as defined by FF_PROFILE_H264_*
1188 int ff_h264_get_profile(SPS *sps)
1190 int profile = sps->profile_idc;
1192 switch (sps->profile_idc) {
1193 case FF_PROFILE_H264_BASELINE:
1194 // constraint_set1_flag set to 1
1195 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1197 case FF_PROFILE_H264_HIGH_10:
1198 case FF_PROFILE_H264_HIGH_422:
1199 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1200 // constraint_set3_flag set to 1
1201 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1208 int ff_h264_set_parameter_from_sps(H264Context *h)
1210 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1211 (h->sps.bitstream_restriction_flag &&
1212 !h->sps.num_reorder_frames)) {
1213 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1214 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1215 "Reenabling low delay requires a codec flush.\n");
1220 if (h->avctx->has_b_frames < 2)
1221 h->avctx->has_b_frames = !h->low_delay;
1223 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1224 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1225 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
1226 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1227 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1228 h->pixel_shift = h->sps.bit_depth_luma > 8;
1230 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1231 h->sps.chroma_format_idc);
1232 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1233 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1234 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1235 h->sps.chroma_format_idc);
1236 if (CONFIG_ERROR_RESILIENCE)
1237 ff_me_cmp_init(&h->mecc, h->avctx);
1238 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1240 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1241 h->sps.bit_depth_luma);
1242 return AVERROR_INVALIDDATA;
1248 int ff_set_ref_count(H264Context *h)
1250 int ref_count[2], list_count;
1251 int num_ref_idx_active_override_flag, max_refs;
1253 // set defaults, might be overridden a few lines later
1254 ref_count[0] = h->pps.ref_count[0];
1255 ref_count[1] = h->pps.ref_count[1];
1257 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1258 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1259 h->direct_spatial_mv_pred = get_bits1(&h->gb);
1260 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1262 if (num_ref_idx_active_override_flag) {
1263 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1264 if (ref_count[0] < 1)
1265 return AVERROR_INVALIDDATA;
1266 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1267 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1268 if (ref_count[1] < 1)
1269 return AVERROR_INVALIDDATA;
1273 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1279 ref_count[0] = ref_count[1] = 0;
1282 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1284 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1285 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1286 h->ref_count[0] = h->ref_count[1] = 0;
1287 return AVERROR_INVALIDDATA;
1290 if (list_count != h->list_count ||
1291 ref_count[0] != h->ref_count[0] ||
1292 ref_count[1] != h->ref_count[1]) {
1293 h->ref_count[0] = ref_count[0];
1294 h->ref_count[1] = ref_count[1];
1295 h->list_count = list_count;
1302 static int find_start_code(const uint8_t *buf, int buf_size,
1303 int buf_index, int next_avc)
1305 // start code prefix search
1306 for (; buf_index + 3 < next_avc; buf_index++)
1307 // This should always succeed in the first iteration.
1308 if (buf[buf_index] == 0 &&
1309 buf[buf_index + 1] == 0 &&
1310 buf[buf_index + 2] == 1)
1313 if (buf_index + 3 >= buf_size)
1316 return buf_index + 3;
1319 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1320 int buf_size, int *buf_index)
1324 if (*buf_index >= buf_size - h->nal_length_size)
1327 for (i = 0; i < h->nal_length_size; i++)
1328 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1329 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1330 av_log(h->avctx, AV_LOG_ERROR,
1331 "AVC: nal size %d\n", nalsize);
1337 static int get_bit_length(H264Context *h, const uint8_t *buf,
1338 const uint8_t *ptr, int dst_length,
1339 int i, int next_avc)
1341 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1342 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1343 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1344 h->workaround_bugs |= FF_BUG_TRUNCATED;
1346 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1347 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1353 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1356 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1358 int next_avc = h->is_avc ? 0 : buf_size;
1361 int nals_needed = 0;
1365 int dst_length, bit_length, consumed;
1368 if (buf_index >= next_avc) {
1369 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1372 next_avc = buf_index + nalsize;
1374 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1375 if (buf_index >= buf_size)
1379 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1380 next_avc - buf_index);
1382 if (!ptr || dst_length < 0)
1383 return AVERROR_INVALIDDATA;
1385 buf_index += consumed;
1387 bit_length = get_bit_length(h, buf, ptr, dst_length,
1388 buf_index, next_avc);
1391 /* packets can sometimes contain multiple PPS/SPS,
1392 * e.g. two PAFF field pictures in one packet, or a demuxer
1393 * which splits NALs strangely if so, when frame threading we
1394 * can't start the next thread until we've read all of them */
1395 switch (h->nal_unit_type) {
1398 nals_needed = nal_index;
1403 init_get_bits(&h->gb, ptr, bit_length);
1404 if (!get_ue_golomb(&h->gb))
1405 nals_needed = nal_index;
1412 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1413 int parse_extradata)
1415 AVCodecContext *const avctx = h->avctx;
1416 H264Context *hx; ///< thread context
1418 unsigned context_count;
1420 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1424 h->max_contexts = h->slice_context_count;
1425 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1426 h->current_slice = 0;
1427 if (!h->first_field)
1428 h->cur_pic_ptr = NULL;
1429 ff_h264_reset_sei(h);
1432 if (avctx->active_thread_type & FF_THREAD_FRAME)
1433 nals_needed = get_last_needed_nal(h, buf, buf_size);
1438 next_avc = h->is_avc ? 0 : buf_size;
1448 if (buf_index >= next_avc) {
1449 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1452 next_avc = buf_index + nalsize;
1454 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1455 if (buf_index >= buf_size)
1459 hx = h->thread_context[context_count];
1461 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1462 &consumed, next_avc - buf_index);
1463 if (!ptr || dst_length < 0) {
1468 bit_length = get_bit_length(h, buf, ptr, dst_length,
1469 buf_index + consumed, next_avc);
1471 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1472 av_log(h->avctx, AV_LOG_DEBUG,
1473 "NAL %d at %d/%d length %d\n",
1474 hx->nal_unit_type, buf_index, buf_size, dst_length);
1476 if (h->is_avc && (nalsize != consumed) && nalsize)
1477 av_log(h->avctx, AV_LOG_DEBUG,
1478 "AVC: Consumed only %d bytes instead of %d\n",
1481 buf_index += consumed;
1484 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1485 h->nal_ref_idc == 0 &&
1486 h->nal_unit_type != NAL_SEI)
1490 /* Ignore every NAL unit type except PPS and SPS during extradata
1491 * parsing. Decoding slices is not possible in codec init
1493 if (parse_extradata && HAVE_THREADS &&
1494 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1495 (hx->nal_unit_type != NAL_PPS &&
1496 hx->nal_unit_type != NAL_SPS)) {
1497 if (hx->nal_unit_type < NAL_AUD ||
1498 hx->nal_unit_type > NAL_AUXILIARY_SLICE)
1499 av_log(avctx, AV_LOG_INFO,
1500 "Ignoring NAL unit %d during extradata parsing\n",
1502 hx->nal_unit_type = NAL_FF_IGNORE;
1505 switch (hx->nal_unit_type) {
1507 if (h->nal_unit_type != NAL_IDR_SLICE) {
1508 av_log(h->avctx, AV_LOG_ERROR,
1509 "Invalid mix of idr and non-idr slices\n");
1513 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1515 init_get_bits(&hx->gb, ptr, bit_length);
1517 hx->inter_gb_ptr = &hx->gb;
1518 hx->data_partitioning = 0;
1520 if ((err = ff_h264_decode_slice_header(hx, h)))
1523 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1524 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1525 ((1 << h->sps.log2_max_frame_num) - 1);
1528 h->cur_pic_ptr->f.key_frame |=
1529 (hx->nal_unit_type == NAL_IDR_SLICE) ||
1530 (h->sei_recovery_frame_cnt >= 0);
1532 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1533 h->recovery_frame == h->frame_num) {
1534 h->recovery_frame = -1;
1535 h->cur_pic_ptr->recovered = 1;
1537 // If we have an IDR, all frames after it in decoded order are
1539 if (hx->nal_unit_type == NAL_IDR_SLICE)
1540 h->frame_recovered |= FRAME_RECOVERED_IDR;
1541 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1543 if (h->current_slice == 1) {
1544 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1545 decode_postinit(h, nal_index >= nals_needed);
1547 if (h->avctx->hwaccel &&
1548 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1552 if (hx->redundant_pic_count == 0 &&
1553 (avctx->skip_frame < AVDISCARD_NONREF ||
1555 (avctx->skip_frame < AVDISCARD_BIDIR ||
1556 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1557 (avctx->skip_frame < AVDISCARD_NONKEY ||
1558 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1559 avctx->skip_frame < AVDISCARD_ALL) {
1560 if (avctx->hwaccel) {
1561 ret = avctx->hwaccel->decode_slice(avctx,
1562 &buf[buf_index - consumed],
1571 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
1572 av_log(h->avctx, AV_LOG_ERROR,
1573 "Decoding in chunks is not supported for "
1574 "partitioned slices.\n");
1575 return AVERROR(ENOSYS);
1578 init_get_bits(&hx->gb, ptr, bit_length);
1580 hx->inter_gb_ptr = NULL;
1582 if ((err = ff_h264_decode_slice_header(hx, h)) < 0) {
1583 /* make sure data_partitioning is cleared if it was set
1584 * before, so we don't try decoding a slice without a valid
1585 * slice header later */
1586 h->data_partitioning = 0;
1590 hx->data_partitioning = 1;
1593 init_get_bits(&hx->intra_gb, ptr, bit_length);
1594 hx->intra_gb_ptr = &hx->intra_gb;
1597 init_get_bits(&hx->inter_gb, ptr, bit_length);
1598 hx->inter_gb_ptr = &hx->inter_gb;
1600 if (hx->redundant_pic_count == 0 &&
1602 hx->data_partitioning &&
1603 h->cur_pic_ptr && h->context_initialized &&
1604 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
1605 (avctx->skip_frame < AVDISCARD_BIDIR ||
1606 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1607 (avctx->skip_frame < AVDISCARD_NONKEY ||
1608 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1609 avctx->skip_frame < AVDISCARD_ALL)
1613 init_get_bits(&h->gb, ptr, bit_length);
1614 ret = ff_h264_decode_sei(h);
1615 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1619 init_get_bits(&h->gb, ptr, bit_length);
1620 ret = ff_h264_decode_seq_parameter_set(h);
1621 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
1622 av_log(h->avctx, AV_LOG_DEBUG,
1623 "SPS decoding failure, trying again with the complete NAL\n");
1624 init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
1626 ff_h264_decode_seq_parameter_set(h);
1629 ret = ff_h264_set_parameter_from_sps(h);
1635 init_get_bits(&h->gb, ptr, bit_length);
1636 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1637 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1641 case NAL_END_SEQUENCE:
1642 case NAL_END_STREAM:
1643 case NAL_FILLER_DATA:
1645 case NAL_AUXILIARY_SLICE:
1650 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1651 hx->nal_unit_type, bit_length);
1654 if (context_count == h->max_contexts) {
1655 ret = ff_h264_execute_decode_slices(h, context_count);
1656 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1662 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1663 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1664 } else if (err == 1) {
1665 /* Slice could not be decoded in parallel mode, copy down
1666 * NAL unit stuff to context 0 and restart. Note that
1667 * rbsp_buffer is not transferred, but since we no longer
1668 * run in parallel mode this should not be an issue. */
1669 h->nal_unit_type = hx->nal_unit_type;
1670 h->nal_ref_idc = hx->nal_ref_idc;
1676 if (context_count) {
1677 ret = ff_h264_execute_decode_slices(h, context_count);
1678 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1685 if (h->cur_pic_ptr && !h->droppable) {
1686 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1687 h->picture_structure == PICT_BOTTOM_FIELD);
1690 return (ret < 0) ? ret : buf_index;
1694 * Return the number of bytes consumed for building the current frame.
1696 static int get_consumed_bytes(int pos, int buf_size)
1699 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1700 if (pos + 10 > buf_size)
1701 pos = buf_size; // oops ;)
1706 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1709 int ret = av_frame_ref(dst, src);
1716 for (i = 0; i < 3; i++) {
1717 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1718 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1719 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1720 (h->sps.crop_top >> vshift) * dst->linesize[i];
1721 dst->data[i] += off;
1726 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1727 int *got_frame, AVPacket *avpkt)
1729 const uint8_t *buf = avpkt->data;
1730 int buf_size = avpkt->size;
1731 H264Context *h = avctx->priv_data;
1732 AVFrame *pict = data;
1736 h->flags = avctx->flags;
1737 /* reset data partitioning here, to ensure GetBitContexts from previous
1738 * packets do not get used. */
1739 h->data_partitioning = 0;
1741 /* end of stream, output what is still in the buffers */
1743 if (buf_size == 0) {
1747 h->cur_pic_ptr = NULL;
1749 // FIXME factorize this with the output code below
1750 out = h->delayed_pic[0];
1753 h->delayed_pic[i] &&
1754 !h->delayed_pic[i]->f.key_frame &&
1755 !h->delayed_pic[i]->mmco_reset;
1757 if (h->delayed_pic[i]->poc < out->poc) {
1758 out = h->delayed_pic[i];
1762 for (i = out_idx; h->delayed_pic[i]; i++)
1763 h->delayed_pic[i] = h->delayed_pic[i + 1];
1766 ret = output_frame(h, pict, &out->f);
1775 buf_index = decode_nal_units(h, buf, buf_size, 0);
1777 return AVERROR_INVALIDDATA;
1779 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1784 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1785 if (avctx->skip_frame >= AVDISCARD_NONREF)
1787 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1788 return AVERROR_INVALIDDATA;
1791 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1792 (h->mb_y >= h->mb_height && h->mb_height)) {
1793 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1794 decode_postinit(h, 1);
1796 ff_h264_field_end(h, 0);
1799 if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
1800 h->next_output_pic->recovered)) {
1801 if (!h->next_output_pic->recovered)
1802 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1804 ret = output_frame(h, pict, &h->next_output_pic->f);
1811 assert(pict->buf[0] || !*got_frame);
1813 return get_consumed_bytes(buf_index, buf_size);
1816 av_cold void ff_h264_free_context(H264Context *h)
1820 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1822 for (i = 0; i < MAX_SPS_COUNT; i++)
1823 av_freep(h->sps_buffers + i);
1825 for (i = 0; i < MAX_PPS_COUNT; i++)
1826 av_freep(h->pps_buffers + i);
1829 static av_cold int h264_decode_end(AVCodecContext *avctx)
1831 H264Context *h = avctx->priv_data;
1833 ff_h264_free_context(h);
1835 ff_h264_unref_picture(h, &h->cur_pic);
1840 static const AVProfile profiles[] = {
1841 { FF_PROFILE_H264_BASELINE, "Baseline" },
1842 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1843 { FF_PROFILE_H264_MAIN, "Main" },
1844 { FF_PROFILE_H264_EXTENDED, "Extended" },
1845 { FF_PROFILE_H264_HIGH, "High" },
1846 { FF_PROFILE_H264_HIGH_10, "High 10" },
1847 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1848 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1849 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1850 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1851 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1852 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1853 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1854 { FF_PROFILE_UNKNOWN },
1857 AVCodec ff_h264_decoder = {
1859 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1860 .type = AVMEDIA_TYPE_VIDEO,
1861 .id = AV_CODEC_ID_H264,
1862 .priv_data_size = sizeof(H264Context),
1863 .init = ff_h264_decode_init,
1864 .close = h264_decode_end,
1865 .decode = h264_decode_frame,
1866 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1867 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1868 CODEC_CAP_FRAME_THREADS,
1870 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1871 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1872 .profiles = NULL_IF_CONFIG_SMALL(profiles),