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, H264SliceContext *sl)
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[sl->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 sl->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[sl->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 sl->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 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
437 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
438 big_mb_num * 48 * sizeof(uint8_t), fail)
439 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
440 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
441 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
442 big_mb_num * sizeof(uint16_t), fail)
443 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
444 big_mb_num * sizeof(uint8_t), fail)
445 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
446 row_mb_num, 16 * sizeof(uint8_t), fail);
447 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
448 row_mb_num, 16 * sizeof(uint8_t), fail);
449 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
450 4 * big_mb_num * sizeof(uint8_t), fail);
451 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
452 big_mb_num * sizeof(uint8_t), fail)
454 memset(h->slice_table_base, -1,
455 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
456 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
458 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
459 big_mb_num * sizeof(uint32_t), fail);
460 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
461 big_mb_num * sizeof(uint32_t), fail);
462 for (y = 0; y < h->mb_height; y++)
463 for (x = 0; x < h->mb_width; x++) {
464 const int mb_xy = x + y * h->mb_stride;
465 const int b_xy = 4 * x + 4 * y * h->b_stride;
467 h->mb2b_xy[mb_xy] = b_xy;
468 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
471 if (!h->dequant4_coeff[0])
472 ff_h264_init_dequant_tables(h);
475 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
478 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
479 av_frame_unref(&h->DPB[i].f);
480 av_frame_unref(&h->cur_pic.f);
486 ff_h264_free_tables(h, 1);
487 return AVERROR(ENOMEM);
492 * Allocate buffers which are not shared amongst multiple threads.
494 int ff_h264_context_init(H264Context *h)
496 ERContext *er = &h->er;
497 int mb_array_size = h->mb_height * h->mb_stride;
498 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
499 int c_size = h->mb_stride * (h->mb_height + 1);
500 int yc_size = y_size + 2 * c_size;
503 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->top_borders[0],
504 h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
505 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->top_borders[1],
506 h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
508 h->ref_cache[0][scan8[5] + 1] =
509 h->ref_cache[0][scan8[7] + 1] =
510 h->ref_cache[0][scan8[13] + 1] =
511 h->ref_cache[1][scan8[5] + 1] =
512 h->ref_cache[1][scan8[7] + 1] =
513 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
515 if (CONFIG_ERROR_RESILIENCE) {
517 er->avctx = h->avctx;
518 er->decode_mb = h264_er_decode_mb;
520 er->quarter_sample = 1;
522 er->mb_num = h->mb_num;
523 er->mb_width = h->mb_width;
524 er->mb_height = h->mb_height;
525 er->mb_stride = h->mb_stride;
526 er->b8_stride = h->mb_width * 2 + 1;
528 // error resilience code looks cleaner with this
529 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
530 (h->mb_num + 1) * sizeof(int), fail);
532 for (y = 0; y < h->mb_height; y++)
533 for (x = 0; x < h->mb_width; x++)
534 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
536 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
537 h->mb_stride + h->mb_width;
539 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
540 mb_array_size * sizeof(uint8_t), fail);
542 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
543 memset(er->mbintra_table, 1, mb_array_size);
545 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
547 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
548 h->mb_height * h->mb_stride, fail);
550 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,
551 yc_size * sizeof(int16_t), fail);
552 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
553 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
554 er->dc_val[2] = er->dc_val[1] + c_size;
555 for (i = 0; i < yc_size; i++)
556 h->dc_val_base[i] = 1024;
562 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
565 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
566 int parse_extradata);
568 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
570 AVCodecContext *avctx = h->avctx;
573 if (!buf || size <= 0)
578 const unsigned char *p = buf;
583 av_log(avctx, AV_LOG_ERROR,
584 "avcC %d too short\n", size);
585 return AVERROR_INVALIDDATA;
587 /* sps and pps in the avcC always have length coded with 2 bytes,
588 * so put a fake nal_length_size = 2 while parsing them */
589 h->nal_length_size = 2;
590 // Decode sps from avcC
591 cnt = *(p + 5) & 0x1f; // Number of sps
593 for (i = 0; i < cnt; i++) {
594 nalsize = AV_RB16(p) + 2;
595 if(nalsize > size - (p-buf))
596 return AVERROR_INVALIDDATA;
597 ret = decode_nal_units(h, p, nalsize, 1);
599 av_log(avctx, AV_LOG_ERROR,
600 "Decoding sps %d from avcC failed\n", i);
605 // Decode pps from avcC
606 cnt = *(p++); // Number of pps
607 for (i = 0; i < cnt; i++) {
608 nalsize = AV_RB16(p) + 2;
609 if(nalsize > size - (p-buf))
610 return AVERROR_INVALIDDATA;
611 ret = decode_nal_units(h, p, nalsize, 1);
613 av_log(avctx, AV_LOG_ERROR,
614 "Decoding pps %d from avcC failed\n", i);
619 // Store right nal length size that will be used to parse all other nals
620 h->nal_length_size = (buf[4] & 0x03) + 1;
623 ret = decode_nal_units(h, buf, size, 1);
630 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
632 H264Context *h = avctx->priv_data;
638 h->bit_depth_luma = 8;
639 h->chroma_format_idc = 1;
641 h->avctx->bits_per_raw_sample = 8;
642 h->cur_chroma_format_idc = 1;
644 ff_h264dsp_init(&h->h264dsp, 8, 1);
645 av_assert0(h->sps.bit_depth_chroma == 0);
646 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
647 ff_h264qpel_init(&h->h264qpel, 8);
648 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
650 h->dequant_coeff_pps = -1;
651 h->current_sps_id = -1;
653 /* needed so that IDCT permutation is known early */
654 ff_videodsp_init(&h->vdsp, 8);
656 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
657 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
659 h->picture_structure = PICT_FRAME;
660 h->slice_context_count = 1;
661 h->workaround_bugs = avctx->workaround_bugs;
662 h->flags = avctx->flags;
665 // s->decode_mb = ff_h263_decode_mb;
666 if (!avctx->has_b_frames)
669 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
671 ff_h264_decode_init_vlc();
673 ff_init_cabac_states();
676 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
678 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
679 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
682 return AVERROR(ENOMEM);
685 h->thread_context[0] = h;
686 for (i = 0; i < h->nb_slice_ctx; i++)
687 h->slice_ctx[i].h264 = h->thread_context[0];
689 h->outputed_poc = h->next_outputed_poc = INT_MIN;
690 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
691 h->last_pocs[i] = INT_MIN;
692 h->prev_poc_msb = 1 << 16;
693 h->prev_frame_num = -1;
695 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
696 ff_h264_reset_sei(h);
697 if (avctx->codec_id == AV_CODEC_ID_H264) {
698 if (avctx->ticks_per_frame == 1) {
699 if(h->avctx->time_base.den < INT_MAX/2) {
700 h->avctx->time_base.den *= 2;
702 h->avctx->time_base.num /= 2;
704 avctx->ticks_per_frame = 2;
707 if (avctx->extradata_size > 0 && avctx->extradata) {
708 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
710 ff_h264_free_context(h);
715 if (h->sps.bitstream_restriction_flag &&
716 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
717 h->avctx->has_b_frames = h->sps.num_reorder_frames;
721 avctx->internal->allocate_progress = 1;
723 ff_h264_flush_change(h);
728 static int decode_init_thread_copy(AVCodecContext *avctx)
730 H264Context *h = avctx->priv_data;
733 if (!avctx->internal->is_copy)
735 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
736 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
738 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
739 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
742 return AVERROR(ENOMEM);
745 for (i = 0; i < h->nb_slice_ctx; i++)
746 h->slice_ctx[i].h264 = h;
749 h->rbsp_buffer[0] = NULL;
750 h->rbsp_buffer[1] = NULL;
751 h->rbsp_buffer_size[0] = 0;
752 h->rbsp_buffer_size[1] = 0;
753 h->context_initialized = 0;
759 * Run setup operations that must be run after slice header decoding.
760 * This includes finding the next displayed frame.
762 * @param h h264 master context
763 * @param setup_finished enough NALs have been read that we can call
764 * ff_thread_finish_setup()
766 static void decode_postinit(H264Context *h, int setup_finished)
768 H264Picture *out = h->cur_pic_ptr;
769 H264Picture *cur = h->cur_pic_ptr;
770 int i, pics, out_of_order, out_idx;
772 h->cur_pic_ptr->f.pict_type = h->pict_type;
774 if (h->next_output_pic)
777 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
778 /* FIXME: if we have two PAFF fields in one packet, we can't start
779 * the next thread here. If we have one field per packet, we can.
780 * The check in decode_nal_units() is not good enough to find this
781 * yet, so we assume the worst for now. */
782 // if (setup_finished)
783 // ff_thread_finish_setup(h->avctx);
784 if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
786 if (h->avctx->hwaccel || h->missing_fields <=1)
790 cur->f.interlaced_frame = 0;
791 cur->f.repeat_pict = 0;
793 /* Signal interlacing information externally. */
794 /* Prioritize picture timing SEI information over used
795 * decoding process if it exists. */
797 if (h->sps.pic_struct_present_flag) {
798 switch (h->sei_pic_struct) {
799 case SEI_PIC_STRUCT_FRAME:
801 case SEI_PIC_STRUCT_TOP_FIELD:
802 case SEI_PIC_STRUCT_BOTTOM_FIELD:
803 cur->f.interlaced_frame = 1;
805 case SEI_PIC_STRUCT_TOP_BOTTOM:
806 case SEI_PIC_STRUCT_BOTTOM_TOP:
807 if (FIELD_OR_MBAFF_PICTURE(h))
808 cur->f.interlaced_frame = 1;
810 // try to flag soft telecine progressive
811 cur->f.interlaced_frame = h->prev_interlaced_frame;
813 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
814 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
815 /* Signal the possibility of telecined film externally
816 * (pic_struct 5,6). From these hints, let the applications
817 * decide if they apply deinterlacing. */
818 cur->f.repeat_pict = 1;
820 case SEI_PIC_STRUCT_FRAME_DOUBLING:
821 cur->f.repeat_pict = 2;
823 case SEI_PIC_STRUCT_FRAME_TRIPLING:
824 cur->f.repeat_pict = 4;
828 if ((h->sei_ct_type & 3) &&
829 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
830 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
832 /* Derive interlacing flag from used decoding process. */
833 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
835 h->prev_interlaced_frame = cur->f.interlaced_frame;
837 if (cur->field_poc[0] != cur->field_poc[1]) {
838 /* Derive top_field_first from field pocs. */
839 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
841 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
842 /* Use picture timing SEI information. Even if it is a
843 * information of a past frame, better than nothing. */
844 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
845 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
846 cur->f.top_field_first = 1;
848 cur->f.top_field_first = 0;
850 /* Most likely progressive */
851 cur->f.top_field_first = 0;
855 if (h->sei_frame_packing_present &&
856 h->frame_packing_arrangement_type >= 0 &&
857 h->frame_packing_arrangement_type <= 6 &&
858 h->content_interpretation_type > 0 &&
859 h->content_interpretation_type < 3) {
860 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
862 switch (h->frame_packing_arrangement_type) {
864 stereo->type = AV_STEREO3D_CHECKERBOARD;
867 stereo->type = AV_STEREO3D_COLUMNS;
870 stereo->type = AV_STEREO3D_LINES;
873 if (h->quincunx_subsampling)
874 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
876 stereo->type = AV_STEREO3D_SIDEBYSIDE;
879 stereo->type = AV_STEREO3D_TOPBOTTOM;
882 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
885 stereo->type = AV_STEREO3D_2D;
889 if (h->content_interpretation_type == 2)
890 stereo->flags = AV_STEREO3D_FLAG_INVERT;
894 if (h->sei_display_orientation_present &&
895 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
896 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
897 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
898 AV_FRAME_DATA_DISPLAYMATRIX,
899 sizeof(int32_t) * 9);
901 av_display_rotation_set((int32_t *)rotation->data, angle);
902 av_display_matrix_flip((int32_t *)rotation->data,
903 h->sei_hflip, h->sei_vflip);
907 cur->mmco_reset = h->mmco_reset;
910 // FIXME do something with unavailable reference frames
912 /* Sort B-frames into display order */
914 if (h->sps.bitstream_restriction_flag &&
915 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
916 h->avctx->has_b_frames = h->sps.num_reorder_frames;
920 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
921 !h->sps.bitstream_restriction_flag) {
922 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
926 for (i = 0; 1; i++) {
927 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
929 h->last_pocs[i-1] = cur->poc;
932 h->last_pocs[i-1]= h->last_pocs[i];
935 out_of_order = MAX_DELAYED_PIC_COUNT - i;
936 if( cur->f.pict_type == AV_PICTURE_TYPE_B
937 || (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))
938 out_of_order = FFMAX(out_of_order, 1);
939 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
940 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
941 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
942 h->last_pocs[i] = INT_MIN;
943 h->last_pocs[0] = cur->poc;
945 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
946 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
947 h->avctx->has_b_frames = out_of_order;
952 while (h->delayed_pic[pics])
955 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
957 h->delayed_pic[pics++] = cur;
958 if (cur->reference == 0)
959 cur->reference = DELAYED_PIC_REF;
961 out = h->delayed_pic[0];
963 for (i = 1; h->delayed_pic[i] &&
964 !h->delayed_pic[i]->f.key_frame &&
965 !h->delayed_pic[i]->mmco_reset;
967 if (h->delayed_pic[i]->poc < out->poc) {
968 out = h->delayed_pic[i];
971 if (h->avctx->has_b_frames == 0 &&
972 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
973 h->next_outputed_poc = INT_MIN;
974 out_of_order = out->poc < h->next_outputed_poc;
976 if (out_of_order || pics > h->avctx->has_b_frames) {
977 out->reference &= ~DELAYED_PIC_REF;
978 // for frame threading, the owner must be the second field's thread or
979 // else the first thread can release the picture and reuse it unsafely
980 for (i = out_idx; h->delayed_pic[i]; i++)
981 h->delayed_pic[i] = h->delayed_pic[i + 1];
983 if (!out_of_order && pics > h->avctx->has_b_frames) {
984 h->next_output_pic = out;
985 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
986 h->next_outputed_poc = INT_MIN;
988 h->next_outputed_poc = out->poc;
990 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
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);
1017 if (sl->luma_log2_weight_denom > 7U) {
1018 av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
1019 sl->luma_log2_weight_denom = 0;
1021 if (sl->chroma_log2_weight_denom > 7U) {
1022 av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
1023 sl->chroma_log2_weight_denom = 0;
1026 luma_def = 1 << sl->luma_log2_weight_denom;
1027 chroma_def = 1 << sl->chroma_log2_weight_denom;
1029 for (list = 0; list < 2; list++) {
1030 sl->luma_weight_flag[list] = 0;
1031 sl->chroma_weight_flag[list] = 0;
1032 for (i = 0; i < h->ref_count[list]; i++) {
1033 int luma_weight_flag, chroma_weight_flag;
1035 luma_weight_flag = get_bits1(&h->gb);
1036 if (luma_weight_flag) {
1037 sl->luma_weight[i][list][0] = get_se_golomb(&h->gb);
1038 sl->luma_weight[i][list][1] = get_se_golomb(&h->gb);
1039 if (sl->luma_weight[i][list][0] != luma_def ||
1040 sl->luma_weight[i][list][1] != 0) {
1042 sl->luma_weight_flag[list] = 1;
1045 sl->luma_weight[i][list][0] = luma_def;
1046 sl->luma_weight[i][list][1] = 0;
1049 if (h->sps.chroma_format_idc) {
1050 chroma_weight_flag = get_bits1(&h->gb);
1051 if (chroma_weight_flag) {
1053 for (j = 0; j < 2; j++) {
1054 sl->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1055 sl->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1056 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1057 sl->chroma_weight[i][list][j][1] != 0) {
1058 sl->use_weight_chroma = 1;
1059 sl->chroma_weight_flag[list] = 1;
1064 for (j = 0; j < 2; j++) {
1065 sl->chroma_weight[i][list][j][0] = chroma_def;
1066 sl->chroma_weight[i][list][j][1] = 0;
1071 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1074 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1079 * instantaneous decoder refresh.
1081 static void idr(H264Context *h)
1084 ff_h264_remove_all_refs(h);
1086 h->prev_frame_num_offset = 0;
1087 h->prev_poc_msb = 1<<16;
1088 h->prev_poc_lsb = 0;
1089 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1090 h->last_pocs[i] = INT_MIN;
1093 /* forget old pics after a seek */
1094 void ff_h264_flush_change(H264Context *h)
1098 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1099 h->prev_interlaced_frame = 1;
1102 h->prev_frame_num = -1;
1103 if (h->cur_pic_ptr) {
1104 h->cur_pic_ptr->reference = 0;
1105 for (j=i=0; h->delayed_pic[i]; i++)
1106 if (h->delayed_pic[i] != h->cur_pic_ptr)
1107 h->delayed_pic[j++] = h->delayed_pic[i];
1108 h->delayed_pic[j] = NULL;
1110 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1113 ff_h264_reset_sei(h);
1114 h->recovery_frame = -1;
1115 h->frame_recovered = 0;
1117 h->current_slice = 0;
1121 /* forget old pics after a seek */
1122 static void flush_dpb(AVCodecContext *avctx)
1124 H264Context *h = avctx->priv_data;
1127 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1129 ff_h264_flush_change(h);
1132 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1133 ff_h264_unref_picture(h, &h->DPB[i]);
1134 h->cur_pic_ptr = NULL;
1135 ff_h264_unref_picture(h, &h->cur_pic);
1137 h->mb_x = h->mb_y = 0;
1139 ff_h264_free_tables(h, 1);
1140 h->context_initialized = 0;
1143 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1145 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1148 h->frame_num_offset = h->prev_frame_num_offset;
1149 if (h->frame_num < h->prev_frame_num)
1150 h->frame_num_offset += max_frame_num;
1152 if (h->sps.poc_type == 0) {
1153 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1155 if (h->poc_lsb < h->prev_poc_lsb &&
1156 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1157 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1158 else if (h->poc_lsb > h->prev_poc_lsb &&
1159 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1160 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1162 h->poc_msb = h->prev_poc_msb;
1164 field_poc[1] = h->poc_msb + h->poc_lsb;
1165 if (h->picture_structure == PICT_FRAME)
1166 field_poc[1] += h->delta_poc_bottom;
1167 } else if (h->sps.poc_type == 1) {
1168 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1171 if (h->sps.poc_cycle_length != 0)
1172 abs_frame_num = h->frame_num_offset + h->frame_num;
1176 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1179 expected_delta_per_poc_cycle = 0;
1180 for (i = 0; i < h->sps.poc_cycle_length; i++)
1181 // FIXME integrate during sps parse
1182 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1184 if (abs_frame_num > 0) {
1185 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1186 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1188 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1189 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1190 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1194 if (h->nal_ref_idc == 0)
1195 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1197 field_poc[0] = expectedpoc + h->delta_poc[0];
1198 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1200 if (h->picture_structure == PICT_FRAME)
1201 field_poc[1] += h->delta_poc[1];
1203 int poc = 2 * (h->frame_num_offset + h->frame_num);
1205 if (!h->nal_ref_idc)
1212 if (h->picture_structure != PICT_BOTTOM_FIELD)
1213 pic_field_poc[0] = field_poc[0];
1214 if (h->picture_structure != PICT_TOP_FIELD)
1215 pic_field_poc[1] = field_poc[1];
1216 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1222 * Compute profile from profile_idc and constraint_set?_flags.
1226 * @return profile as defined by FF_PROFILE_H264_*
1228 int ff_h264_get_profile(SPS *sps)
1230 int profile = sps->profile_idc;
1232 switch (sps->profile_idc) {
1233 case FF_PROFILE_H264_BASELINE:
1234 // constraint_set1_flag set to 1
1235 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1237 case FF_PROFILE_H264_HIGH_10:
1238 case FF_PROFILE_H264_HIGH_422:
1239 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1240 // constraint_set3_flag set to 1
1241 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1248 int ff_h264_set_parameter_from_sps(H264Context *h)
1250 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1251 (h->sps.bitstream_restriction_flag &&
1252 !h->sps.num_reorder_frames)) {
1253 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1254 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1255 "Reenabling low delay requires a codec flush.\n");
1260 if (h->avctx->has_b_frames < 2)
1261 h->avctx->has_b_frames = !h->low_delay;
1263 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1264 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1265 if (h->avctx->codec &&
1266 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
1267 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
1268 av_log(h->avctx, AV_LOG_ERROR,
1269 "VDPAU decoding does not support video colorspace.\n");
1270 return AVERROR_INVALIDDATA;
1272 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
1273 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
1274 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1275 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1276 h->pixel_shift = h->sps.bit_depth_luma > 8;
1278 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1279 h->sps.chroma_format_idc);
1280 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1281 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1282 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1283 h->sps.chroma_format_idc);
1285 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1287 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1288 h->sps.bit_depth_luma);
1289 return AVERROR_INVALIDDATA;
1295 int ff_set_ref_count(H264Context *h)
1297 int ref_count[2], list_count;
1298 int num_ref_idx_active_override_flag;
1300 // set defaults, might be overridden a few lines later
1301 ref_count[0] = h->pps.ref_count[0];
1302 ref_count[1] = h->pps.ref_count[1];
1304 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1306 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1308 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1309 h->direct_spatial_mv_pred = get_bits1(&h->gb);
1310 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1312 if (num_ref_idx_active_override_flag) {
1313 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1314 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1315 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1317 // full range is spec-ok in this case, even for frames
1321 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1322 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]);
1323 h->ref_count[0] = h->ref_count[1] = 0;
1325 return AVERROR_INVALIDDATA;
1328 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1334 ref_count[0] = ref_count[1] = 0;
1337 if (list_count != h->list_count ||
1338 ref_count[0] != h->ref_count[0] ||
1339 ref_count[1] != h->ref_count[1]) {
1340 h->ref_count[0] = ref_count[0];
1341 h->ref_count[1] = ref_count[1];
1342 h->list_count = list_count;
1349 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
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;
1376 int first_slice = 0;
1380 int dst_length, bit_length, consumed;
1383 if (buf_index >= next_avc) {
1384 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1387 next_avc = buf_index + nalsize;
1389 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1390 if (buf_index >= buf_size)
1392 if (buf_index >= next_avc)
1396 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1397 next_avc - buf_index);
1399 if (!ptr || dst_length < 0)
1400 return AVERROR_INVALIDDATA;
1402 buf_index += consumed;
1404 bit_length = get_bit_length(h, buf, ptr, dst_length,
1405 buf_index, next_avc);
1408 /* packets can sometimes contain multiple PPS/SPS,
1409 * e.g. two PAFF field pictures in one packet, or a demuxer
1410 * which splits NALs strangely if so, when frame threading we
1411 * can't start the next thread until we've read all of them */
1412 switch (h->nal_unit_type) {
1415 nals_needed = nal_index;
1420 init_get_bits(&h->gb, ptr, bit_length);
1421 if (!get_ue_golomb(&h->gb) ||
1423 first_slice != h->nal_unit_type)
1424 nals_needed = nal_index;
1426 first_slice = h->nal_unit_type;
1433 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1434 int parse_extradata)
1436 AVCodecContext *const avctx = h->avctx;
1437 H264Context *hx; ///< thread context
1438 H264SliceContext *sl;
1440 unsigned context_count;
1442 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1447 h->nal_unit_type= 0;
1449 if(!h->slice_context_count)
1450 h->slice_context_count= 1;
1451 h->max_contexts = h->slice_context_count;
1452 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1453 h->current_slice = 0;
1454 if (!h->first_field)
1455 h->cur_pic_ptr = NULL;
1456 ff_h264_reset_sei(h);
1459 if (h->nal_length_size == 4) {
1460 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1462 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1466 if (avctx->active_thread_type & FF_THREAD_FRAME)
1467 nals_needed = get_last_needed_nal(h, buf, buf_size);
1472 next_avc = h->is_avc ? 0 : buf_size;
1482 if (buf_index >= next_avc) {
1483 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1486 next_avc = buf_index + nalsize;
1488 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1489 if (buf_index >= buf_size)
1491 if (buf_index >= next_avc)
1495 hx = h->thread_context[context_count];
1496 sl = &h->slice_ctx[context_count];
1498 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1499 &consumed, next_avc - buf_index);
1500 if (!ptr || dst_length < 0) {
1505 bit_length = get_bit_length(h, buf, ptr, dst_length,
1506 buf_index + consumed, next_avc);
1508 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1509 av_log(h->avctx, AV_LOG_DEBUG,
1510 "NAL %d/%d at %d/%d length %d\n",
1511 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
1513 if (h->is_avc && (nalsize != consumed) && nalsize)
1514 av_log(h->avctx, AV_LOG_DEBUG,
1515 "AVC: Consumed only %d bytes instead of %d\n",
1518 buf_index += consumed;
1521 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1522 h->nal_ref_idc == 0 &&
1523 h->nal_unit_type != NAL_SEI)
1527 if ( (!(avctx->active_thread_type & FF_THREAD_FRAME) || nals_needed >= nal_index)
1528 && !h->current_slice)
1530 /* Ignore per frame NAL unit type during extradata
1531 * parsing. Decoding slices is not possible in codec init
1533 if (parse_extradata) {
1534 switch (hx->nal_unit_type) {
1540 av_log(h->avctx, AV_LOG_WARNING,
1541 "Ignoring NAL %d in global header/extradata\n",
1543 // fall through to next case
1544 case NAL_AUXILIARY_SLICE:
1545 hx->nal_unit_type = NAL_FF_IGNORE;
1551 switch (hx->nal_unit_type) {
1553 if ((ptr[0] & 0xFC) == 0x98) {
1554 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1555 h->next_outputed_poc = INT_MIN;
1559 if (h->nal_unit_type != NAL_IDR_SLICE) {
1560 av_log(h->avctx, AV_LOG_ERROR,
1561 "Invalid mix of idr and non-idr slices\n");
1566 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1568 h->has_recovery_point = 1;
1570 init_get_bits(&hx->gb, ptr, bit_length);
1572 hx->inter_gb_ptr = &hx->gb;
1574 if ((err = ff_h264_decode_slice_header(hx, sl, h)))
1577 if (h->sei_recovery_frame_cnt >= 0) {
1578 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
1579 h->valid_recovery_point = 1;
1581 if ( h->recovery_frame < 0
1582 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
1583 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1584 ((1 << h->sps.log2_max_frame_num) - 1);
1586 if (!h->valid_recovery_point)
1587 h->recovery_frame = h->frame_num;
1591 h->cur_pic_ptr->f.key_frame |=
1592 (hx->nal_unit_type == NAL_IDR_SLICE);
1594 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1595 h->recovery_frame == h->frame_num) {
1596 h->recovery_frame = -1;
1597 h->cur_pic_ptr->recovered = 1;
1599 // If we have an IDR, all frames after it in decoded order are
1601 if (hx->nal_unit_type == NAL_IDR_SLICE)
1602 h->frame_recovered |= FRAME_RECOVERED_IDR;
1603 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1604 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1606 h->cur_pic_ptr->recovered |= h->frame_recovered;
1608 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1611 if (h->current_slice == 1) {
1612 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1613 decode_postinit(h, nal_index >= nals_needed);
1615 if (h->avctx->hwaccel &&
1616 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1618 if (CONFIG_H264_VDPAU_DECODER &&
1619 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
1620 ff_vdpau_h264_picture_start(h);
1623 if (hx->redundant_pic_count == 0) {
1624 if (avctx->hwaccel) {
1625 ret = avctx->hwaccel->decode_slice(avctx,
1626 &buf[buf_index - consumed],
1630 } else if (CONFIG_H264_VDPAU_DECODER &&
1631 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
1632 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1634 sizeof(start_code));
1635 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1636 &buf[buf_index - consumed],
1645 avpriv_request_sample(avctx, "data partitioning");
1646 ret = AVERROR(ENOSYS);
1650 init_get_bits(&h->gb, ptr, bit_length);
1651 ret = ff_h264_decode_sei(h);
1652 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1656 init_get_bits(&h->gb, ptr, bit_length);
1657 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
1658 av_log(h->avctx, AV_LOG_DEBUG,
1659 "SPS decoding failure, trying again with the complete NAL\n");
1661 av_assert0(next_avc - buf_index + consumed == nalsize);
1662 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1664 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1665 8*(next_avc - buf_index + consumed - 1));
1666 ff_h264_decode_seq_parameter_set(h);
1671 init_get_bits(&h->gb, ptr, bit_length);
1672 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1673 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1677 case NAL_END_SEQUENCE:
1678 case NAL_END_STREAM:
1679 case NAL_FILLER_DATA:
1681 case NAL_AUXILIARY_SLICE:
1686 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1687 hx->nal_unit_type, bit_length);
1690 if (context_count == h->max_contexts) {
1691 ret = ff_h264_execute_decode_slices(h, context_count);
1692 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1697 if (err < 0 || err == SLICE_SKIPED) {
1699 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1700 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1701 } else if (err == SLICE_SINGLETHREAD) {
1702 /* Slice could not be decoded in parallel mode, copy down
1703 * NAL unit stuff to context 0 and restart. Note that
1704 * rbsp_buffer is not transferred, but since we no longer
1705 * run in parallel mode this should not be an issue. */
1706 h->nal_unit_type = hx->nal_unit_type;
1707 h->nal_ref_idc = hx->nal_ref_idc;
1709 sl = &h->slice_ctx[0];
1714 if (context_count) {
1715 ret = ff_h264_execute_decode_slices(h, context_count);
1716 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1723 if (h->cur_pic_ptr && !h->droppable) {
1724 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1725 h->picture_structure == PICT_BOTTOM_FIELD);
1728 return (ret < 0) ? ret : buf_index;
1732 * Return the number of bytes consumed for building the current frame.
1734 static int get_consumed_bytes(int pos, int buf_size)
1737 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1738 if (pos + 10 > buf_size)
1739 pos = buf_size; // oops ;)
1744 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1746 AVFrame *src = &srcp->f;
1747 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1749 int ret = av_frame_ref(dst, src);
1753 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1755 if (srcp->sei_recovery_frame_cnt == 0)
1760 for (i = 0; i < desc->nb_components; i++) {
1761 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1762 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1763 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1764 (srcp->crop_top >> vshift) * dst->linesize[i];
1765 dst->data[i] += off;
1770 static int is_extra(const uint8_t *buf, int buf_size)
1772 int cnt= buf[5]&0x1f;
1773 const uint8_t *p= buf+6;
1775 int nalsize= AV_RB16(p) + 2;
1776 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1784 int nalsize= AV_RB16(p) + 2;
1785 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1792 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1793 int *got_frame, AVPacket *avpkt)
1795 const uint8_t *buf = avpkt->data;
1796 int buf_size = avpkt->size;
1797 H264Context *h = avctx->priv_data;
1798 AVFrame *pict = data;
1804 h->flags = avctx->flags;
1806 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1808 /* end of stream, output what is still in the buffers */
1809 if (buf_size == 0) {
1812 h->cur_pic_ptr = NULL;
1815 // FIXME factorize this with the output code below
1816 out = h->delayed_pic[0];
1819 h->delayed_pic[i] &&
1820 !h->delayed_pic[i]->f.key_frame &&
1821 !h->delayed_pic[i]->mmco_reset;
1823 if (h->delayed_pic[i]->poc < out->poc) {
1824 out = h->delayed_pic[i];
1828 for (i = out_idx; h->delayed_pic[i]; i++)
1829 h->delayed_pic[i] = h->delayed_pic[i + 1];
1832 out->reference &= ~DELAYED_PIC_REF;
1833 ret = output_frame(h, pict, out);
1841 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1843 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1844 if (is_extra(side, side_size))
1845 ff_h264_decode_extradata(h, side, side_size);
1847 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1848 if (is_extra(buf, buf_size))
1849 return ff_h264_decode_extradata(h, buf, buf_size);
1852 buf_index = decode_nal_units(h, buf, buf_size, 0);
1854 return AVERROR_INVALIDDATA;
1856 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1857 av_assert0(buf_index <= buf_size);
1861 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1862 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1863 buf_size >= 4 && !memcmp("Q264", buf, 4))
1865 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1866 return AVERROR_INVALIDDATA;
1869 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1870 (h->mb_y >= h->mb_height && h->mb_height)) {
1871 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1872 decode_postinit(h, 1);
1874 ff_h264_field_end(h, 0);
1876 /* Wait for second field. */
1878 if (h->next_output_pic && (
1879 h->next_output_pic->recovered)) {
1880 if (!h->next_output_pic->recovered)
1881 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1883 if (!h->avctx->hwaccel &&
1884 (h->next_output_pic->field_poc[0] == INT_MAX ||
1885 h->next_output_pic->field_poc[1] == INT_MAX)
1888 AVFrame *f = &h->next_output_pic->f;
1889 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1890 uint8_t *dst_data[4];
1892 const uint8_t *src_data[4];
1894 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1896 for (p = 0; p<4; p++) {
1897 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1898 src_data[p] = f->data[p] + field *f->linesize[p];
1899 linesizes[p] = 2*f->linesize[p];
1902 av_image_copy(dst_data, linesizes, src_data, linesizes,
1903 f->format, f->width, f->height>>1);
1906 ret = output_frame(h, pict, h->next_output_pic);
1910 if (CONFIG_MPEGVIDEO) {
1911 ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,
1912 h->next_output_pic->mb_type,
1913 h->next_output_pic->qscale_table,
1914 h->next_output_pic->motion_val,
1916 h->mb_width, h->mb_height, h->mb_stride, 1);
1921 av_assert0(pict->buf[0] || !*got_frame);
1923 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1925 return get_consumed_bytes(buf_index, buf_size);
1928 av_cold void ff_h264_free_context(H264Context *h)
1932 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1934 av_freep(&h->slice_ctx);
1935 h->nb_slice_ctx = 0;
1937 for (i = 0; i < MAX_SPS_COUNT; i++)
1938 av_freep(h->sps_buffers + i);
1940 for (i = 0; i < MAX_PPS_COUNT; i++)
1941 av_freep(h->pps_buffers + i);
1944 static av_cold int h264_decode_end(AVCodecContext *avctx)
1946 H264Context *h = avctx->priv_data;
1948 ff_h264_remove_all_refs(h);
1949 ff_h264_free_context(h);
1951 ff_h264_unref_picture(h, &h->cur_pic);
1952 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1957 static const AVProfile profiles[] = {
1958 { FF_PROFILE_H264_BASELINE, "Baseline" },
1959 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1960 { FF_PROFILE_H264_MAIN, "Main" },
1961 { FF_PROFILE_H264_EXTENDED, "Extended" },
1962 { FF_PROFILE_H264_HIGH, "High" },
1963 { FF_PROFILE_H264_HIGH_10, "High 10" },
1964 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1965 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1966 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1967 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1968 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1969 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1970 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1971 { FF_PROFILE_UNKNOWN },
1974 static const AVOption h264_options[] = {
1975 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1976 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1980 static const AVClass h264_class = {
1981 .class_name = "H264 Decoder",
1982 .item_name = av_default_item_name,
1983 .option = h264_options,
1984 .version = LIBAVUTIL_VERSION_INT,
1987 AVCodec ff_h264_decoder = {
1989 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1990 .type = AVMEDIA_TYPE_VIDEO,
1991 .id = AV_CODEC_ID_H264,
1992 .priv_data_size = sizeof(H264Context),
1993 .init = ff_h264_decode_init,
1994 .close = h264_decode_end,
1995 .decode = h264_decode_frame,
1996 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1997 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1998 CODEC_CAP_FRAME_THREADS,
2000 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
2001 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
2002 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2003 .priv_class = &h264_class,
2006 #if CONFIG_H264_VDPAU_DECODER
2007 static const AVClass h264_vdpau_class = {
2008 .class_name = "H264 VDPAU Decoder",
2009 .item_name = av_default_item_name,
2010 .option = h264_options,
2011 .version = LIBAVUTIL_VERSION_INT,
2014 AVCodec ff_h264_vdpau_decoder = {
2015 .name = "h264_vdpau",
2016 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
2017 .type = AVMEDIA_TYPE_VIDEO,
2018 .id = AV_CODEC_ID_H264,
2019 .priv_data_size = sizeof(H264Context),
2020 .init = ff_h264_decode_init,
2021 .close = h264_decode_end,
2022 .decode = h264_decode_frame,
2023 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2025 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2027 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2028 .priv_class = &h264_vdpau_class,