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/imgutils.h"
30 #include "libavutil/stereo3d.h"
31 #include "libavutil/timer.h"
34 #include "cabac_functions.h"
36 #include "error_resilience.h"
40 #include "h264chroma.h"
41 #include "h264_mvpred.h"
44 #include "mpegutils.h"
45 #include "rectangle.h"
51 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
53 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
55 int mb_x, int mb_y, int mb_intra, int mb_skipped)
57 H264Context *h = opaque;
61 h->mb_xy = mb_x + mb_y * h->mb_stride;
62 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
64 /* FIXME: It is possible albeit uncommon that slice references
65 * differ between slices. We take the easy approach and ignore
66 * it for now. If this turns out to have any relevance in
67 * practice then correct remapping should be added. */
68 if (ref >= h->ref_count[0])
70 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
72 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
73 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
74 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
75 assert(!FRAME_MBAFF(h));
76 ff_h264_hl_decode_mb(h);
79 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
81 AVCodecContext *avctx = h->avctx;
82 AVFrame *cur = &h->cur_pic.f;
83 AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
84 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
85 int vshift = desc->log2_chroma_h;
86 const int field_pic = h->picture_structure != PICT_FRAME;
92 height = FFMIN(height, avctx->height - y);
94 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
97 if (avctx->draw_horiz_band) {
99 int offset[AV_NUM_DATA_POINTERS];
102 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
103 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
110 offset[0] = y * src->linesize[0];
112 offset[2] = (y >> vshift) * src->linesize[1];
113 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
118 avctx->draw_horiz_band(avctx, src, offset,
119 y, h->picture_structure, height);
124 * Check if the top & left blocks are available if needed and
125 * change the dc mode so it only uses the available blocks.
127 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
129 static const int8_t top[12] = {
130 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
132 static const int8_t left[12] = {
133 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
137 if (!(h->top_samples_available & 0x8000)) {
138 for (i = 0; i < 4; i++) {
139 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
141 av_log(h->avctx, AV_LOG_ERROR,
142 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
143 status, h->mb_x, h->mb_y);
144 return AVERROR_INVALIDDATA;
146 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
151 if ((h->left_samples_available & 0x8888) != 0x8888) {
152 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
153 for (i = 0; i < 4; i++)
154 if (!(h->left_samples_available & mask[i])) {
155 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
157 av_log(h->avctx, AV_LOG_ERROR,
158 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
159 status, h->mb_x, h->mb_y);
160 return AVERROR_INVALIDDATA;
162 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
168 } // FIXME cleanup like ff_h264_check_intra_pred_mode
171 * Check if the top & left blocks are available if needed and
172 * change the dc mode so it only uses the available blocks.
174 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
176 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
177 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
180 av_log(h->avctx, AV_LOG_ERROR,
181 "out of range intra chroma pred mode at %d %d\n",
183 return AVERROR_INVALIDDATA;
186 if (!(h->top_samples_available & 0x8000)) {
189 av_log(h->avctx, AV_LOG_ERROR,
190 "top block unavailable for requested intra mode at %d %d\n",
192 return AVERROR_INVALIDDATA;
196 if ((h->left_samples_available & 0x8080) != 0x8080) {
198 if (is_chroma && (h->left_samples_available & 0x8080)) {
199 // mad cow disease mode, aka MBAFF + constrained_intra_pred
200 mode = ALZHEIMER_DC_L0T_PRED8x8 +
201 (!(h->left_samples_available & 0x8000)) +
202 2 * (mode == DC_128_PRED8x8);
205 av_log(h->avctx, AV_LOG_ERROR,
206 "left block unavailable for requested intra mode at %d %d\n",
208 return AVERROR_INVALIDDATA;
215 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
216 int *dst_length, int *consumed, int length)
222 // src[0]&0x80; // forbidden bit
223 h->nal_ref_idc = src[0] >> 5;
224 h->nal_unit_type = src[0] & 0x1F;
229 #define STARTCODE_TEST \
230 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
231 if (src[i + 2] != 3) { \
232 /* startcode, so we must be past the end */ \
238 #if HAVE_FAST_UNALIGNED
239 #define FIND_FIRST_ZERO \
240 if (i > 0 && !src[i]) \
246 for (i = 0; i + 1 < length; i += 9) {
247 if (!((~AV_RN64A(src + i) &
248 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
249 0x8000800080008080ULL))
256 for (i = 0; i + 1 < length; i += 5) {
257 if (!((~AV_RN32A(src + i) &
258 (AV_RN32A(src + i) - 0x01000101U)) &
267 for (i = 0; i + 1 < length; i += 2) {
270 if (i > 0 && src[i - 1] == 0)
276 if (i >= length - 1) { // no escaped 0
277 *dst_length = length;
278 *consumed = length + 1; // +1 for the header
282 // use second escape buffer for inter data
283 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
284 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
285 length + FF_INPUT_BUFFER_PADDING_SIZE);
286 dst = h->rbsp_buffer[bufidx];
293 while (si + 2 < length) {
294 // remove escapes (very rare 1:2^22)
295 if (src[si + 2] > 3) {
296 dst[di++] = src[si++];
297 dst[di++] = src[si++];
298 } else if (src[si] == 0 && src[si + 1] == 0) {
299 if (src[si + 2] == 3) { // escape
304 } else // next start code
308 dst[di++] = src[si++];
311 dst[di++] = src[si++];
314 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
317 *consumed = si + 1; // +1 for the header
318 /* FIXME store exact number of bits in the getbitcontext
319 * (it is needed for decoding) */
324 * Identify the exact end of the bitstream
325 * @return the length of the trailing, or 0 if damaged
327 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
332 tprintf(h->avctx, "rbsp trailing %X\n", v);
334 for (r = 1; r < 9; r++) {
342 void ff_h264_free_tables(H264Context *h, int free_rbsp)
347 av_freep(&h->intra4x4_pred_mode);
348 av_freep(&h->chroma_pred_mode_table);
349 av_freep(&h->cbp_table);
350 av_freep(&h->mvd_table[0]);
351 av_freep(&h->mvd_table[1]);
352 av_freep(&h->direct_table);
353 av_freep(&h->non_zero_count);
354 av_freep(&h->slice_table_base);
355 h->slice_table = NULL;
356 av_freep(&h->list_counts);
358 av_freep(&h->mb2b_xy);
359 av_freep(&h->mb2br_xy);
361 av_buffer_pool_uninit(&h->qscale_table_pool);
362 av_buffer_pool_uninit(&h->mb_type_pool);
363 av_buffer_pool_uninit(&h->motion_val_pool);
364 av_buffer_pool_uninit(&h->ref_index_pool);
366 if (free_rbsp && h->DPB) {
367 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
368 ff_h264_unref_picture(h, &h->DPB[i]);
371 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
372 h->DPB[i].needs_realloc = 1;
375 h->cur_pic_ptr = NULL;
377 for (i = 0; i < H264_MAX_THREADS; i++) {
378 hx = h->thread_context[i];
381 av_freep(&hx->top_borders[1]);
382 av_freep(&hx->top_borders[0]);
383 av_freep(&hx->bipred_scratchpad);
384 av_freep(&hx->edge_emu_buffer);
385 av_freep(&hx->dc_val_base);
386 av_freep(&hx->er.mb_index2xy);
387 av_freep(&hx->er.error_status_table);
388 av_freep(&hx->er.er_temp_buffer);
389 av_freep(&hx->er.mbintra_table);
390 av_freep(&hx->er.mbskip_table);
393 av_freep(&hx->rbsp_buffer[1]);
394 av_freep(&hx->rbsp_buffer[0]);
395 hx->rbsp_buffer_size[0] = 0;
396 hx->rbsp_buffer_size[1] = 0;
399 av_freep(&h->thread_context[i]);
403 int ff_h264_alloc_tables(H264Context *h)
405 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
406 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
409 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
410 row_mb_num * 8 * sizeof(uint8_t), fail)
411 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
412 big_mb_num * 48 * sizeof(uint8_t), fail)
413 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
414 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
415 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
416 big_mb_num * sizeof(uint16_t), fail)
417 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
418 big_mb_num * sizeof(uint8_t), fail)
419 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
420 16 * row_mb_num * sizeof(uint8_t), fail);
421 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
422 16 * row_mb_num * sizeof(uint8_t), fail);
423 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
424 4 * big_mb_num * sizeof(uint8_t), fail);
425 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
426 big_mb_num * sizeof(uint8_t), fail)
428 memset(h->slice_table_base, -1,
429 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
430 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
432 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
433 big_mb_num * sizeof(uint32_t), fail);
434 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
435 big_mb_num * sizeof(uint32_t), fail);
436 for (y = 0; y < h->mb_height; y++)
437 for (x = 0; x < h->mb_width; x++) {
438 const int mb_xy = x + y * h->mb_stride;
439 const int b_xy = 4 * x + 4 * y * h->b_stride;
441 h->mb2b_xy[mb_xy] = b_xy;
442 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
445 if (!h->dequant4_coeff[0])
446 h264_init_dequant_tables(h);
449 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
451 return AVERROR(ENOMEM);
452 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
453 av_frame_unref(&h->DPB[i].f);
454 av_frame_unref(&h->cur_pic.f);
460 ff_h264_free_tables(h, 1);
461 return AVERROR(ENOMEM);
466 * Allocate buffers which are not shared amongst multiple threads.
468 int ff_h264_context_init(H264Context *h)
470 ERContext *er = &h->er;
471 int mb_array_size = h->mb_height * h->mb_stride;
472 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
473 int c_size = h->mb_stride * (h->mb_height + 1);
474 int yc_size = y_size + 2 * c_size;
477 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
478 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
479 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
480 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
482 h->ref_cache[0][scan8[5] + 1] =
483 h->ref_cache[0][scan8[7] + 1] =
484 h->ref_cache[0][scan8[13] + 1] =
485 h->ref_cache[1][scan8[5] + 1] =
486 h->ref_cache[1][scan8[7] + 1] =
487 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
489 if (CONFIG_ERROR_RESILIENCE) {
491 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 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
504 fail); // error ressilience code looks cleaner with this
505 for (y = 0; y < h->mb_height; y++)
506 for (x = 0; x < h->mb_width; x++)
507 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
509 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
510 h->mb_stride + h->mb_width;
512 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
513 mb_array_size * sizeof(uint8_t), fail);
515 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
516 memset(er->mbintra_table, 1, mb_array_size);
518 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
520 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
523 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
524 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
525 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
526 er->dc_val[2] = er->dc_val[1] + c_size;
527 for (i = 0; i < yc_size; i++)
528 h->dc_val_base[i] = 1024;
534 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
537 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
538 int parse_extradata);
540 int ff_h264_decode_extradata(H264Context *h)
542 AVCodecContext *avctx = h->avctx;
545 if (avctx->extradata[0] == 1) {
547 unsigned char *p = avctx->extradata;
551 if (avctx->extradata_size < 7) {
552 av_log(avctx, AV_LOG_ERROR,
553 "avcC %d too short\n", avctx->extradata_size);
554 return AVERROR_INVALIDDATA;
556 /* sps and pps in the avcC always have length coded with 2 bytes,
557 * so put a fake nal_length_size = 2 while parsing them */
558 h->nal_length_size = 2;
559 // Decode sps from avcC
560 cnt = *(p + 5) & 0x1f; // Number of sps
562 for (i = 0; i < cnt; i++) {
563 nalsize = AV_RB16(p) + 2;
564 if (p - avctx->extradata + nalsize > avctx->extradata_size)
565 return AVERROR_INVALIDDATA;
566 ret = decode_nal_units(h, p, nalsize, 1);
568 av_log(avctx, AV_LOG_ERROR,
569 "Decoding sps %d from avcC failed\n", i);
574 // Decode pps from avcC
575 cnt = *(p++); // Number of pps
576 for (i = 0; i < cnt; i++) {
577 nalsize = AV_RB16(p) + 2;
578 if (p - avctx->extradata + nalsize > avctx->extradata_size)
579 return AVERROR_INVALIDDATA;
580 ret = decode_nal_units(h, p, nalsize, 1);
582 av_log(avctx, AV_LOG_ERROR,
583 "Decoding pps %d from avcC failed\n", i);
588 // Now store right nal length size, that will be used to parse all other nals
589 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
592 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
599 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
601 H264Context *h = avctx->priv_data;
607 h->bit_depth_luma = 8;
608 h->chroma_format_idc = 1;
610 ff_h264dsp_init(&h->h264dsp, 8, 1);
611 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
612 ff_h264qpel_init(&h->h264qpel, 8);
613 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
615 h->dequant_coeff_pps = -1;
617 /* needed so that IDCT permutation is known early */
618 if (CONFIG_ERROR_RESILIENCE)
619 ff_dsputil_init(&h->dsp, h->avctx);
620 ff_videodsp_init(&h->vdsp, 8);
622 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
623 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
625 h->picture_structure = PICT_FRAME;
626 h->slice_context_count = 1;
627 h->workaround_bugs = avctx->workaround_bugs;
628 h->flags = avctx->flags;
631 // s->decode_mb = ff_h263_decode_mb;
632 if (!avctx->has_b_frames)
635 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
637 ff_h264_decode_init_vlc();
639 ff_init_cabac_states();
642 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
644 h->thread_context[0] = h;
645 h->outputed_poc = h->next_outputed_poc = INT_MIN;
646 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
647 h->last_pocs[i] = INT_MIN;
648 h->prev_poc_msb = 1 << 16;
650 ff_h264_reset_sei(h);
651 h->recovery_frame = -1;
652 h->frame_recovered = 0;
653 if (avctx->codec_id == AV_CODEC_ID_H264) {
654 if (avctx->ticks_per_frame == 1)
655 h->avctx->time_base.den *= 2;
656 avctx->ticks_per_frame = 2;
659 if (avctx->extradata_size > 0 && avctx->extradata) {
660 ret = ff_h264_decode_extradata(h);
665 if (h->sps.bitstream_restriction_flag &&
666 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
667 h->avctx->has_b_frames = h->sps.num_reorder_frames;
671 avctx->internal->allocate_progress = 1;
676 static int decode_init_thread_copy(AVCodecContext *avctx)
678 H264Context *h = avctx->priv_data;
680 if (!avctx->internal->is_copy)
682 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
683 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
685 h->context_initialized = 0;
691 * Run setup operations that must be run after slice header decoding.
692 * This includes finding the next displayed frame.
694 * @param h h264 master context
695 * @param setup_finished enough NALs have been read that we can call
696 * ff_thread_finish_setup()
698 static void decode_postinit(H264Context *h, int setup_finished)
700 H264Picture *out = h->cur_pic_ptr;
701 H264Picture *cur = h->cur_pic_ptr;
702 int i, pics, out_of_order, out_idx;
703 int invalid = 0, cnt = 0;
705 h->cur_pic_ptr->f.pict_type = h->pict_type;
707 if (h->next_output_pic)
710 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
711 /* FIXME: if we have two PAFF fields in one packet, we can't start
712 * the next thread here. If we have one field per packet, we can.
713 * The check in decode_nal_units() is not good enough to find this
714 * yet, so we assume the worst for now. */
715 // if (setup_finished)
716 // ff_thread_finish_setup(h->avctx);
720 cur->f.interlaced_frame = 0;
721 cur->f.repeat_pict = 0;
723 /* Signal interlacing information externally. */
724 /* Prioritize picture timing SEI information over used
725 * decoding process if it exists. */
727 if (h->sps.pic_struct_present_flag) {
728 switch (h->sei_pic_struct) {
729 case SEI_PIC_STRUCT_FRAME:
731 case SEI_PIC_STRUCT_TOP_FIELD:
732 case SEI_PIC_STRUCT_BOTTOM_FIELD:
733 cur->f.interlaced_frame = 1;
735 case SEI_PIC_STRUCT_TOP_BOTTOM:
736 case SEI_PIC_STRUCT_BOTTOM_TOP:
737 if (FIELD_OR_MBAFF_PICTURE(h))
738 cur->f.interlaced_frame = 1;
740 // try to flag soft telecine progressive
741 cur->f.interlaced_frame = h->prev_interlaced_frame;
743 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
744 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
745 /* Signal the possibility of telecined film externally
746 * (pic_struct 5,6). From these hints, let the applications
747 * decide if they apply deinterlacing. */
748 cur->f.repeat_pict = 1;
750 case SEI_PIC_STRUCT_FRAME_DOUBLING:
751 cur->f.repeat_pict = 2;
753 case SEI_PIC_STRUCT_FRAME_TRIPLING:
754 cur->f.repeat_pict = 4;
758 if ((h->sei_ct_type & 3) &&
759 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
760 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
762 /* Derive interlacing flag from used decoding process. */
763 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
765 h->prev_interlaced_frame = cur->f.interlaced_frame;
767 if (cur->field_poc[0] != cur->field_poc[1]) {
768 /* Derive top_field_first from field pocs. */
769 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
771 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
772 /* Use picture timing SEI information. Even if it is a
773 * information of a past frame, better than nothing. */
774 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
775 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
776 cur->f.top_field_first = 1;
778 cur->f.top_field_first = 0;
780 /* Most likely progressive */
781 cur->f.top_field_first = 0;
785 if (h->sei_frame_packing_present &&
786 h->frame_packing_arrangement_type >= 0 &&
787 h->frame_packing_arrangement_type <= 6 &&
788 h->content_interpretation_type > 0 &&
789 h->content_interpretation_type < 3) {
790 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
794 switch (h->frame_packing_arrangement_type) {
796 stereo->type = AV_STEREO3D_CHECKERBOARD;
799 stereo->type = AV_STEREO3D_LINES;
802 stereo->type = AV_STEREO3D_COLUMNS;
805 if (h->quincunx_subsampling)
806 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
808 stereo->type = AV_STEREO3D_SIDEBYSIDE;
811 stereo->type = AV_STEREO3D_TOPBOTTOM;
814 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
817 stereo->type = AV_STEREO3D_2D;
821 if (h->content_interpretation_type == 2)
822 stereo->flags = AV_STEREO3D_FLAG_INVERT;
825 // FIXME do something with unavailable reference frames
827 /* Sort B-frames into display order */
829 if (h->sps.bitstream_restriction_flag &&
830 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
831 h->avctx->has_b_frames = h->sps.num_reorder_frames;
835 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
836 !h->sps.bitstream_restriction_flag) {
837 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
842 while (h->delayed_pic[pics])
845 assert(pics <= MAX_DELAYED_PIC_COUNT);
847 h->delayed_pic[pics++] = cur;
848 if (cur->reference == 0)
849 cur->reference = DELAYED_PIC_REF;
851 /* Frame reordering. This code takes pictures from coding order and sorts
852 * them by their incremental POC value into display order. It supports POC
853 * gaps, MMCO reset codes and random resets.
854 * A "display group" can start either with a IDR frame (f.key_frame = 1),
855 * and/or can be closed down with a MMCO reset code. In sequences where
856 * there is no delay, we can't detect that (since the frame was already
857 * output to the user), so we also set h->mmco_reset to detect the MMCO
859 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
860 * we increase the delay between input and output. All frames affected by
861 * the lag (e.g. those that should have been output before another frame
862 * that we already returned to the user) will be dropped. This is a bug
863 * that we will fix later. */
864 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
865 cnt += out->poc < h->last_pocs[i];
866 invalid += out->poc == INT_MIN;
868 if (!h->mmco_reset && !cur->f.key_frame &&
869 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
872 h->delayed_pic[pics - 2]->mmco_reset = 2;
874 if (h->mmco_reset || cur->f.key_frame) {
875 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
876 h->last_pocs[i] = INT_MIN;
878 invalid = MAX_DELAYED_PIC_COUNT;
880 out = h->delayed_pic[0];
882 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
884 !h->delayed_pic[i - 1]->mmco_reset &&
885 !h->delayed_pic[i]->f.key_frame;
887 if (h->delayed_pic[i]->poc < out->poc) {
888 out = h->delayed_pic[i];
891 if (h->avctx->has_b_frames == 0 &&
892 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
893 h->next_outputed_poc = INT_MIN;
894 out_of_order = !out->f.key_frame && !h->mmco_reset &&
895 (out->poc < h->next_outputed_poc);
897 if (h->sps.bitstream_restriction_flag &&
898 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
899 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
900 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
901 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
902 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
905 } else if (h->low_delay &&
906 ((h->next_outputed_poc != INT_MIN &&
907 out->poc > h->next_outputed_poc + 2) ||
908 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
910 h->avctx->has_b_frames++;
913 if (pics > h->avctx->has_b_frames) {
914 out->reference &= ~DELAYED_PIC_REF;
915 // for frame threading, the owner must be the second field's thread or
916 // else the first thread can release the picture and reuse it unsafely
917 for (i = out_idx; h->delayed_pic[i]; i++)
918 h->delayed_pic[i] = h->delayed_pic[i + 1];
920 memmove(h->last_pocs, &h->last_pocs[1],
921 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
922 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
923 if (!out_of_order && pics > h->avctx->has_b_frames) {
924 h->next_output_pic = out;
925 if (out->mmco_reset) {
927 h->next_outputed_poc = out->poc;
928 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
930 h->next_outputed_poc = INT_MIN;
933 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
934 h->next_outputed_poc = INT_MIN;
936 h->next_outputed_poc = out->poc;
941 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
944 if (h->next_output_pic) {
945 if (h->next_output_pic->recovered) {
946 // We have reached an recovery point and all frames after it in
947 // display order are "recovered".
948 h->frame_recovered |= FRAME_RECOVERED_SEI;
950 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
953 if (setup_finished && !h->avctx->hwaccel)
954 ff_thread_finish_setup(h->avctx);
957 int ff_pred_weight_table(H264Context *h)
960 int luma_def, chroma_def;
963 h->use_weight_chroma = 0;
964 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
965 if (h->sps.chroma_format_idc)
966 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
967 luma_def = 1 << h->luma_log2_weight_denom;
968 chroma_def = 1 << h->chroma_log2_weight_denom;
970 for (list = 0; list < 2; list++) {
971 h->luma_weight_flag[list] = 0;
972 h->chroma_weight_flag[list] = 0;
973 for (i = 0; i < h->ref_count[list]; i++) {
974 int luma_weight_flag, chroma_weight_flag;
976 luma_weight_flag = get_bits1(&h->gb);
977 if (luma_weight_flag) {
978 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
979 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
980 if (h->luma_weight[i][list][0] != luma_def ||
981 h->luma_weight[i][list][1] != 0) {
983 h->luma_weight_flag[list] = 1;
986 h->luma_weight[i][list][0] = luma_def;
987 h->luma_weight[i][list][1] = 0;
990 if (h->sps.chroma_format_idc) {
991 chroma_weight_flag = get_bits1(&h->gb);
992 if (chroma_weight_flag) {
994 for (j = 0; j < 2; j++) {
995 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
996 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
997 if (h->chroma_weight[i][list][j][0] != chroma_def ||
998 h->chroma_weight[i][list][j][1] != 0) {
999 h->use_weight_chroma = 1;
1000 h->chroma_weight_flag[list] = 1;
1005 for (j = 0; j < 2; j++) {
1006 h->chroma_weight[i][list][j][0] = chroma_def;
1007 h->chroma_weight[i][list][j][1] = 0;
1012 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1015 h->use_weight = h->use_weight || h->use_weight_chroma;
1020 * instantaneous decoder refresh.
1022 static void idr(H264Context *h)
1024 ff_h264_remove_all_refs(h);
1025 h->prev_frame_num = 0;
1026 h->prev_frame_num_offset = 0;
1028 h->prev_poc_lsb = 0;
1031 /* forget old pics after a seek */
1032 void ff_h264_flush_change(H264Context *h)
1035 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1036 h->last_pocs[i] = INT_MIN;
1037 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1038 h->prev_interlaced_frame = 1;
1041 h->cur_pic_ptr->reference = 0;
1043 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
1044 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
1045 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
1046 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
1047 ff_h264_reset_sei(h);
1048 h->recovery_frame = -1;
1049 h->frame_recovered = 0;
1052 /* forget old pics after a seek */
1053 static void flush_dpb(AVCodecContext *avctx)
1055 H264Context *h = avctx->priv_data;
1058 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1059 if (h->delayed_pic[i])
1060 h->delayed_pic[i]->reference = 0;
1061 h->delayed_pic[i] = NULL;
1064 ff_h264_flush_change(h);
1067 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1068 ff_h264_unref_picture(h, &h->DPB[i]);
1069 h->cur_pic_ptr = NULL;
1070 ff_h264_unref_picture(h, &h->cur_pic);
1072 h->mb_x = h->mb_y = 0;
1074 h->parse_context.state = -1;
1075 h->parse_context.frame_start_found = 0;
1076 h->parse_context.overread = 0;
1077 h->parse_context.overread_index = 0;
1078 h->parse_context.index = 0;
1079 h->parse_context.last_index = 0;
1081 ff_h264_free_tables(h, 1);
1082 h->context_initialized = 0;
1085 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1087 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1090 h->frame_num_offset = h->prev_frame_num_offset;
1091 if (h->frame_num < h->prev_frame_num)
1092 h->frame_num_offset += max_frame_num;
1094 if (h->sps.poc_type == 0) {
1095 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1097 if (h->poc_lsb < h->prev_poc_lsb &&
1098 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1099 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1100 else if (h->poc_lsb > h->prev_poc_lsb &&
1101 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1102 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1104 h->poc_msb = h->prev_poc_msb;
1106 field_poc[1] = h->poc_msb + h->poc_lsb;
1107 if (h->picture_structure == PICT_FRAME)
1108 field_poc[1] += h->delta_poc_bottom;
1109 } else if (h->sps.poc_type == 1) {
1110 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1113 if (h->sps.poc_cycle_length != 0)
1114 abs_frame_num = h->frame_num_offset + h->frame_num;
1118 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1121 expected_delta_per_poc_cycle = 0;
1122 for (i = 0; i < h->sps.poc_cycle_length; i++)
1123 // FIXME integrate during sps parse
1124 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1126 if (abs_frame_num > 0) {
1127 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1128 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1130 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1131 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1132 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1136 if (h->nal_ref_idc == 0)
1137 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1139 field_poc[0] = expectedpoc + h->delta_poc[0];
1140 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1142 if (h->picture_structure == PICT_FRAME)
1143 field_poc[1] += h->delta_poc[1];
1145 int poc = 2 * (h->frame_num_offset + h->frame_num);
1147 if (!h->nal_ref_idc)
1154 if (h->picture_structure != PICT_BOTTOM_FIELD)
1155 pic_field_poc[0] = field_poc[0];
1156 if (h->picture_structure != PICT_TOP_FIELD)
1157 pic_field_poc[1] = field_poc[1];
1158 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1164 * Compute profile from profile_idc and constraint_set?_flags.
1168 * @return profile as defined by FF_PROFILE_H264_*
1170 int ff_h264_get_profile(SPS *sps)
1172 int profile = sps->profile_idc;
1174 switch (sps->profile_idc) {
1175 case FF_PROFILE_H264_BASELINE:
1176 // constraint_set1_flag set to 1
1177 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1179 case FF_PROFILE_H264_HIGH_10:
1180 case FF_PROFILE_H264_HIGH_422:
1181 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1182 // constraint_set3_flag set to 1
1183 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1190 int ff_h264_set_parameter_from_sps(H264Context *h)
1192 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1193 (h->sps.bitstream_restriction_flag &&
1194 !h->sps.num_reorder_frames)) {
1195 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1196 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1197 "Reenabling low delay requires a codec flush.\n");
1202 if (h->avctx->has_b_frames < 2)
1203 h->avctx->has_b_frames = !h->low_delay;
1205 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1206 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1207 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
1208 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1209 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1210 h->pixel_shift = h->sps.bit_depth_luma > 8;
1212 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1213 h->sps.chroma_format_idc);
1214 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1215 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1216 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1217 h->sps.chroma_format_idc);
1218 if (CONFIG_ERROR_RESILIENCE)
1219 ff_dsputil_init(&h->dsp, h->avctx);
1220 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1222 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1223 h->sps.bit_depth_luma);
1224 return AVERROR_INVALIDDATA;
1230 int ff_set_ref_count(H264Context *h)
1232 int ref_count[2], list_count;
1233 int num_ref_idx_active_override_flag, max_refs;
1235 // set defaults, might be overridden a few lines later
1236 ref_count[0] = h->pps.ref_count[0];
1237 ref_count[1] = h->pps.ref_count[1];
1239 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1240 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1241 h->direct_spatial_mv_pred = get_bits1(&h->gb);
1242 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1244 if (num_ref_idx_active_override_flag) {
1245 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1246 if (ref_count[0] < 1)
1247 return AVERROR_INVALIDDATA;
1248 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1249 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1250 if (ref_count[1] < 1)
1251 return AVERROR_INVALIDDATA;
1255 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1261 ref_count[0] = ref_count[1] = 0;
1264 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1266 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1267 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1268 h->ref_count[0] = h->ref_count[1] = 0;
1269 return AVERROR_INVALIDDATA;
1272 if (list_count != h->list_count ||
1273 ref_count[0] != h->ref_count[0] ||
1274 ref_count[1] != h->ref_count[1]) {
1275 h->ref_count[0] = ref_count[0];
1276 h->ref_count[1] = ref_count[1];
1277 h->list_count = list_count;
1284 static int find_start_code(const uint8_t *buf, int buf_size,
1285 int buf_index, int next_avc)
1287 // start code prefix search
1288 for (; buf_index + 3 < next_avc; buf_index++)
1289 // This should always succeed in the first iteration.
1290 if (buf[buf_index] == 0 &&
1291 buf[buf_index + 1] == 0 &&
1292 buf[buf_index + 2] == 1)
1295 if (buf_index + 3 >= buf_size)
1298 return buf_index + 3;
1301 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1302 int buf_size, int *buf_index)
1306 if (*buf_index >= buf_size - h->nal_length_size)
1309 for (i = 0; i < h->nal_length_size; i++)
1310 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1311 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1312 av_log(h->avctx, AV_LOG_ERROR,
1313 "AVC: nal size %d\n", nalsize);
1319 static int get_bit_length(H264Context *h, const uint8_t *buf,
1320 const uint8_t *ptr, int dst_length,
1321 int i, int next_avc)
1323 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1324 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1325 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1326 h->workaround_bugs |= FF_BUG_TRUNCATED;
1328 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1329 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1335 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1338 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1340 int next_avc = h->is_avc ? 0 : buf_size;
1343 int nals_needed = 0;
1347 int dst_length, bit_length, consumed;
1350 if (buf_index >= next_avc) {
1351 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1354 next_avc = buf_index + nalsize;
1356 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1357 if (buf_index >= buf_size)
1361 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1362 next_avc - buf_index);
1364 if (ptr == NULL || dst_length < 0)
1365 return AVERROR_INVALIDDATA;
1367 buf_index += consumed;
1369 bit_length = get_bit_length(h, buf, ptr, dst_length,
1370 buf_index, next_avc);
1373 /* packets can sometimes contain multiple PPS/SPS,
1374 * e.g. two PAFF field pictures in one packet, or a demuxer
1375 * which splits NALs strangely if so, when frame threading we
1376 * can't start the next thread until we've read all of them */
1377 switch (h->nal_unit_type) {
1380 nals_needed = nal_index;
1385 init_get_bits(&h->gb, ptr, bit_length);
1386 if (!get_ue_golomb(&h->gb))
1387 nals_needed = nal_index;
1394 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1395 int parse_extradata)
1397 AVCodecContext *const avctx = h->avctx;
1398 H264Context *hx; ///< thread context
1400 unsigned context_count;
1402 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1406 h->max_contexts = h->slice_context_count;
1407 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1408 h->current_slice = 0;
1409 if (!h->first_field)
1410 h->cur_pic_ptr = NULL;
1411 ff_h264_reset_sei(h);
1414 if (avctx->active_thread_type & FF_THREAD_FRAME)
1415 nals_needed = get_last_needed_nal(h, buf, buf_size);
1420 next_avc = h->is_avc ? 0 : buf_size;
1430 if (buf_index >= next_avc) {
1431 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1434 next_avc = buf_index + nalsize;
1436 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1437 if (buf_index >= buf_size)
1441 hx = h->thread_context[context_count];
1443 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1444 &consumed, next_avc - buf_index);
1445 if (ptr == NULL || dst_length < 0) {
1450 bit_length = get_bit_length(h, buf, ptr, dst_length,
1451 buf_index + consumed, next_avc);
1453 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1454 av_log(h->avctx, AV_LOG_DEBUG,
1455 "NAL %d at %d/%d length %d\n",
1456 hx->nal_unit_type, buf_index, buf_size, dst_length);
1458 if (h->is_avc && (nalsize != consumed) && nalsize)
1459 av_log(h->avctx, AV_LOG_DEBUG,
1460 "AVC: Consumed only %d bytes instead of %d\n",
1463 buf_index += consumed;
1466 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1467 h->nal_ref_idc == 0 &&
1468 h->nal_unit_type != NAL_SEI)
1472 /* Ignore every NAL unit type except PPS and SPS during extradata
1473 * parsing. Decoding slices is not possible in codec init
1475 if (parse_extradata && HAVE_THREADS &&
1476 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1477 (hx->nal_unit_type != NAL_PPS &&
1478 hx->nal_unit_type != NAL_SPS)) {
1479 if (hx->nal_unit_type < NAL_AUD ||
1480 hx->nal_unit_type > NAL_AUXILIARY_SLICE)
1481 av_log(avctx, AV_LOG_INFO,
1482 "Ignoring NAL unit %d during extradata parsing\n",
1484 hx->nal_unit_type = NAL_FF_IGNORE;
1487 switch (hx->nal_unit_type) {
1489 if (h->nal_unit_type != NAL_IDR_SLICE) {
1490 av_log(h->avctx, AV_LOG_ERROR,
1491 "Invalid mix of idr and non-idr slices\n");
1495 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1497 init_get_bits(&hx->gb, ptr, bit_length);
1499 hx->inter_gb_ptr = &hx->gb;
1500 hx->data_partitioning = 0;
1502 if ((err = ff_h264_decode_slice_header(hx, h)))
1505 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1506 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1507 ((1 << h->sps.log2_max_frame_num) - 1);
1510 h->cur_pic_ptr->f.key_frame |=
1511 (hx->nal_unit_type == NAL_IDR_SLICE) ||
1512 (h->sei_recovery_frame_cnt >= 0);
1514 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1515 h->recovery_frame == h->frame_num) {
1516 h->recovery_frame = -1;
1517 h->cur_pic_ptr->recovered = 1;
1519 // If we have an IDR, all frames after it in decoded order are
1521 if (hx->nal_unit_type == NAL_IDR_SLICE)
1522 h->frame_recovered |= FRAME_RECOVERED_IDR;
1523 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1525 if (h->current_slice == 1) {
1526 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1527 decode_postinit(h, nal_index >= nals_needed);
1529 if (h->avctx->hwaccel &&
1530 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1534 if (hx->redundant_pic_count == 0 &&
1535 (avctx->skip_frame < AVDISCARD_NONREF ||
1537 (avctx->skip_frame < AVDISCARD_BIDIR ||
1538 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1539 (avctx->skip_frame < AVDISCARD_NONKEY ||
1540 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1541 avctx->skip_frame < AVDISCARD_ALL) {
1542 if (avctx->hwaccel) {
1543 ret = avctx->hwaccel->decode_slice(avctx,
1544 &buf[buf_index - consumed],
1553 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
1554 av_log(h->avctx, AV_LOG_ERROR,
1555 "Decoding in chunks is not supported for "
1556 "partitioned slices.\n");
1557 return AVERROR(ENOSYS);
1560 init_get_bits(&hx->gb, ptr, bit_length);
1562 hx->inter_gb_ptr = NULL;
1564 if ((err = ff_h264_decode_slice_header(hx, h)) < 0) {
1565 /* make sure data_partitioning is cleared if it was set
1566 * before, so we don't try decoding a slice without a valid
1567 * slice header later */
1568 h->data_partitioning = 0;
1572 hx->data_partitioning = 1;
1575 init_get_bits(&hx->intra_gb, ptr, bit_length);
1576 hx->intra_gb_ptr = &hx->intra_gb;
1579 init_get_bits(&hx->inter_gb, ptr, bit_length);
1580 hx->inter_gb_ptr = &hx->inter_gb;
1582 if (hx->redundant_pic_count == 0 &&
1584 hx->data_partitioning &&
1585 h->cur_pic_ptr && h->context_initialized &&
1586 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
1587 (avctx->skip_frame < AVDISCARD_BIDIR ||
1588 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1589 (avctx->skip_frame < AVDISCARD_NONKEY ||
1590 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1591 avctx->skip_frame < AVDISCARD_ALL)
1595 init_get_bits(&h->gb, ptr, bit_length);
1596 ret = ff_h264_decode_sei(h);
1597 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1601 init_get_bits(&h->gb, ptr, bit_length);
1602 ret = ff_h264_decode_seq_parameter_set(h);
1603 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
1604 av_log(h->avctx, AV_LOG_DEBUG,
1605 "SPS decoding failure, trying again with the complete NAL\n");
1606 init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
1608 ff_h264_decode_seq_parameter_set(h);
1611 ret = ff_h264_set_parameter_from_sps(h);
1617 init_get_bits(&h->gb, ptr, bit_length);
1618 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1619 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1623 case NAL_END_SEQUENCE:
1624 case NAL_END_STREAM:
1625 case NAL_FILLER_DATA:
1627 case NAL_AUXILIARY_SLICE:
1632 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1633 hx->nal_unit_type, bit_length);
1636 if (context_count == h->max_contexts) {
1637 ret = ff_h264_execute_decode_slices(h, context_count);
1638 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1644 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1645 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1646 } else if (err == 1) {
1647 /* Slice could not be decoded in parallel mode, copy down
1648 * NAL unit stuff to context 0 and restart. Note that
1649 * rbsp_buffer is not transferred, but since we no longer
1650 * run in parallel mode this should not be an issue. */
1651 h->nal_unit_type = hx->nal_unit_type;
1652 h->nal_ref_idc = hx->nal_ref_idc;
1658 if (context_count) {
1659 ret = ff_h264_execute_decode_slices(h, context_count);
1660 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1666 if (h->cur_pic_ptr && !h->droppable) {
1667 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1668 h->picture_structure == PICT_BOTTOM_FIELD);
1671 return (ret < 0) ? ret : buf_index;
1675 * Return the number of bytes consumed for building the current frame.
1677 static int get_consumed_bytes(int pos, int buf_size)
1680 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
1681 if (pos + 10 > buf_size)
1682 pos = buf_size; // oops ;)
1687 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1690 int ret = av_frame_ref(dst, src);
1697 for (i = 0; i < 3; i++) {
1698 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1699 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1700 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1701 (h->sps.crop_top >> vshift) * dst->linesize[i];
1702 dst->data[i] += off;
1707 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1708 int *got_frame, AVPacket *avpkt)
1710 const uint8_t *buf = avpkt->data;
1711 int buf_size = avpkt->size;
1712 H264Context *h = avctx->priv_data;
1713 AVFrame *pict = data;
1717 h->flags = avctx->flags;
1718 /* reset data partitioning here, to ensure GetBitContexts from previous
1719 * packets do not get used. */
1720 h->data_partitioning = 0;
1722 /* end of stream, output what is still in the buffers */
1724 if (buf_size == 0) {
1728 h->cur_pic_ptr = NULL;
1730 // FIXME factorize this with the output code below
1731 out = h->delayed_pic[0];
1734 h->delayed_pic[i] &&
1735 !h->delayed_pic[i]->f.key_frame &&
1736 !h->delayed_pic[i]->mmco_reset;
1738 if (h->delayed_pic[i]->poc < out->poc) {
1739 out = h->delayed_pic[i];
1743 for (i = out_idx; h->delayed_pic[i]; i++)
1744 h->delayed_pic[i] = h->delayed_pic[i + 1];
1747 ret = output_frame(h, pict, &out->f);
1756 buf_index = decode_nal_units(h, buf, buf_size, 0);
1758 return AVERROR_INVALIDDATA;
1760 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1765 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1766 if (avctx->skip_frame >= AVDISCARD_NONREF)
1768 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1769 return AVERROR_INVALIDDATA;
1772 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1773 (h->mb_y >= h->mb_height && h->mb_height)) {
1774 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1775 decode_postinit(h, 1);
1777 ff_h264_field_end(h, 0);
1780 if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
1781 h->next_output_pic->recovered)) {
1782 if (!h->next_output_pic->recovered)
1783 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1785 ret = output_frame(h, pict, &h->next_output_pic->f);
1792 assert(pict->buf[0] || !*got_frame);
1794 return get_consumed_bytes(buf_index, buf_size);
1797 av_cold void ff_h264_free_context(H264Context *h)
1801 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1803 for (i = 0; i < MAX_SPS_COUNT; i++)
1804 av_freep(h->sps_buffers + i);
1806 for (i = 0; i < MAX_PPS_COUNT; i++)
1807 av_freep(h->pps_buffers + i);
1810 static av_cold int h264_decode_end(AVCodecContext *avctx)
1812 H264Context *h = avctx->priv_data;
1814 ff_h264_free_context(h);
1816 ff_h264_unref_picture(h, &h->cur_pic);
1821 static const AVProfile profiles[] = {
1822 { FF_PROFILE_H264_BASELINE, "Baseline" },
1823 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1824 { FF_PROFILE_H264_MAIN, "Main" },
1825 { FF_PROFILE_H264_EXTENDED, "Extended" },
1826 { FF_PROFILE_H264_HIGH, "High" },
1827 { FF_PROFILE_H264_HIGH_10, "High 10" },
1828 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1829 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1830 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1831 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1832 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1833 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1834 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1835 { FF_PROFILE_UNKNOWN },
1838 AVCodec ff_h264_decoder = {
1840 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1841 .type = AVMEDIA_TYPE_VIDEO,
1842 .id = AV_CODEC_ID_H264,
1843 .priv_data_size = sizeof(H264Context),
1844 .init = ff_h264_decode_init,
1845 .close = h264_decode_end,
1846 .decode = h264_decode_frame,
1847 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1848 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1849 CODEC_CAP_FRAME_THREADS,
1851 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1852 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1853 .profiles = NULL_IF_CONFIG_SMALL(profiles),