2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/stereo3d.h"
32 #include "libavutil/timer.h"
35 #include "cabac_functions.h"
36 #include "error_resilience.h"
40 #include "h264chroma.h"
41 #include "h264_mvpred.h"
45 #include "mpegutils.h"
46 #include "rectangle.h"
52 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
54 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
56 int mb_x, int mb_y, int mb_intra, int mb_skipped)
58 H264Context *h = opaque;
59 H264SliceContext *sl = &h->slice_ctx[0];
63 h->mb_xy = mb_x + mb_y * h->mb_stride;
64 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
66 /* FIXME: It is possible albeit uncommon that slice references
67 * differ between slices. We take the easy approach and ignore
68 * it for now. If this turns out to have any relevance in
69 * practice then correct remapping should be added. */
70 if (ref >= h->ref_count[0])
72 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
74 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
75 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
76 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
77 assert(!FRAME_MBAFF(h));
78 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
81 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
83 AVCodecContext *avctx = h->avctx;
84 AVFrame *cur = &h->cur_pic.f;
85 AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
86 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
87 int vshift = desc->log2_chroma_h;
88 const int field_pic = h->picture_structure != PICT_FRAME;
94 height = FFMIN(height, avctx->height - y);
96 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
99 if (avctx->draw_horiz_band) {
101 int offset[AV_NUM_DATA_POINTERS];
104 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
105 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
112 offset[0] = y * src->linesize[0];
114 offset[2] = (y >> vshift) * src->linesize[1];
115 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
120 avctx->draw_horiz_band(avctx, src, offset,
121 y, h->picture_structure, height);
126 * Check if the top & left blocks are available if needed and
127 * change the dc mode so it only uses the available blocks.
129 int ff_h264_check_intra4x4_pred_mode(H264Context *h, H264SliceContext *sl)
131 static const int8_t top[12] = {
132 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
134 static const int8_t left[12] = {
135 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
139 if (!(sl->top_samples_available & 0x8000)) {
140 for (i = 0; i < 4; i++) {
141 int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
143 av_log(h->avctx, AV_LOG_ERROR,
144 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
145 status, h->mb_x, h->mb_y);
146 return AVERROR_INVALIDDATA;
148 sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
153 if ((sl->left_samples_available & 0x8888) != 0x8888) {
154 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
155 for (i = 0; i < 4; i++)
156 if (!(sl->left_samples_available & mask[i])) {
157 int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
159 av_log(h->avctx, AV_LOG_ERROR,
160 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
161 status, h->mb_x, h->mb_y);
162 return AVERROR_INVALIDDATA;
164 sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
170 } // FIXME cleanup like ff_h264_check_intra_pred_mode
173 * Check if the top & left blocks are available if needed and
174 * change the dc mode so it only uses the available blocks.
176 int ff_h264_check_intra_pred_mode(H264Context *h, H264SliceContext *sl,
177 int mode, int is_chroma)
179 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
180 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
183 av_log(h->avctx, AV_LOG_ERROR,
184 "out of range intra chroma pred mode at %d %d\n",
186 return AVERROR_INVALIDDATA;
189 if (!(sl->top_samples_available & 0x8000)) {
192 av_log(h->avctx, AV_LOG_ERROR,
193 "top block unavailable for requested intra mode at %d %d\n",
195 return AVERROR_INVALIDDATA;
199 if ((sl->left_samples_available & 0x8080) != 0x8080) {
201 if (is_chroma && (sl->left_samples_available & 0x8080)) {
202 // mad cow disease mode, aka MBAFF + constrained_intra_pred
203 mode = ALZHEIMER_DC_L0T_PRED8x8 +
204 (!(sl->left_samples_available & 0x8000)) +
205 2 * (mode == DC_128_PRED8x8);
208 av_log(h->avctx, AV_LOG_ERROR,
209 "left block unavailable for requested intra mode at %d %d\n",
211 return AVERROR_INVALIDDATA;
218 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
219 int *dst_length, int *consumed, int length)
225 // src[0]&0x80; // forbidden bit
226 h->nal_ref_idc = src[0] >> 5;
227 h->nal_unit_type = src[0] & 0x1F;
232 #define STARTCODE_TEST \
233 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
234 if (src[i + 2] != 3) { \
235 /* startcode, so we must be past the end */ \
241 #if HAVE_FAST_UNALIGNED
242 #define FIND_FIRST_ZERO \
243 if (i > 0 && !src[i]) \
249 for (i = 0; i + 1 < length; i += 9) {
250 if (!((~AV_RN64A(src + i) &
251 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
252 0x8000800080008080ULL))
259 for (i = 0; i + 1 < length; i += 5) {
260 if (!((~AV_RN32A(src + i) &
261 (AV_RN32A(src + i) - 0x01000101U)) &
270 for (i = 0; i + 1 < length; i += 2) {
273 if (i > 0 && src[i - 1] == 0)
279 if (i >= length - 1) { // no escaped 0
280 *dst_length = length;
281 *consumed = length + 1; // +1 for the header
285 // use second escape buffer for inter data
286 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
287 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
288 length + FF_INPUT_BUFFER_PADDING_SIZE);
289 dst = h->rbsp_buffer[bufidx];
296 while (si + 2 < length) {
297 // remove escapes (very rare 1:2^22)
298 if (src[si + 2] > 3) {
299 dst[di++] = src[si++];
300 dst[di++] = src[si++];
301 } else if (src[si] == 0 && src[si + 1] == 0) {
302 if (src[si + 2] == 3) { // escape
307 } else // next start code
311 dst[di++] = src[si++];
314 dst[di++] = src[si++];
317 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
320 *consumed = si + 1; // +1 for the header
321 /* FIXME store exact number of bits in the getbitcontext
322 * (it is needed for decoding) */
327 * Identify the exact end of the bitstream
328 * @return the length of the trailing, or 0 if damaged
330 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
335 tprintf(h->avctx, "rbsp trailing %X\n", v);
337 for (r = 1; r < 9; r++) {
345 void ff_h264_free_tables(H264Context *h, int free_rbsp)
350 av_freep(&h->intra4x4_pred_mode);
351 av_freep(&h->chroma_pred_mode_table);
352 av_freep(&h->cbp_table);
353 av_freep(&h->mvd_table[0]);
354 av_freep(&h->mvd_table[1]);
355 av_freep(&h->direct_table);
356 av_freep(&h->non_zero_count);
357 av_freep(&h->slice_table_base);
358 h->slice_table = NULL;
359 av_freep(&h->list_counts);
361 av_freep(&h->mb2b_xy);
362 av_freep(&h->mb2br_xy);
364 av_buffer_pool_uninit(&h->qscale_table_pool);
365 av_buffer_pool_uninit(&h->mb_type_pool);
366 av_buffer_pool_uninit(&h->motion_val_pool);
367 av_buffer_pool_uninit(&h->ref_index_pool);
369 if (free_rbsp && h->DPB) {
370 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
371 ff_h264_unref_picture(h, &h->DPB[i]);
374 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
375 h->DPB[i].needs_realloc = 1;
378 h->cur_pic_ptr = NULL;
380 for (i = 0; i < H264_MAX_THREADS; i++) {
381 hx = h->thread_context[i];
384 av_freep(&hx->top_borders[1]);
385 av_freep(&hx->top_borders[0]);
386 av_freep(&hx->bipred_scratchpad);
387 av_freep(&hx->edge_emu_buffer);
388 av_freep(&hx->dc_val_base);
389 av_freep(&hx->er.mb_index2xy);
390 av_freep(&hx->er.error_status_table);
391 av_freep(&hx->er.er_temp_buffer);
392 av_freep(&hx->er.mbintra_table);
393 av_freep(&hx->er.mbskip_table);
396 av_freep(&hx->rbsp_buffer[1]);
397 av_freep(&hx->rbsp_buffer[0]);
398 hx->rbsp_buffer_size[0] = 0;
399 hx->rbsp_buffer_size[1] = 0;
402 av_freep(&h->thread_context[i]);
406 int ff_h264_alloc_tables(H264Context *h)
408 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
409 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
412 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
413 row_mb_num * 8 * sizeof(uint8_t), fail)
414 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
416 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
417 big_mb_num * 48 * sizeof(uint8_t), fail)
418 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
419 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
420 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
421 big_mb_num * sizeof(uint16_t), fail)
422 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
423 big_mb_num * sizeof(uint8_t), fail)
424 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
425 16 * row_mb_num * sizeof(uint8_t), fail);
426 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
427 16 * row_mb_num * sizeof(uint8_t), fail);
428 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
429 4 * big_mb_num * sizeof(uint8_t), fail);
430 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
431 big_mb_num * sizeof(uint8_t), fail)
433 memset(h->slice_table_base, -1,
434 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
435 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
437 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
438 big_mb_num * sizeof(uint32_t), fail);
439 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
440 big_mb_num * sizeof(uint32_t), fail);
441 for (y = 0; y < h->mb_height; y++)
442 for (x = 0; x < h->mb_width; x++) {
443 const int mb_xy = x + y * h->mb_stride;
444 const int b_xy = 4 * x + 4 * y * h->b_stride;
446 h->mb2b_xy[mb_xy] = b_xy;
447 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
450 if (!h->dequant4_coeff[0])
451 h264_init_dequant_tables(h);
454 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
457 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
458 av_frame_unref(&h->DPB[i].f);
459 av_frame_unref(&h->cur_pic.f);
465 ff_h264_free_tables(h, 1);
466 return AVERROR(ENOMEM);
471 * Allocate buffers which are not shared amongst multiple threads.
473 int ff_h264_context_init(H264Context *h)
475 ERContext *er = &h->er;
476 int mb_array_size = h->mb_height * h->mb_stride;
477 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
478 int c_size = h->mb_stride * (h->mb_height + 1);
479 int yc_size = y_size + 2 * c_size;
482 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
483 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
484 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
485 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
487 for (i = 0; i < h->nb_slice_ctx; i++) {
488 h->slice_ctx[i].ref_cache[0][scan8[5] + 1] =
489 h->slice_ctx[i].ref_cache[0][scan8[7] + 1] =
490 h->slice_ctx[i].ref_cache[0][scan8[13] + 1] =
491 h->slice_ctx[i].ref_cache[1][scan8[5] + 1] =
492 h->slice_ctx[i].ref_cache[1][scan8[7] + 1] =
493 h->slice_ctx[i].ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
496 if (CONFIG_ERROR_RESILIENCE) {
498 er->avctx = h->avctx;
499 er->decode_mb = h264_er_decode_mb;
501 er->quarter_sample = 1;
503 er->mb_num = h->mb_num;
504 er->mb_width = h->mb_width;
505 er->mb_height = h->mb_height;
506 er->mb_stride = h->mb_stride;
507 er->b8_stride = h->mb_width * 2 + 1;
509 // error resilience code looks cleaner with this
510 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
511 (h->mb_num + 1) * sizeof(int), fail);
513 for (y = 0; y < h->mb_height; y++)
514 for (x = 0; x < h->mb_width; x++)
515 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
517 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
518 h->mb_stride + h->mb_width;
520 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
521 mb_array_size * sizeof(uint8_t), fail);
523 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
524 memset(er->mbintra_table, 1, mb_array_size);
526 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
528 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
529 h->mb_height * h->mb_stride, fail);
531 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,
532 yc_size * sizeof(int16_t), fail);
533 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
534 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
535 er->dc_val[2] = er->dc_val[1] + c_size;
536 for (i = 0; i < yc_size; i++)
537 h->dc_val_base[i] = 1024;
543 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
546 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
547 int parse_extradata);
549 int ff_h264_decode_extradata(H264Context *h)
551 AVCodecContext *avctx = h->avctx;
554 if (avctx->extradata[0] == 1) {
556 unsigned char *p = avctx->extradata;
560 if (avctx->extradata_size < 7) {
561 av_log(avctx, AV_LOG_ERROR,
562 "avcC %d too short\n", avctx->extradata_size);
563 return AVERROR_INVALIDDATA;
565 /* sps and pps in the avcC always have length coded with 2 bytes,
566 * so put a fake nal_length_size = 2 while parsing them */
567 h->nal_length_size = 2;
568 // Decode sps from avcC
569 cnt = *(p + 5) & 0x1f; // Number of sps
571 for (i = 0; i < cnt; i++) {
572 nalsize = AV_RB16(p) + 2;
573 if (p - avctx->extradata + nalsize > avctx->extradata_size)
574 return AVERROR_INVALIDDATA;
575 ret = decode_nal_units(h, p, nalsize, 1);
577 av_log(avctx, AV_LOG_ERROR,
578 "Decoding sps %d from avcC failed\n", i);
583 // Decode pps from avcC
584 cnt = *(p++); // Number of pps
585 for (i = 0; i < cnt; i++) {
586 nalsize = AV_RB16(p) + 2;
587 if (p - avctx->extradata + nalsize > avctx->extradata_size)
588 return AVERROR_INVALIDDATA;
589 ret = decode_nal_units(h, p, nalsize, 1);
591 av_log(avctx, AV_LOG_ERROR,
592 "Decoding pps %d from avcC failed\n", i);
597 // Store right nal length size that will be used to parse all other nals
598 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
601 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
608 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
610 H264Context *h = avctx->priv_data;
616 h->bit_depth_luma = 8;
617 h->chroma_format_idc = 1;
619 ff_h264dsp_init(&h->h264dsp, 8, 1);
620 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
621 ff_h264qpel_init(&h->h264qpel, 8);
622 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
624 h->dequant_coeff_pps = -1;
626 /* needed so that IDCT permutation is known early */
627 ff_videodsp_init(&h->vdsp, 8);
629 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
630 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
632 h->picture_structure = PICT_FRAME;
633 h->slice_context_count = 1;
634 h->workaround_bugs = avctx->workaround_bugs;
635 h->flags = avctx->flags;
638 // s->decode_mb = ff_h263_decode_mb;
639 if (!avctx->has_b_frames)
642 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
644 ff_h264_decode_init_vlc();
646 ff_init_cabac_states();
649 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
651 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
652 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
655 return AVERROR(ENOMEM);
658 h->thread_context[0] = h;
659 for (i = 0; i < h->nb_slice_ctx; i++)
660 h->slice_ctx[i].h264 = h->thread_context[0];
662 h->outputed_poc = h->next_outputed_poc = INT_MIN;
663 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
664 h->last_pocs[i] = INT_MIN;
665 h->prev_poc_msb = 1 << 16;
667 ff_h264_reset_sei(h);
668 h->recovery_frame = -1;
669 h->frame_recovered = 0;
670 if (avctx->codec_id == AV_CODEC_ID_H264) {
671 if (avctx->ticks_per_frame == 1)
672 h->avctx->framerate.num *= 2;
673 avctx->ticks_per_frame = 2;
676 if (avctx->extradata_size > 0 && avctx->extradata) {
677 ret = ff_h264_decode_extradata(h);
679 ff_h264_free_context(h);
684 if (h->sps.bitstream_restriction_flag &&
685 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
686 h->avctx->has_b_frames = h->sps.num_reorder_frames;
690 avctx->internal->allocate_progress = 1;
695 static int decode_init_thread_copy(AVCodecContext *avctx)
697 H264Context *h = avctx->priv_data;
700 if (!avctx->internal->is_copy)
702 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
703 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
705 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
706 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
709 return AVERROR(ENOMEM);
712 for (i = 0; i < h->nb_slice_ctx; i++)
713 h->slice_ctx[i].h264 = h;
716 h->rbsp_buffer[0] = NULL;
717 h->rbsp_buffer[1] = NULL;
718 h->rbsp_buffer_size[0] = 0;
719 h->rbsp_buffer_size[1] = 0;
720 h->context_initialized = 0;
726 * Run setup operations that must be run after slice header decoding.
727 * This includes finding the next displayed frame.
729 * @param h h264 master context
730 * @param setup_finished enough NALs have been read that we can call
731 * ff_thread_finish_setup()
733 static void decode_postinit(H264Context *h, int setup_finished)
735 H264Picture *out = h->cur_pic_ptr;
736 H264Picture *cur = h->cur_pic_ptr;
737 int i, pics, out_of_order, out_idx;
738 int invalid = 0, cnt = 0;
740 h->cur_pic_ptr->f.pict_type = h->pict_type;
742 if (h->next_output_pic)
745 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
746 /* FIXME: if we have two PAFF fields in one packet, we can't start
747 * the next thread here. If we have one field per packet, we can.
748 * The check in decode_nal_units() is not good enough to find this
749 * yet, so we assume the worst for now. */
750 // if (setup_finished)
751 // ff_thread_finish_setup(h->avctx);
755 cur->f.interlaced_frame = 0;
756 cur->f.repeat_pict = 0;
758 /* Signal interlacing information externally. */
759 /* Prioritize picture timing SEI information over used
760 * decoding process if it exists. */
762 if (h->sps.pic_struct_present_flag) {
763 switch (h->sei_pic_struct) {
764 case SEI_PIC_STRUCT_FRAME:
766 case SEI_PIC_STRUCT_TOP_FIELD:
767 case SEI_PIC_STRUCT_BOTTOM_FIELD:
768 cur->f.interlaced_frame = 1;
770 case SEI_PIC_STRUCT_TOP_BOTTOM:
771 case SEI_PIC_STRUCT_BOTTOM_TOP:
772 if (FIELD_OR_MBAFF_PICTURE(h))
773 cur->f.interlaced_frame = 1;
775 // try to flag soft telecine progressive
776 cur->f.interlaced_frame = h->prev_interlaced_frame;
778 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
779 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
780 /* Signal the possibility of telecined film externally
781 * (pic_struct 5,6). From these hints, let the applications
782 * decide if they apply deinterlacing. */
783 cur->f.repeat_pict = 1;
785 case SEI_PIC_STRUCT_FRAME_DOUBLING:
786 cur->f.repeat_pict = 2;
788 case SEI_PIC_STRUCT_FRAME_TRIPLING:
789 cur->f.repeat_pict = 4;
793 if ((h->sei_ct_type & 3) &&
794 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
795 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
797 /* Derive interlacing flag from used decoding process. */
798 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
800 h->prev_interlaced_frame = cur->f.interlaced_frame;
802 if (cur->field_poc[0] != cur->field_poc[1]) {
803 /* Derive top_field_first from field pocs. */
804 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
806 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
807 /* Use picture timing SEI information. Even if it is a
808 * information of a past frame, better than nothing. */
809 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
810 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
811 cur->f.top_field_first = 1;
813 cur->f.top_field_first = 0;
815 /* Most likely progressive */
816 cur->f.top_field_first = 0;
820 if (h->sei_frame_packing_present &&
821 h->frame_packing_arrangement_type >= 0 &&
822 h->frame_packing_arrangement_type <= 6 &&
823 h->content_interpretation_type > 0 &&
824 h->content_interpretation_type < 3) {
825 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
829 switch (h->frame_packing_arrangement_type) {
831 stereo->type = AV_STEREO3D_CHECKERBOARD;
834 stereo->type = AV_STEREO3D_COLUMNS;
837 stereo->type = AV_STEREO3D_LINES;
840 if (h->quincunx_subsampling)
841 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
843 stereo->type = AV_STEREO3D_SIDEBYSIDE;
846 stereo->type = AV_STEREO3D_TOPBOTTOM;
849 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
852 stereo->type = AV_STEREO3D_2D;
856 if (h->content_interpretation_type == 2)
857 stereo->flags = AV_STEREO3D_FLAG_INVERT;
860 if (h->sei_display_orientation_present &&
861 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
862 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
863 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
864 AV_FRAME_DATA_DISPLAYMATRIX,
865 sizeof(int32_t) * 9);
869 av_display_rotation_set((int32_t *)rotation->data, angle);
870 av_display_matrix_flip((int32_t *)rotation->data,
871 h->sei_hflip, h->sei_vflip);
874 // FIXME do something with unavailable reference frames
876 /* Sort B-frames into display order */
878 if (h->sps.bitstream_restriction_flag &&
879 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
880 h->avctx->has_b_frames = h->sps.num_reorder_frames;
884 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
885 !h->sps.bitstream_restriction_flag) {
886 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
891 while (h->delayed_pic[pics])
894 assert(pics <= MAX_DELAYED_PIC_COUNT);
896 h->delayed_pic[pics++] = cur;
897 if (cur->reference == 0)
898 cur->reference = DELAYED_PIC_REF;
900 /* Frame reordering. This code takes pictures from coding order and sorts
901 * them by their incremental POC value into display order. It supports POC
902 * gaps, MMCO reset codes and random resets.
903 * A "display group" can start either with a IDR frame (f.key_frame = 1),
904 * and/or can be closed down with a MMCO reset code. In sequences where
905 * there is no delay, we can't detect that (since the frame was already
906 * output to the user), so we also set h->mmco_reset to detect the MMCO
908 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
909 * we increase the delay between input and output. All frames affected by
910 * the lag (e.g. those that should have been output before another frame
911 * that we already returned to the user) will be dropped. This is a bug
912 * that we will fix later. */
913 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
914 cnt += out->poc < h->last_pocs[i];
915 invalid += out->poc == INT_MIN;
917 if (!h->mmco_reset && !cur->f.key_frame &&
918 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
921 h->delayed_pic[pics - 2]->mmco_reset = 2;
923 if (h->mmco_reset || cur->f.key_frame) {
924 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
925 h->last_pocs[i] = INT_MIN;
927 invalid = MAX_DELAYED_PIC_COUNT;
929 out = h->delayed_pic[0];
931 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
933 !h->delayed_pic[i - 1]->mmco_reset &&
934 !h->delayed_pic[i]->f.key_frame;
936 if (h->delayed_pic[i]->poc < out->poc) {
937 out = h->delayed_pic[i];
940 if (h->avctx->has_b_frames == 0 &&
941 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
942 h->next_outputed_poc = INT_MIN;
943 out_of_order = !out->f.key_frame && !h->mmco_reset &&
944 (out->poc < h->next_outputed_poc);
946 if (h->sps.bitstream_restriction_flag &&
947 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
948 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
949 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
950 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
951 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
954 } else if (h->low_delay &&
955 ((h->next_outputed_poc != INT_MIN &&
956 out->poc > h->next_outputed_poc + 2) ||
957 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
959 h->avctx->has_b_frames++;
962 if (pics > h->avctx->has_b_frames) {
963 out->reference &= ~DELAYED_PIC_REF;
964 // for frame threading, the owner must be the second field's thread or
965 // else the first thread can release the picture and reuse it unsafely
966 for (i = out_idx; h->delayed_pic[i]; i++)
967 h->delayed_pic[i] = h->delayed_pic[i + 1];
969 memmove(h->last_pocs, &h->last_pocs[1],
970 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
971 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
972 if (!out_of_order && pics > h->avctx->has_b_frames) {
973 h->next_output_pic = out;
974 if (out->mmco_reset) {
976 h->next_outputed_poc = out->poc;
977 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
979 h->next_outputed_poc = INT_MIN;
982 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
983 h->next_outputed_poc = INT_MIN;
985 h->next_outputed_poc = out->poc;
990 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
993 if (h->next_output_pic) {
994 if (h->next_output_pic->recovered) {
995 // We have reached an recovery point and all frames after it in
996 // display order are "recovered".
997 h->frame_recovered |= FRAME_RECOVERED_SEI;
999 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
1002 if (setup_finished && !h->avctx->hwaccel)
1003 ff_thread_finish_setup(h->avctx);
1006 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
1009 int luma_def, chroma_def;
1012 sl->use_weight_chroma = 0;
1013 sl->luma_log2_weight_denom = get_ue_golomb(&h->gb);
1014 if (h->sps.chroma_format_idc)
1015 sl->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
1016 luma_def = 1 << sl->luma_log2_weight_denom;
1017 chroma_def = 1 << sl->chroma_log2_weight_denom;
1019 for (list = 0; list < 2; list++) {
1020 sl->luma_weight_flag[list] = 0;
1021 sl->chroma_weight_flag[list] = 0;
1022 for (i = 0; i < h->ref_count[list]; i++) {
1023 int luma_weight_flag, chroma_weight_flag;
1025 luma_weight_flag = get_bits1(&h->gb);
1026 if (luma_weight_flag) {
1027 sl->luma_weight[i][list][0] = get_se_golomb(&h->gb);
1028 sl->luma_weight[i][list][1] = get_se_golomb(&h->gb);
1029 if (sl->luma_weight[i][list][0] != luma_def ||
1030 sl->luma_weight[i][list][1] != 0) {
1032 sl->luma_weight_flag[list] = 1;
1035 sl->luma_weight[i][list][0] = luma_def;
1036 sl->luma_weight[i][list][1] = 0;
1039 if (h->sps.chroma_format_idc) {
1040 chroma_weight_flag = get_bits1(&h->gb);
1041 if (chroma_weight_flag) {
1043 for (j = 0; j < 2; j++) {
1044 sl->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1045 sl->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1046 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1047 sl->chroma_weight[i][list][j][1] != 0) {
1048 sl->use_weight_chroma = 1;
1049 sl->chroma_weight_flag[list] = 1;
1054 for (j = 0; j < 2; j++) {
1055 sl->chroma_weight[i][list][j][0] = chroma_def;
1056 sl->chroma_weight[i][list][j][1] = 0;
1061 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1064 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1069 * instantaneous decoder refresh.
1071 static void idr(H264Context *h)
1073 ff_h264_remove_all_refs(h);
1075 h->prev_frame_num_offset =
1077 h->prev_poc_lsb = 0;
1080 /* forget old pics after a seek */
1081 void ff_h264_flush_change(H264Context *h)
1084 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1085 h->last_pocs[i] = INT_MIN;
1086 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1087 h->prev_interlaced_frame = 1;
1090 h->cur_pic_ptr->reference = 0;
1092 ff_h264_reset_sei(h);
1093 h->recovery_frame = -1;
1094 h->frame_recovered = 0;
1097 /* forget old pics after a seek */
1098 static void flush_dpb(AVCodecContext *avctx)
1100 H264Context *h = avctx->priv_data;
1103 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1105 ff_h264_flush_change(h);
1108 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1109 ff_h264_unref_picture(h, &h->DPB[i]);
1110 h->cur_pic_ptr = NULL;
1111 ff_h264_unref_picture(h, &h->cur_pic);
1113 h->mb_x = h->mb_y = 0;
1115 ff_h264_free_tables(h, 1);
1116 h->context_initialized = 0;
1119 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1121 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1124 h->frame_num_offset = h->prev_frame_num_offset;
1125 if (h->frame_num < h->prev_frame_num)
1126 h->frame_num_offset += max_frame_num;
1128 if (h->sps.poc_type == 0) {
1129 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1131 if (h->poc_lsb < h->prev_poc_lsb &&
1132 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1133 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1134 else if (h->poc_lsb > h->prev_poc_lsb &&
1135 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1136 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1138 h->poc_msb = h->prev_poc_msb;
1140 field_poc[1] = h->poc_msb + h->poc_lsb;
1141 if (h->picture_structure == PICT_FRAME)
1142 field_poc[1] += h->delta_poc_bottom;
1143 } else if (h->sps.poc_type == 1) {
1144 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1147 if (h->sps.poc_cycle_length != 0)
1148 abs_frame_num = h->frame_num_offset + h->frame_num;
1152 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1155 expected_delta_per_poc_cycle = 0;
1156 for (i = 0; i < h->sps.poc_cycle_length; i++)
1157 // FIXME integrate during sps parse
1158 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1160 if (abs_frame_num > 0) {
1161 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1162 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1164 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1165 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1166 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1170 if (h->nal_ref_idc == 0)
1171 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1173 field_poc[0] = expectedpoc + h->delta_poc[0];
1174 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1176 if (h->picture_structure == PICT_FRAME)
1177 field_poc[1] += h->delta_poc[1];
1179 int poc = 2 * (h->frame_num_offset + h->frame_num);
1181 if (!h->nal_ref_idc)
1188 if (h->picture_structure != PICT_BOTTOM_FIELD)
1189 pic_field_poc[0] = field_poc[0];
1190 if (h->picture_structure != PICT_TOP_FIELD)
1191 pic_field_poc[1] = field_poc[1];
1192 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1198 * Compute profile from profile_idc and constraint_set?_flags.
1202 * @return profile as defined by FF_PROFILE_H264_*
1204 int ff_h264_get_profile(SPS *sps)
1206 int profile = sps->profile_idc;
1208 switch (sps->profile_idc) {
1209 case FF_PROFILE_H264_BASELINE:
1210 // constraint_set1_flag set to 1
1211 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1213 case FF_PROFILE_H264_HIGH_10:
1214 case FF_PROFILE_H264_HIGH_422:
1215 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1216 // constraint_set3_flag set to 1
1217 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1224 int ff_h264_set_parameter_from_sps(H264Context *h)
1226 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1227 (h->sps.bitstream_restriction_flag &&
1228 !h->sps.num_reorder_frames)) {
1229 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1230 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1231 "Reenabling low delay requires a codec flush.\n");
1236 if (h->avctx->has_b_frames < 2)
1237 h->avctx->has_b_frames = !h->low_delay;
1239 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1240 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1241 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
1242 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1243 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1244 h->pixel_shift = h->sps.bit_depth_luma > 8;
1246 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1247 h->sps.chroma_format_idc);
1248 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1249 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1250 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1251 h->sps.chroma_format_idc);
1252 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1254 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1255 h->sps.bit_depth_luma);
1256 return AVERROR_INVALIDDATA;
1262 int ff_set_ref_count(H264Context *h)
1264 int ref_count[2], list_count;
1265 int num_ref_idx_active_override_flag, max_refs;
1267 // set defaults, might be overridden a few lines later
1268 ref_count[0] = h->pps.ref_count[0];
1269 ref_count[1] = h->pps.ref_count[1];
1271 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1272 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1273 h->direct_spatial_mv_pred = get_bits1(&h->gb);
1274 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1276 if (num_ref_idx_active_override_flag) {
1277 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1278 if (ref_count[0] < 1)
1279 return AVERROR_INVALIDDATA;
1280 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1281 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1282 if (ref_count[1] < 1)
1283 return AVERROR_INVALIDDATA;
1287 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1293 ref_count[0] = ref_count[1] = 0;
1296 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1298 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1299 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1300 h->ref_count[0] = h->ref_count[1] = 0;
1301 return AVERROR_INVALIDDATA;
1304 if (list_count != h->list_count ||
1305 ref_count[0] != h->ref_count[0] ||
1306 ref_count[1] != h->ref_count[1]) {
1307 h->ref_count[0] = ref_count[0];
1308 h->ref_count[1] = ref_count[1];
1309 h->list_count = list_count;
1316 static int find_start_code(const uint8_t *buf, int buf_size,
1317 int buf_index, int next_avc)
1319 // start code prefix search
1320 for (; buf_index + 3 < next_avc; buf_index++)
1321 // This should always succeed in the first iteration.
1322 if (buf[buf_index] == 0 &&
1323 buf[buf_index + 1] == 0 &&
1324 buf[buf_index + 2] == 1)
1327 if (buf_index + 3 >= buf_size)
1330 return buf_index + 3;
1333 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1334 int buf_size, int *buf_index)
1338 if (*buf_index >= buf_size - h->nal_length_size)
1341 for (i = 0; i < h->nal_length_size; i++)
1342 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1343 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1344 av_log(h->avctx, AV_LOG_ERROR,
1345 "AVC: nal size %d\n", nalsize);
1351 static int get_bit_length(H264Context *h, const uint8_t *buf,
1352 const uint8_t *ptr, int dst_length,
1353 int i, int next_avc)
1355 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1356 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1357 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1358 h->workaround_bugs |= FF_BUG_TRUNCATED;
1360 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1361 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1367 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1370 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1372 int next_avc = h->is_avc ? 0 : buf_size;
1375 int nals_needed = 0;
1379 int dst_length, bit_length, consumed;
1382 if (buf_index >= next_avc) {
1383 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1386 next_avc = buf_index + nalsize;
1388 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1389 if (buf_index >= buf_size)
1393 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1394 next_avc - buf_index);
1396 if (!ptr || dst_length < 0)
1397 return AVERROR_INVALIDDATA;
1399 buf_index += consumed;
1401 bit_length = get_bit_length(h, buf, ptr, dst_length,
1402 buf_index, next_avc);
1405 /* packets can sometimes contain multiple PPS/SPS,
1406 * e.g. two PAFF field pictures in one packet, or a demuxer
1407 * which splits NALs strangely if so, when frame threading we
1408 * can't start the next thread until we've read all of them */
1409 switch (h->nal_unit_type) {
1412 nals_needed = nal_index;
1417 init_get_bits(&h->gb, ptr, bit_length);
1418 if (!get_ue_golomb(&h->gb))
1419 nals_needed = nal_index;
1426 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1427 int parse_extradata)
1429 AVCodecContext *const avctx = h->avctx;
1430 H264Context *hx; ///< thread context
1431 H264SliceContext *sl;
1433 unsigned context_count;
1435 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1439 h->max_contexts = h->slice_context_count;
1440 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1441 h->current_slice = 0;
1442 if (!h->first_field)
1443 h->cur_pic_ptr = NULL;
1444 ff_h264_reset_sei(h);
1447 if (avctx->active_thread_type & FF_THREAD_FRAME)
1448 nals_needed = get_last_needed_nal(h, buf, buf_size);
1453 next_avc = h->is_avc ? 0 : buf_size;
1463 if (buf_index >= next_avc) {
1464 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1467 next_avc = buf_index + nalsize;
1469 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1470 if (buf_index >= buf_size)
1472 if (buf_index >= next_avc)
1476 hx = h->thread_context[context_count];
1477 sl = &h->slice_ctx[context_count];
1479 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1480 &consumed, next_avc - buf_index);
1481 if (!ptr || dst_length < 0) {
1486 bit_length = get_bit_length(h, buf, ptr, dst_length,
1487 buf_index + consumed, next_avc);
1489 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1490 av_log(h->avctx, AV_LOG_DEBUG,
1491 "NAL %d at %d/%d length %d\n",
1492 hx->nal_unit_type, buf_index, buf_size, dst_length);
1494 if (h->is_avc && (nalsize != consumed) && nalsize)
1495 av_log(h->avctx, AV_LOG_DEBUG,
1496 "AVC: Consumed only %d bytes instead of %d\n",
1499 buf_index += consumed;
1502 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1503 h->nal_ref_idc == 0 &&
1504 h->nal_unit_type != NAL_SEI)
1508 /* Ignore every NAL unit type except PPS and SPS during extradata
1509 * parsing. Decoding slices is not possible in codec init
1511 if (parse_extradata && HAVE_THREADS &&
1512 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1513 (hx->nal_unit_type != NAL_PPS &&
1514 hx->nal_unit_type != NAL_SPS)) {
1515 if (hx->nal_unit_type < NAL_AUD ||
1516 hx->nal_unit_type > NAL_AUXILIARY_SLICE)
1517 av_log(avctx, AV_LOG_INFO,
1518 "Ignoring NAL unit %d during extradata parsing\n",
1520 hx->nal_unit_type = NAL_FF_IGNORE;
1523 switch (hx->nal_unit_type) {
1525 if (h->nal_unit_type != NAL_IDR_SLICE) {
1526 av_log(h->avctx, AV_LOG_ERROR,
1527 "Invalid mix of idr and non-idr slices\n");
1531 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1533 init_get_bits(&hx->gb, ptr, bit_length);
1535 hx->inter_gb_ptr = &hx->gb;
1537 if ((err = ff_h264_decode_slice_header(hx, sl, h)))
1540 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1541 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1542 ((1 << h->sps.log2_max_frame_num) - 1);
1545 h->cur_pic_ptr->f.key_frame |=
1546 (hx->nal_unit_type == NAL_IDR_SLICE) ||
1547 (h->sei_recovery_frame_cnt >= 0);
1549 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1550 h->recovery_frame == h->frame_num) {
1551 h->recovery_frame = -1;
1552 h->cur_pic_ptr->recovered = 1;
1554 // If we have an IDR, all frames after it in decoded order are
1556 if (hx->nal_unit_type == NAL_IDR_SLICE)
1557 h->frame_recovered |= FRAME_RECOVERED_IDR;
1558 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1560 if (h->current_slice == 1) {
1561 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1562 decode_postinit(h, nal_index >= nals_needed);
1564 if (h->avctx->hwaccel &&
1565 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1569 if (hx->redundant_pic_count == 0 &&
1570 (avctx->skip_frame < AVDISCARD_NONREF ||
1572 (avctx->skip_frame < AVDISCARD_BIDIR ||
1573 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1574 (avctx->skip_frame < AVDISCARD_NONKEY ||
1575 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1576 avctx->skip_frame < AVDISCARD_ALL) {
1577 if (avctx->hwaccel) {
1578 ret = avctx->hwaccel->decode_slice(avctx,
1579 &buf[buf_index - consumed],
1590 avpriv_request_sample(avctx, "data partitioning");
1591 ret = AVERROR(ENOSYS);
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;
1654 sl = &h->slice_ctx[0];
1659 if (context_count) {
1660 ret = ff_h264_execute_decode_slices(h, context_count);
1661 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1668 if (h->cur_pic_ptr && !h->droppable) {
1669 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1670 h->picture_structure == PICT_BOTTOM_FIELD);
1673 return (ret < 0) ? ret : buf_index;
1677 * Return the number of bytes consumed for building the current frame.
1679 static int get_consumed_bytes(int pos, int buf_size)
1682 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1683 if (pos + 10 > buf_size)
1684 pos = buf_size; // oops ;)
1689 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1692 int ret = av_frame_ref(dst, src);
1699 for (i = 0; i < 3; i++) {
1700 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1701 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1702 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1703 (h->sps.crop_top >> vshift) * dst->linesize[i];
1704 dst->data[i] += off;
1709 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1710 int *got_frame, AVPacket *avpkt)
1712 const uint8_t *buf = avpkt->data;
1713 int buf_size = avpkt->size;
1714 H264Context *h = avctx->priv_data;
1715 AVFrame *pict = data;
1719 h->flags = avctx->flags;
1721 /* end of stream, output what is still in the buffers */
1723 if (buf_size == 0) {
1727 h->cur_pic_ptr = NULL;
1729 // FIXME factorize this with the output code below
1730 out = h->delayed_pic[0];
1733 h->delayed_pic[i] &&
1734 !h->delayed_pic[i]->f.key_frame &&
1735 !h->delayed_pic[i]->mmco_reset;
1737 if (h->delayed_pic[i]->poc < out->poc) {
1738 out = h->delayed_pic[i];
1742 for (i = out_idx; h->delayed_pic[i]; i++)
1743 h->delayed_pic[i] = h->delayed_pic[i + 1];
1746 ret = output_frame(h, pict, &out->f);
1755 buf_index = decode_nal_units(h, buf, buf_size, 0);
1757 return AVERROR_INVALIDDATA;
1759 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1764 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1765 if (avctx->skip_frame >= AVDISCARD_NONREF)
1767 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1768 return AVERROR_INVALIDDATA;
1771 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1772 (h->mb_y >= h->mb_height && h->mb_height)) {
1773 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1774 decode_postinit(h, 1);
1776 ff_h264_field_end(h, 0);
1779 if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
1780 h->next_output_pic->recovered)) {
1781 if (!h->next_output_pic->recovered)
1782 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1784 ret = output_frame(h, pict, &h->next_output_pic->f);
1791 assert(pict->buf[0] || !*got_frame);
1793 return get_consumed_bytes(buf_index, buf_size);
1796 av_cold void ff_h264_free_context(H264Context *h)
1800 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1802 av_freep(&h->slice_ctx);
1803 h->nb_slice_ctx = 0;
1805 for (i = 0; i < MAX_SPS_COUNT; i++)
1806 av_freep(h->sps_buffers + i);
1808 for (i = 0; i < MAX_PPS_COUNT; i++)
1809 av_freep(h->pps_buffers + i);
1812 static av_cold int h264_decode_end(AVCodecContext *avctx)
1814 H264Context *h = avctx->priv_data;
1816 ff_h264_free_context(h);
1818 ff_h264_unref_picture(h, &h->cur_pic);
1823 static const AVProfile profiles[] = {
1824 { FF_PROFILE_H264_BASELINE, "Baseline" },
1825 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1826 { FF_PROFILE_H264_MAIN, "Main" },
1827 { FF_PROFILE_H264_EXTENDED, "Extended" },
1828 { FF_PROFILE_H264_HIGH, "High" },
1829 { FF_PROFILE_H264_HIGH_10, "High 10" },
1830 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1831 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1832 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1833 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1834 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1835 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1836 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1837 { FF_PROFILE_UNKNOWN },
1840 AVCodec ff_h264_decoder = {
1842 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1843 .type = AVMEDIA_TYPE_VIDEO,
1844 .id = AV_CODEC_ID_H264,
1845 .priv_data_size = sizeof(H264Context),
1846 .init = ff_h264_decode_init,
1847 .close = h264_decode_end,
1848 .decode = h264_decode_frame,
1849 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1850 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1851 CODEC_CAP_FRAME_THREADS,
1853 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1854 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1855 .profiles = NULL_IF_CONFIG_SMALL(profiles),