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 FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/avassert.h"
31 #include "libavutil/display.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/stereo3d.h"
35 #include "libavutil/timer.h"
38 #include "cabac_functions.h"
39 #include "error_resilience.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
48 #include "mpegutils.h"
49 #include "rectangle.h"
52 #include "vdpau_internal.h"
54 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
58 H264Context *h = avctx->priv_data;
59 return h ? h->sps.num_reorder_frames : 0;
62 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
64 int mb_x, int mb_y, int mb_intra, int mb_skipped)
66 H264Context *h = opaque;
70 h->mb_xy = mb_x + mb_y * h->mb_stride;
71 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
73 /* FIXME: It is possible albeit uncommon that slice references
74 * differ between slices. We take the easy approach and ignore
75 * it for now. If this turns out to have any relevance in
76 * practice then correct remapping should be added. */
77 if (ref >= h->ref_count[0])
79 if (!h->ref_list[0][ref].f.data[0]) {
80 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
83 if ((h->ref_list[0][ref].reference&3) != 3) {
84 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
87 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
89 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
90 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
91 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
93 h->mb_field_decoding_flag = 0;
94 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
97 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
99 AVCodecContext *avctx = h->avctx;
100 AVFrame *cur = &h->cur_pic.f;
101 AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
102 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
103 int vshift = desc->log2_chroma_h;
104 const int field_pic = h->picture_structure != PICT_FRAME;
110 height = FFMIN(height, avctx->height - y);
112 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
115 if (avctx->draw_horiz_band) {
117 int offset[AV_NUM_DATA_POINTERS];
120 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
121 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
128 offset[0] = y * src->linesize[0];
130 offset[2] = (y >> vshift) * src->linesize[1];
131 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
136 avctx->draw_horiz_band(avctx, src, offset,
137 y, h->picture_structure, height);
142 * Check if the top & left blocks are available if needed and
143 * change the dc mode so it only uses the available blocks.
145 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
147 static const int8_t top[12] = {
148 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
150 static const int8_t left[12] = {
151 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
155 if (!(h->top_samples_available & 0x8000)) {
156 for (i = 0; i < 4; i++) {
157 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
159 av_log(h->avctx, AV_LOG_ERROR,
160 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
161 status, h->mb_x, h->mb_y);
162 return AVERROR_INVALIDDATA;
164 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
169 if ((h->left_samples_available & 0x8888) != 0x8888) {
170 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
171 for (i = 0; i < 4; i++)
172 if (!(h->left_samples_available & mask[i])) {
173 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
175 av_log(h->avctx, AV_LOG_ERROR,
176 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
177 status, h->mb_x, h->mb_y);
178 return AVERROR_INVALIDDATA;
180 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
186 } // FIXME cleanup like ff_h264_check_intra_pred_mode
189 * Check if the top & left blocks are available if needed and
190 * change the dc mode so it only uses the available blocks.
192 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
194 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
195 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
198 av_log(h->avctx, AV_LOG_ERROR,
199 "out of range intra chroma pred mode at %d %d\n",
201 return AVERROR_INVALIDDATA;
204 if (!(h->top_samples_available & 0x8000)) {
207 av_log(h->avctx, AV_LOG_ERROR,
208 "top block unavailable for requested intra mode at %d %d\n",
210 return AVERROR_INVALIDDATA;
214 if ((h->left_samples_available & 0x8080) != 0x8080) {
217 av_log(h->avctx, AV_LOG_ERROR,
218 "left block unavailable for requested intra mode at %d %d\n",
220 return AVERROR_INVALIDDATA;
222 if (is_chroma && (h->left_samples_available & 0x8080)) {
223 // mad cow disease mode, aka MBAFF + constrained_intra_pred
224 mode = ALZHEIMER_DC_L0T_PRED8x8 +
225 (!(h->left_samples_available & 0x8000)) +
226 2 * (mode == DC_128_PRED8x8);
233 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
234 int *dst_length, int *consumed, int length)
240 // src[0]&0x80; // forbidden bit
241 h->nal_ref_idc = src[0] >> 5;
242 h->nal_unit_type = src[0] & 0x1F;
247 #define STARTCODE_TEST \
248 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
249 if (src[i + 2] != 3 && src[i + 2] != 0) { \
250 /* startcode, so we must be past the end */ \
256 #if HAVE_FAST_UNALIGNED
257 #define FIND_FIRST_ZERO \
258 if (i > 0 && !src[i]) \
264 for (i = 0; i + 1 < length; i += 9) {
265 if (!((~AV_RN64A(src + i) &
266 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
267 0x8000800080008080ULL))
274 for (i = 0; i + 1 < length; i += 5) {
275 if (!((~AV_RN32A(src + i) &
276 (AV_RN32A(src + i) - 0x01000101U)) &
285 for (i = 0; i + 1 < length; i += 2) {
288 if (i > 0 && src[i - 1] == 0)
294 // use second escape buffer for inter data
295 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
297 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
298 dst = h->rbsp_buffer[bufidx];
303 if(i>=length-1){ //no escaped 0
305 *consumed= length+1; //+1 for the header
306 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
309 memcpy(dst, src, length);
316 while (si + 2 < length) {
317 // remove escapes (very rare 1:2^22)
318 if (src[si + 2] > 3) {
319 dst[di++] = src[si++];
320 dst[di++] = src[si++];
321 } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {
322 if (src[si + 2] == 3) { // escape
327 } else // next start code
331 dst[di++] = src[si++];
334 dst[di++] = src[si++];
337 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
340 *consumed = si + 1; // +1 for the header
341 /* FIXME store exact number of bits in the getbitcontext
342 * (it is needed for decoding) */
347 * Identify the exact end of the bitstream
348 * @return the length of the trailing, or 0 if damaged
350 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
355 tprintf(h->avctx, "rbsp trailing %X\n", v);
357 for (r = 1; r < 9; r++) {
365 void ff_h264_free_tables(H264Context *h, int free_rbsp)
370 av_freep(&h->intra4x4_pred_mode);
371 av_freep(&h->chroma_pred_mode_table);
372 av_freep(&h->cbp_table);
373 av_freep(&h->mvd_table[0]);
374 av_freep(&h->mvd_table[1]);
375 av_freep(&h->direct_table);
376 av_freep(&h->non_zero_count);
377 av_freep(&h->slice_table_base);
378 h->slice_table = NULL;
379 av_freep(&h->list_counts);
381 av_freep(&h->mb2b_xy);
382 av_freep(&h->mb2br_xy);
384 av_buffer_pool_uninit(&h->qscale_table_pool);
385 av_buffer_pool_uninit(&h->mb_type_pool);
386 av_buffer_pool_uninit(&h->motion_val_pool);
387 av_buffer_pool_uninit(&h->ref_index_pool);
389 if (free_rbsp && h->DPB) {
390 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
391 ff_h264_unref_picture(h, &h->DPB[i]);
392 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
395 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
396 h->DPB[i].needs_realloc = 1;
399 h->cur_pic_ptr = NULL;
401 for (i = 0; i < H264_MAX_THREADS; i++) {
402 hx = h->thread_context[i];
405 av_freep(&hx->top_borders[1]);
406 av_freep(&hx->top_borders[0]);
407 av_freep(&hx->bipred_scratchpad);
408 av_freep(&hx->edge_emu_buffer);
409 av_freep(&hx->dc_val_base);
410 av_freep(&hx->er.mb_index2xy);
411 av_freep(&hx->er.error_status_table);
412 av_freep(&hx->er.er_temp_buffer);
413 av_freep(&hx->er.mbintra_table);
414 av_freep(&hx->er.mbskip_table);
417 av_freep(&hx->rbsp_buffer[1]);
418 av_freep(&hx->rbsp_buffer[0]);
419 hx->rbsp_buffer_size[0] = 0;
420 hx->rbsp_buffer_size[1] = 0;
423 av_freep(&h->thread_context[i]);
427 int ff_h264_alloc_tables(H264Context *h)
429 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
430 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
433 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
434 row_mb_num, 8 * sizeof(uint8_t), fail)
435 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
436 big_mb_num * 48 * sizeof(uint8_t), fail)
437 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
438 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
439 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
440 big_mb_num * sizeof(uint16_t), fail)
441 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
442 big_mb_num * sizeof(uint8_t), fail)
443 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
444 row_mb_num, 16 * sizeof(uint8_t), fail);
445 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
446 row_mb_num, 16 * sizeof(uint8_t), fail);
447 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
448 4 * big_mb_num * sizeof(uint8_t), fail);
449 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
450 big_mb_num * sizeof(uint8_t), fail)
452 memset(h->slice_table_base, -1,
453 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
454 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
456 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
457 big_mb_num * sizeof(uint32_t), fail);
458 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
459 big_mb_num * sizeof(uint32_t), fail);
460 for (y = 0; y < h->mb_height; y++)
461 for (x = 0; x < h->mb_width; x++) {
462 const int mb_xy = x + y * h->mb_stride;
463 const int b_xy = 4 * x + 4 * y * h->b_stride;
465 h->mb2b_xy[mb_xy] = b_xy;
466 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
469 if (!h->dequant4_coeff[0])
470 ff_h264_init_dequant_tables(h);
473 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
476 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
477 av_frame_unref(&h->DPB[i].f);
478 av_frame_unref(&h->cur_pic.f);
484 ff_h264_free_tables(h, 1);
485 return AVERROR(ENOMEM);
490 * Allocate buffers which are not shared amongst multiple threads.
492 int ff_h264_context_init(H264Context *h)
494 ERContext *er = &h->er;
495 int mb_array_size = h->mb_height * h->mb_stride;
496 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
497 int c_size = h->mb_stride * (h->mb_height + 1);
498 int yc_size = y_size + 2 * c_size;
501 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->top_borders[0],
502 h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
503 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->top_borders[1],
504 h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
506 h->ref_cache[0][scan8[5] + 1] =
507 h->ref_cache[0][scan8[7] + 1] =
508 h->ref_cache[0][scan8[13] + 1] =
509 h->ref_cache[1][scan8[5] + 1] =
510 h->ref_cache[1][scan8[7] + 1] =
511 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
513 if (CONFIG_ERROR_RESILIENCE) {
515 er->avctx = h->avctx;
516 er->decode_mb = h264_er_decode_mb;
518 er->quarter_sample = 1;
520 er->mb_num = h->mb_num;
521 er->mb_width = h->mb_width;
522 er->mb_height = h->mb_height;
523 er->mb_stride = h->mb_stride;
524 er->b8_stride = h->mb_width * 2 + 1;
526 // error resilience code looks cleaner with this
527 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
528 (h->mb_num + 1) * sizeof(int), fail);
530 for (y = 0; y < h->mb_height; y++)
531 for (x = 0; x < h->mb_width; x++)
532 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
534 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
535 h->mb_stride + h->mb_width;
537 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
538 mb_array_size * sizeof(uint8_t), fail);
540 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
541 memset(er->mbintra_table, 1, mb_array_size);
543 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
545 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
546 h->mb_height * h->mb_stride, fail);
548 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,
549 yc_size * sizeof(int16_t), fail);
550 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
551 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
552 er->dc_val[2] = er->dc_val[1] + c_size;
553 for (i = 0; i < yc_size; i++)
554 h->dc_val_base[i] = 1024;
560 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
563 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
564 int parse_extradata);
566 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
568 AVCodecContext *avctx = h->avctx;
571 if (!buf || size <= 0)
576 const unsigned char *p = buf;
581 av_log(avctx, AV_LOG_ERROR,
582 "avcC %d too short\n", size);
583 return AVERROR_INVALIDDATA;
585 /* sps and pps in the avcC always have length coded with 2 bytes,
586 * so put a fake nal_length_size = 2 while parsing them */
587 h->nal_length_size = 2;
588 // Decode sps from avcC
589 cnt = *(p + 5) & 0x1f; // Number of sps
591 for (i = 0; i < cnt; i++) {
592 nalsize = AV_RB16(p) + 2;
593 if(nalsize > size - (p-buf))
594 return AVERROR_INVALIDDATA;
595 ret = decode_nal_units(h, p, nalsize, 1);
597 av_log(avctx, AV_LOG_ERROR,
598 "Decoding sps %d from avcC failed\n", i);
603 // Decode pps from avcC
604 cnt = *(p++); // Number of pps
605 for (i = 0; i < cnt; i++) {
606 nalsize = AV_RB16(p) + 2;
607 if(nalsize > size - (p-buf))
608 return AVERROR_INVALIDDATA;
609 ret = decode_nal_units(h, p, nalsize, 1);
611 av_log(avctx, AV_LOG_ERROR,
612 "Decoding pps %d from avcC failed\n", i);
617 // Store right nal length size that will be used to parse all other nals
618 h->nal_length_size = (buf[4] & 0x03) + 1;
621 ret = decode_nal_units(h, buf, size, 1);
628 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
630 H264Context *h = avctx->priv_data;
636 h->bit_depth_luma = 8;
637 h->chroma_format_idc = 1;
639 h->avctx->bits_per_raw_sample = 8;
640 h->cur_chroma_format_idc = 1;
642 ff_h264dsp_init(&h->h264dsp, 8, 1);
643 av_assert0(h->sps.bit_depth_chroma == 0);
644 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
645 ff_h264qpel_init(&h->h264qpel, 8);
646 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
648 h->dequant_coeff_pps = -1;
649 h->current_sps_id = -1;
651 /* needed so that IDCT permutation is known early */
652 ff_videodsp_init(&h->vdsp, 8);
654 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
655 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
657 h->picture_structure = PICT_FRAME;
658 h->slice_context_count = 1;
659 h->workaround_bugs = avctx->workaround_bugs;
660 h->flags = avctx->flags;
663 // s->decode_mb = ff_h263_decode_mb;
664 if (!avctx->has_b_frames)
667 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
669 ff_h264_decode_init_vlc();
671 ff_init_cabac_states();
674 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
676 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
677 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
680 return AVERROR(ENOMEM);
683 h->thread_context[0] = h;
684 for (i = 0; i < h->nb_slice_ctx; i++)
685 h->slice_ctx[i].h264 = h->thread_context[0];
687 h->outputed_poc = h->next_outputed_poc = INT_MIN;
688 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
689 h->last_pocs[i] = INT_MIN;
690 h->prev_poc_msb = 1 << 16;
691 h->prev_frame_num = -1;
693 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
694 ff_h264_reset_sei(h);
695 if (avctx->codec_id == AV_CODEC_ID_H264) {
696 if (avctx->ticks_per_frame == 1) {
697 if(h->avctx->time_base.den < INT_MAX/2) {
698 h->avctx->time_base.den *= 2;
700 h->avctx->time_base.num /= 2;
702 avctx->ticks_per_frame = 2;
705 if (avctx->extradata_size > 0 && avctx->extradata) {
706 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
708 ff_h264_free_context(h);
713 if (h->sps.bitstream_restriction_flag &&
714 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
715 h->avctx->has_b_frames = h->sps.num_reorder_frames;
719 avctx->internal->allocate_progress = 1;
721 ff_h264_flush_change(h);
726 static int decode_init_thread_copy(AVCodecContext *avctx)
728 H264Context *h = avctx->priv_data;
731 if (!avctx->internal->is_copy)
733 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
734 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
736 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
737 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
740 return AVERROR(ENOMEM);
743 for (i = 0; i < h->nb_slice_ctx; i++)
744 h->slice_ctx[i].h264 = h;
747 h->rbsp_buffer[0] = NULL;
748 h->rbsp_buffer[1] = NULL;
749 h->rbsp_buffer_size[0] = 0;
750 h->rbsp_buffer_size[1] = 0;
751 h->context_initialized = 0;
757 * Run setup operations that must be run after slice header decoding.
758 * This includes finding the next displayed frame.
760 * @param h h264 master context
761 * @param setup_finished enough NALs have been read that we can call
762 * ff_thread_finish_setup()
764 static void decode_postinit(H264Context *h, int setup_finished)
766 H264Picture *out = h->cur_pic_ptr;
767 H264Picture *cur = h->cur_pic_ptr;
768 int i, pics, out_of_order, out_idx;
770 h->cur_pic_ptr->f.pict_type = h->pict_type;
772 if (h->next_output_pic)
775 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
776 /* FIXME: if we have two PAFF fields in one packet, we can't start
777 * the next thread here. If we have one field per packet, we can.
778 * The check in decode_nal_units() is not good enough to find this
779 * yet, so we assume the worst for now. */
780 // if (setup_finished)
781 // ff_thread_finish_setup(h->avctx);
782 if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
784 if (h->avctx->hwaccel || h->missing_fields <=1)
788 cur->f.interlaced_frame = 0;
789 cur->f.repeat_pict = 0;
791 /* Signal interlacing information externally. */
792 /* Prioritize picture timing SEI information over used
793 * decoding process if it exists. */
795 if (h->sps.pic_struct_present_flag) {
796 switch (h->sei_pic_struct) {
797 case SEI_PIC_STRUCT_FRAME:
799 case SEI_PIC_STRUCT_TOP_FIELD:
800 case SEI_PIC_STRUCT_BOTTOM_FIELD:
801 cur->f.interlaced_frame = 1;
803 case SEI_PIC_STRUCT_TOP_BOTTOM:
804 case SEI_PIC_STRUCT_BOTTOM_TOP:
805 if (FIELD_OR_MBAFF_PICTURE(h))
806 cur->f.interlaced_frame = 1;
808 // try to flag soft telecine progressive
809 cur->f.interlaced_frame = h->prev_interlaced_frame;
811 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
812 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
813 /* Signal the possibility of telecined film externally
814 * (pic_struct 5,6). From these hints, let the applications
815 * decide if they apply deinterlacing. */
816 cur->f.repeat_pict = 1;
818 case SEI_PIC_STRUCT_FRAME_DOUBLING:
819 cur->f.repeat_pict = 2;
821 case SEI_PIC_STRUCT_FRAME_TRIPLING:
822 cur->f.repeat_pict = 4;
826 if ((h->sei_ct_type & 3) &&
827 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
828 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
830 /* Derive interlacing flag from used decoding process. */
831 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
833 h->prev_interlaced_frame = cur->f.interlaced_frame;
835 if (cur->field_poc[0] != cur->field_poc[1]) {
836 /* Derive top_field_first from field pocs. */
837 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
839 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
840 /* Use picture timing SEI information. Even if it is a
841 * information of a past frame, better than nothing. */
842 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
843 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
844 cur->f.top_field_first = 1;
846 cur->f.top_field_first = 0;
848 /* Most likely progressive */
849 cur->f.top_field_first = 0;
853 if (h->sei_frame_packing_present &&
854 h->frame_packing_arrangement_type >= 0 &&
855 h->frame_packing_arrangement_type <= 6 &&
856 h->content_interpretation_type > 0 &&
857 h->content_interpretation_type < 3) {
858 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
860 switch (h->frame_packing_arrangement_type) {
862 stereo->type = AV_STEREO3D_CHECKERBOARD;
865 stereo->type = AV_STEREO3D_COLUMNS;
868 stereo->type = AV_STEREO3D_LINES;
871 if (h->quincunx_subsampling)
872 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
874 stereo->type = AV_STEREO3D_SIDEBYSIDE;
877 stereo->type = AV_STEREO3D_TOPBOTTOM;
880 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
883 stereo->type = AV_STEREO3D_2D;
887 if (h->content_interpretation_type == 2)
888 stereo->flags = AV_STEREO3D_FLAG_INVERT;
892 if (h->sei_display_orientation_present &&
893 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
894 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
895 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
896 AV_FRAME_DATA_DISPLAYMATRIX,
897 sizeof(int32_t) * 9);
899 av_display_rotation_set((int32_t *)rotation->data, angle);
900 av_display_matrix_flip((int32_t *)rotation->data,
901 h->sei_hflip, h->sei_vflip);
905 cur->mmco_reset = h->mmco_reset;
908 // FIXME do something with unavailable reference frames
910 /* Sort B-frames into display order */
912 if (h->sps.bitstream_restriction_flag &&
913 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
914 h->avctx->has_b_frames = h->sps.num_reorder_frames;
918 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
919 !h->sps.bitstream_restriction_flag) {
920 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
924 for (i = 0; 1; i++) {
925 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
927 h->last_pocs[i-1] = cur->poc;
930 h->last_pocs[i-1]= h->last_pocs[i];
933 out_of_order = MAX_DELAYED_PIC_COUNT - i;
934 if( cur->f.pict_type == AV_PICTURE_TYPE_B
935 || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
936 out_of_order = FFMAX(out_of_order, 1);
937 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
938 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
939 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
940 h->last_pocs[i] = INT_MIN;
941 h->last_pocs[0] = cur->poc;
943 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
944 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
945 h->avctx->has_b_frames = out_of_order;
950 while (h->delayed_pic[pics])
953 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
955 h->delayed_pic[pics++] = cur;
956 if (cur->reference == 0)
957 cur->reference = DELAYED_PIC_REF;
959 out = h->delayed_pic[0];
961 for (i = 1; h->delayed_pic[i] &&
962 !h->delayed_pic[i]->f.key_frame &&
963 !h->delayed_pic[i]->mmco_reset;
965 if (h->delayed_pic[i]->poc < out->poc) {
966 out = h->delayed_pic[i];
969 if (h->avctx->has_b_frames == 0 &&
970 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
971 h->next_outputed_poc = INT_MIN;
972 out_of_order = out->poc < h->next_outputed_poc;
974 if (out_of_order || pics > h->avctx->has_b_frames) {
975 out->reference &= ~DELAYED_PIC_REF;
976 // for frame threading, the owner must be the second field's thread or
977 // else the first thread can release the picture and reuse it unsafely
978 for (i = out_idx; h->delayed_pic[i]; i++)
979 h->delayed_pic[i] = h->delayed_pic[i + 1];
981 if (!out_of_order && pics > h->avctx->has_b_frames) {
982 h->next_output_pic = out;
983 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
984 h->next_outputed_poc = INT_MIN;
986 h->next_outputed_poc = out->poc;
988 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
991 if (h->next_output_pic) {
992 if (h->next_output_pic->recovered) {
993 // We have reached an recovery point and all frames after it in
994 // display order are "recovered".
995 h->frame_recovered |= FRAME_RECOVERED_SEI;
997 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
1000 if (setup_finished && !h->avctx->hwaccel)
1001 ff_thread_finish_setup(h->avctx);
1004 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
1007 int luma_def, chroma_def;
1010 sl->use_weight_chroma = 0;
1011 sl->luma_log2_weight_denom = get_ue_golomb(&h->gb);
1012 if (h->sps.chroma_format_idc)
1013 sl->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
1015 if (sl->luma_log2_weight_denom > 7U) {
1016 av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
1017 sl->luma_log2_weight_denom = 0;
1019 if (sl->chroma_log2_weight_denom > 7U) {
1020 av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
1021 sl->chroma_log2_weight_denom = 0;
1024 luma_def = 1 << sl->luma_log2_weight_denom;
1025 chroma_def = 1 << sl->chroma_log2_weight_denom;
1027 for (list = 0; list < 2; list++) {
1028 sl->luma_weight_flag[list] = 0;
1029 sl->chroma_weight_flag[list] = 0;
1030 for (i = 0; i < h->ref_count[list]; i++) {
1031 int luma_weight_flag, chroma_weight_flag;
1033 luma_weight_flag = get_bits1(&h->gb);
1034 if (luma_weight_flag) {
1035 sl->luma_weight[i][list][0] = get_se_golomb(&h->gb);
1036 sl->luma_weight[i][list][1] = get_se_golomb(&h->gb);
1037 if (sl->luma_weight[i][list][0] != luma_def ||
1038 sl->luma_weight[i][list][1] != 0) {
1040 sl->luma_weight_flag[list] = 1;
1043 sl->luma_weight[i][list][0] = luma_def;
1044 sl->luma_weight[i][list][1] = 0;
1047 if (h->sps.chroma_format_idc) {
1048 chroma_weight_flag = get_bits1(&h->gb);
1049 if (chroma_weight_flag) {
1051 for (j = 0; j < 2; j++) {
1052 sl->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1053 sl->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1054 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1055 sl->chroma_weight[i][list][j][1] != 0) {
1056 sl->use_weight_chroma = 1;
1057 sl->chroma_weight_flag[list] = 1;
1062 for (j = 0; j < 2; j++) {
1063 sl->chroma_weight[i][list][j][0] = chroma_def;
1064 sl->chroma_weight[i][list][j][1] = 0;
1069 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1072 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1077 * instantaneous decoder refresh.
1079 static void idr(H264Context *h)
1082 ff_h264_remove_all_refs(h);
1084 h->prev_frame_num_offset = 0;
1085 h->prev_poc_msb = 1<<16;
1086 h->prev_poc_lsb = 0;
1087 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1088 h->last_pocs[i] = INT_MIN;
1091 /* forget old pics after a seek */
1092 void ff_h264_flush_change(H264Context *h)
1096 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1097 h->prev_interlaced_frame = 1;
1100 h->prev_frame_num = -1;
1101 if (h->cur_pic_ptr) {
1102 h->cur_pic_ptr->reference = 0;
1103 for (j=i=0; h->delayed_pic[i]; i++)
1104 if (h->delayed_pic[i] != h->cur_pic_ptr)
1105 h->delayed_pic[j++] = h->delayed_pic[i];
1106 h->delayed_pic[j] = NULL;
1108 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1111 ff_h264_reset_sei(h);
1112 h->recovery_frame = -1;
1113 h->frame_recovered = 0;
1115 h->current_slice = 0;
1119 /* forget old pics after a seek */
1120 static void flush_dpb(AVCodecContext *avctx)
1122 H264Context *h = avctx->priv_data;
1125 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1127 ff_h264_flush_change(h);
1130 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1131 ff_h264_unref_picture(h, &h->DPB[i]);
1132 h->cur_pic_ptr = NULL;
1133 ff_h264_unref_picture(h, &h->cur_pic);
1135 h->mb_x = h->mb_y = 0;
1137 ff_h264_free_tables(h, 1);
1138 h->context_initialized = 0;
1141 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1143 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1146 h->frame_num_offset = h->prev_frame_num_offset;
1147 if (h->frame_num < h->prev_frame_num)
1148 h->frame_num_offset += max_frame_num;
1150 if (h->sps.poc_type == 0) {
1151 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1153 if (h->poc_lsb < h->prev_poc_lsb &&
1154 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1155 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1156 else if (h->poc_lsb > h->prev_poc_lsb &&
1157 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1158 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1160 h->poc_msb = h->prev_poc_msb;
1162 field_poc[1] = h->poc_msb + h->poc_lsb;
1163 if (h->picture_structure == PICT_FRAME)
1164 field_poc[1] += h->delta_poc_bottom;
1165 } else if (h->sps.poc_type == 1) {
1166 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1169 if (h->sps.poc_cycle_length != 0)
1170 abs_frame_num = h->frame_num_offset + h->frame_num;
1174 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1177 expected_delta_per_poc_cycle = 0;
1178 for (i = 0; i < h->sps.poc_cycle_length; i++)
1179 // FIXME integrate during sps parse
1180 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1182 if (abs_frame_num > 0) {
1183 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1184 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1186 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1187 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1188 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1192 if (h->nal_ref_idc == 0)
1193 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1195 field_poc[0] = expectedpoc + h->delta_poc[0];
1196 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1198 if (h->picture_structure == PICT_FRAME)
1199 field_poc[1] += h->delta_poc[1];
1201 int poc = 2 * (h->frame_num_offset + h->frame_num);
1203 if (!h->nal_ref_idc)
1210 if (h->picture_structure != PICT_BOTTOM_FIELD)
1211 pic_field_poc[0] = field_poc[0];
1212 if (h->picture_structure != PICT_TOP_FIELD)
1213 pic_field_poc[1] = field_poc[1];
1214 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1220 * Compute profile from profile_idc and constraint_set?_flags.
1224 * @return profile as defined by FF_PROFILE_H264_*
1226 int ff_h264_get_profile(SPS *sps)
1228 int profile = sps->profile_idc;
1230 switch (sps->profile_idc) {
1231 case FF_PROFILE_H264_BASELINE:
1232 // constraint_set1_flag set to 1
1233 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1235 case FF_PROFILE_H264_HIGH_10:
1236 case FF_PROFILE_H264_HIGH_422:
1237 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1238 // constraint_set3_flag set to 1
1239 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1246 int ff_h264_set_parameter_from_sps(H264Context *h)
1248 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1249 (h->sps.bitstream_restriction_flag &&
1250 !h->sps.num_reorder_frames)) {
1251 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1252 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1253 "Reenabling low delay requires a codec flush.\n");
1258 if (h->avctx->has_b_frames < 2)
1259 h->avctx->has_b_frames = !h->low_delay;
1261 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1262 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1263 if (h->avctx->codec &&
1264 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
1265 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
1266 av_log(h->avctx, AV_LOG_ERROR,
1267 "VDPAU decoding does not support video colorspace.\n");
1268 return AVERROR_INVALIDDATA;
1270 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
1271 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
1272 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1273 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1274 h->pixel_shift = h->sps.bit_depth_luma > 8;
1276 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1277 h->sps.chroma_format_idc);
1278 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1279 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1280 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1281 h->sps.chroma_format_idc);
1283 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1285 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1286 h->sps.bit_depth_luma);
1287 return AVERROR_INVALIDDATA;
1293 int ff_set_ref_count(H264Context *h)
1295 int ref_count[2], list_count;
1296 int num_ref_idx_active_override_flag;
1298 // set defaults, might be overridden a few lines later
1299 ref_count[0] = h->pps.ref_count[0];
1300 ref_count[1] = h->pps.ref_count[1];
1302 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1304 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1306 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1307 h->direct_spatial_mv_pred = get_bits1(&h->gb);
1308 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1310 if (num_ref_idx_active_override_flag) {
1311 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1312 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1313 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1315 // full range is spec-ok in this case, even for frames
1319 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1320 av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]);
1321 h->ref_count[0] = h->ref_count[1] = 0;
1323 return AVERROR_INVALIDDATA;
1326 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1332 ref_count[0] = ref_count[1] = 0;
1335 if (list_count != h->list_count ||
1336 ref_count[0] != h->ref_count[0] ||
1337 ref_count[1] != h->ref_count[1]) {
1338 h->ref_count[0] = ref_count[0];
1339 h->ref_count[1] = ref_count[1];
1340 h->list_count = list_count;
1347 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1349 static int get_bit_length(H264Context *h, const uint8_t *buf,
1350 const uint8_t *ptr, int dst_length,
1351 int i, int next_avc)
1353 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1354 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1355 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1356 h->workaround_bugs |= FF_BUG_TRUNCATED;
1358 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1359 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1365 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1368 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1370 int next_avc = h->is_avc ? 0 : buf_size;
1373 int nals_needed = 0;
1374 int first_slice = 0;
1378 int dst_length, bit_length, consumed;
1381 if (buf_index >= next_avc) {
1382 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1385 next_avc = buf_index + nalsize;
1387 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1388 if (buf_index >= buf_size)
1390 if (buf_index >= next_avc)
1394 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1395 next_avc - buf_index);
1397 if (!ptr || dst_length < 0)
1398 return AVERROR_INVALIDDATA;
1400 buf_index += consumed;
1402 bit_length = get_bit_length(h, buf, ptr, dst_length,
1403 buf_index, next_avc);
1406 /* packets can sometimes contain multiple PPS/SPS,
1407 * e.g. two PAFF field pictures in one packet, or a demuxer
1408 * which splits NALs strangely if so, when frame threading we
1409 * can't start the next thread until we've read all of them */
1410 switch (h->nal_unit_type) {
1413 nals_needed = nal_index;
1418 init_get_bits(&h->gb, ptr, bit_length);
1419 if (!get_ue_golomb(&h->gb) ||
1421 first_slice != h->nal_unit_type)
1422 nals_needed = nal_index;
1424 first_slice = h->nal_unit_type;
1431 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1432 int parse_extradata)
1434 AVCodecContext *const avctx = h->avctx;
1435 H264Context *hx; ///< thread context
1436 H264SliceContext *sl;
1438 unsigned context_count;
1440 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1445 h->nal_unit_type= 0;
1447 if(!h->slice_context_count)
1448 h->slice_context_count= 1;
1449 h->max_contexts = h->slice_context_count;
1450 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1451 h->current_slice = 0;
1452 if (!h->first_field)
1453 h->cur_pic_ptr = NULL;
1454 ff_h264_reset_sei(h);
1457 if (h->nal_length_size == 4) {
1458 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1460 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1464 if (avctx->active_thread_type & FF_THREAD_FRAME)
1465 nals_needed = get_last_needed_nal(h, buf, buf_size);
1470 next_avc = h->is_avc ? 0 : buf_size;
1480 if (buf_index >= next_avc) {
1481 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1484 next_avc = buf_index + nalsize;
1486 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1487 if (buf_index >= buf_size)
1489 if (buf_index >= next_avc)
1493 hx = h->thread_context[context_count];
1494 sl = &h->slice_ctx[context_count];
1496 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1497 &consumed, next_avc - buf_index);
1498 if (!ptr || dst_length < 0) {
1503 bit_length = get_bit_length(h, buf, ptr, dst_length,
1504 buf_index + consumed, next_avc);
1506 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1507 av_log(h->avctx, AV_LOG_DEBUG,
1508 "NAL %d/%d at %d/%d length %d\n",
1509 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
1511 if (h->is_avc && (nalsize != consumed) && nalsize)
1512 av_log(h->avctx, AV_LOG_DEBUG,
1513 "AVC: Consumed only %d bytes instead of %d\n",
1516 buf_index += consumed;
1519 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1520 h->nal_ref_idc == 0 &&
1521 h->nal_unit_type != NAL_SEI)
1525 if ( (!(avctx->active_thread_type & FF_THREAD_FRAME) || nals_needed >= nal_index)
1526 && !h->current_slice)
1528 /* Ignore per frame NAL unit type during extradata
1529 * parsing. Decoding slices is not possible in codec init
1531 if (parse_extradata) {
1532 switch (hx->nal_unit_type) {
1538 av_log(h->avctx, AV_LOG_WARNING,
1539 "Ignoring NAL %d in global header/extradata\n",
1541 // fall through to next case
1542 case NAL_AUXILIARY_SLICE:
1543 hx->nal_unit_type = NAL_FF_IGNORE;
1549 switch (hx->nal_unit_type) {
1551 if ((ptr[0] & 0xFC) == 0x98) {
1552 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1553 h->next_outputed_poc = INT_MIN;
1557 if (h->nal_unit_type != NAL_IDR_SLICE) {
1558 av_log(h->avctx, AV_LOG_ERROR,
1559 "Invalid mix of idr and non-idr slices\n");
1564 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1566 h->has_recovery_point = 1;
1568 init_get_bits(&hx->gb, ptr, bit_length);
1570 hx->inter_gb_ptr = &hx->gb;
1572 if ((err = ff_h264_decode_slice_header(hx, sl, h)))
1575 if (h->sei_recovery_frame_cnt >= 0) {
1576 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
1577 h->valid_recovery_point = 1;
1579 if ( h->recovery_frame < 0
1580 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
1581 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1582 ((1 << h->sps.log2_max_frame_num) - 1);
1584 if (!h->valid_recovery_point)
1585 h->recovery_frame = h->frame_num;
1589 h->cur_pic_ptr->f.key_frame |=
1590 (hx->nal_unit_type == NAL_IDR_SLICE);
1592 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1593 h->recovery_frame == h->frame_num) {
1594 h->recovery_frame = -1;
1595 h->cur_pic_ptr->recovered = 1;
1597 // If we have an IDR, all frames after it in decoded order are
1599 if (hx->nal_unit_type == NAL_IDR_SLICE)
1600 h->frame_recovered |= FRAME_RECOVERED_IDR;
1601 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1602 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1604 h->cur_pic_ptr->recovered |= h->frame_recovered;
1606 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1609 if (h->current_slice == 1) {
1610 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1611 decode_postinit(h, nal_index >= nals_needed);
1613 if (h->avctx->hwaccel &&
1614 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1616 if (CONFIG_H264_VDPAU_DECODER &&
1617 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
1618 ff_vdpau_h264_picture_start(h);
1621 if (hx->redundant_pic_count == 0) {
1622 if (avctx->hwaccel) {
1623 ret = avctx->hwaccel->decode_slice(avctx,
1624 &buf[buf_index - consumed],
1628 } else if (CONFIG_H264_VDPAU_DECODER &&
1629 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
1630 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1632 sizeof(start_code));
1633 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1634 &buf[buf_index - consumed],
1643 avpriv_request_sample(avctx, "data partitioning");
1644 ret = AVERROR(ENOSYS);
1648 init_get_bits(&h->gb, ptr, bit_length);
1649 ret = ff_h264_decode_sei(h);
1650 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1654 init_get_bits(&h->gb, ptr, bit_length);
1655 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
1656 av_log(h->avctx, AV_LOG_DEBUG,
1657 "SPS decoding failure, trying again with the complete NAL\n");
1659 av_assert0(next_avc - buf_index + consumed == nalsize);
1660 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1662 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1663 8*(next_avc - buf_index + consumed - 1));
1664 ff_h264_decode_seq_parameter_set(h);
1669 init_get_bits(&h->gb, ptr, bit_length);
1670 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1671 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1675 case NAL_END_SEQUENCE:
1676 case NAL_END_STREAM:
1677 case NAL_FILLER_DATA:
1679 case NAL_AUXILIARY_SLICE:
1684 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1685 hx->nal_unit_type, bit_length);
1688 if (context_count == h->max_contexts) {
1689 ret = ff_h264_execute_decode_slices(h, context_count);
1690 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1695 if (err < 0 || err == SLICE_SKIPED) {
1697 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1698 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1699 } else if (err == SLICE_SINGLETHREAD) {
1700 /* Slice could not be decoded in parallel mode, copy down
1701 * NAL unit stuff to context 0 and restart. Note that
1702 * rbsp_buffer is not transferred, but since we no longer
1703 * run in parallel mode this should not be an issue. */
1704 h->nal_unit_type = hx->nal_unit_type;
1705 h->nal_ref_idc = hx->nal_ref_idc;
1707 sl = &h->slice_ctx[0];
1712 if (context_count) {
1713 ret = ff_h264_execute_decode_slices(h, context_count);
1714 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1721 if (h->cur_pic_ptr && !h->droppable) {
1722 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1723 h->picture_structure == PICT_BOTTOM_FIELD);
1726 return (ret < 0) ? ret : buf_index;
1730 * Return the number of bytes consumed for building the current frame.
1732 static int get_consumed_bytes(int pos, int buf_size)
1735 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1736 if (pos + 10 > buf_size)
1737 pos = buf_size; // oops ;)
1742 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1744 AVFrame *src = &srcp->f;
1745 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1747 int ret = av_frame_ref(dst, src);
1751 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1753 if (srcp->sei_recovery_frame_cnt == 0)
1758 for (i = 0; i < desc->nb_components; i++) {
1759 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1760 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1761 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1762 (srcp->crop_top >> vshift) * dst->linesize[i];
1763 dst->data[i] += off;
1768 static int is_extra(const uint8_t *buf, int buf_size)
1770 int cnt= buf[5]&0x1f;
1771 const uint8_t *p= buf+6;
1773 int nalsize= AV_RB16(p) + 2;
1774 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1782 int nalsize= AV_RB16(p) + 2;
1783 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1790 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1791 int *got_frame, AVPacket *avpkt)
1793 const uint8_t *buf = avpkt->data;
1794 int buf_size = avpkt->size;
1795 H264Context *h = avctx->priv_data;
1796 AVFrame *pict = data;
1802 h->flags = avctx->flags;
1804 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1806 /* end of stream, output what is still in the buffers */
1807 if (buf_size == 0) {
1810 h->cur_pic_ptr = NULL;
1813 // FIXME factorize this with the output code below
1814 out = h->delayed_pic[0];
1817 h->delayed_pic[i] &&
1818 !h->delayed_pic[i]->f.key_frame &&
1819 !h->delayed_pic[i]->mmco_reset;
1821 if (h->delayed_pic[i]->poc < out->poc) {
1822 out = h->delayed_pic[i];
1826 for (i = out_idx; h->delayed_pic[i]; i++)
1827 h->delayed_pic[i] = h->delayed_pic[i + 1];
1830 out->reference &= ~DELAYED_PIC_REF;
1831 ret = output_frame(h, pict, out);
1839 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1841 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1842 if (is_extra(side, side_size))
1843 ff_h264_decode_extradata(h, side, side_size);
1845 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1846 if (is_extra(buf, buf_size))
1847 return ff_h264_decode_extradata(h, buf, buf_size);
1850 buf_index = decode_nal_units(h, buf, buf_size, 0);
1852 return AVERROR_INVALIDDATA;
1854 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1855 av_assert0(buf_index <= buf_size);
1859 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1860 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1861 buf_size >= 4 && !memcmp("Q264", buf, 4))
1863 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1864 return AVERROR_INVALIDDATA;
1867 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1868 (h->mb_y >= h->mb_height && h->mb_height)) {
1869 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1870 decode_postinit(h, 1);
1872 ff_h264_field_end(h, 0);
1874 /* Wait for second field. */
1876 if (h->next_output_pic && (
1877 h->next_output_pic->recovered)) {
1878 if (!h->next_output_pic->recovered)
1879 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1881 if (!h->avctx->hwaccel &&
1882 (h->next_output_pic->field_poc[0] == INT_MAX ||
1883 h->next_output_pic->field_poc[1] == INT_MAX)
1886 AVFrame *f = &h->next_output_pic->f;
1887 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1888 uint8_t *dst_data[4];
1890 const uint8_t *src_data[4];
1892 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1894 for (p = 0; p<4; p++) {
1895 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1896 src_data[p] = f->data[p] + field *f->linesize[p];
1897 linesizes[p] = 2*f->linesize[p];
1900 av_image_copy(dst_data, linesizes, src_data, linesizes,
1901 f->format, f->width, f->height>>1);
1904 ret = output_frame(h, pict, h->next_output_pic);
1908 if (CONFIG_MPEGVIDEO) {
1909 ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,
1910 h->next_output_pic->mb_type,
1911 h->next_output_pic->qscale_table,
1912 h->next_output_pic->motion_val,
1914 h->mb_width, h->mb_height, h->mb_stride, 1);
1919 av_assert0(pict->buf[0] || !*got_frame);
1921 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1923 return get_consumed_bytes(buf_index, buf_size);
1926 av_cold void ff_h264_free_context(H264Context *h)
1930 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1932 av_freep(&h->slice_ctx);
1933 h->nb_slice_ctx = 0;
1935 for (i = 0; i < MAX_SPS_COUNT; i++)
1936 av_freep(h->sps_buffers + i);
1938 for (i = 0; i < MAX_PPS_COUNT; i++)
1939 av_freep(h->pps_buffers + i);
1942 static av_cold int h264_decode_end(AVCodecContext *avctx)
1944 H264Context *h = avctx->priv_data;
1946 ff_h264_remove_all_refs(h);
1947 ff_h264_free_context(h);
1949 ff_h264_unref_picture(h, &h->cur_pic);
1950 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1955 static const AVProfile profiles[] = {
1956 { FF_PROFILE_H264_BASELINE, "Baseline" },
1957 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1958 { FF_PROFILE_H264_MAIN, "Main" },
1959 { FF_PROFILE_H264_EXTENDED, "Extended" },
1960 { FF_PROFILE_H264_HIGH, "High" },
1961 { FF_PROFILE_H264_HIGH_10, "High 10" },
1962 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1963 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1964 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1965 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1966 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1967 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1968 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1969 { FF_PROFILE_UNKNOWN },
1972 static const AVOption h264_options[] = {
1973 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1974 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1978 static const AVClass h264_class = {
1979 .class_name = "H264 Decoder",
1980 .item_name = av_default_item_name,
1981 .option = h264_options,
1982 .version = LIBAVUTIL_VERSION_INT,
1985 AVCodec ff_h264_decoder = {
1987 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1988 .type = AVMEDIA_TYPE_VIDEO,
1989 .id = AV_CODEC_ID_H264,
1990 .priv_data_size = sizeof(H264Context),
1991 .init = ff_h264_decode_init,
1992 .close = h264_decode_end,
1993 .decode = h264_decode_frame,
1994 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1995 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1996 CODEC_CAP_FRAME_THREADS,
1998 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1999 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
2000 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2001 .priv_class = &h264_class,
2004 #if CONFIG_H264_VDPAU_DECODER
2005 static const AVClass h264_vdpau_class = {
2006 .class_name = "H264 VDPAU Decoder",
2007 .item_name = av_default_item_name,
2008 .option = h264_options,
2009 .version = LIBAVUTIL_VERSION_INT,
2012 AVCodec ff_h264_vdpau_decoder = {
2013 .name = "h264_vdpau",
2014 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
2015 .type = AVMEDIA_TYPE_VIDEO,
2016 .id = AV_CODEC_ID_H264,
2017 .priv_data_size = sizeof(H264Context),
2018 .init = ff_h264_decode_init,
2019 .close = h264_decode_end,
2020 .decode = h264_decode_frame,
2021 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2023 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2025 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2026 .priv_class = &h264_vdpau_class,