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"
40 #include "error_resilience.h"
44 #include "h264chroma.h"
45 #include "h264_mvpred.h"
48 #include "mpegutils.h"
49 #include "rectangle.h"
52 #include "vdpau_internal.h"
56 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
58 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
60 H264Context *h = avctx->priv_data;
61 return h ? h->sps.num_reorder_frames : 0;
64 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
66 int mb_x, int mb_y, int mb_intra, int mb_skipped)
68 H264Context *h = opaque;
72 h->mb_xy = mb_x + mb_y * h->mb_stride;
73 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
75 /* FIXME: It is possible albeit uncommon that slice references
76 * differ between slices. We take the easy approach and ignore
77 * it for now. If this turns out to have any relevance in
78 * practice then correct remapping should be added. */
79 if (ref >= h->ref_count[0])
81 if (!h->ref_list[0][ref].f.data[0]) {
82 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
85 if ((h->ref_list[0][ref].reference&3) != 3) {
86 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
89 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
91 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
92 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
93 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
95 h->mb_field_decoding_flag = 0;
96 ff_h264_hl_decode_mb(h);
99 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
101 AVCodecContext *avctx = h->avctx;
102 AVFrame *cur = &h->cur_pic.f;
103 AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
104 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
105 int vshift = desc->log2_chroma_h;
106 const int field_pic = h->picture_structure != PICT_FRAME;
112 height = FFMIN(height, avctx->height - y);
114 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
117 if (avctx->draw_horiz_band) {
119 int offset[AV_NUM_DATA_POINTERS];
122 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
123 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
130 offset[0] = y * src->linesize[0];
132 offset[2] = (y >> vshift) * src->linesize[1];
133 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
138 avctx->draw_horiz_band(avctx, src, offset,
139 y, h->picture_structure, height);
144 * Check if the top & left blocks are available if needed and
145 * change the dc mode so it only uses the available blocks.
147 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
149 static const int8_t top[12] = {
150 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
152 static const int8_t left[12] = {
153 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
157 if (!(h->top_samples_available & 0x8000)) {
158 for (i = 0; i < 4; i++) {
159 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
161 av_log(h->avctx, AV_LOG_ERROR,
162 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
163 status, h->mb_x, h->mb_y);
164 return AVERROR_INVALIDDATA;
166 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
171 if ((h->left_samples_available & 0x8888) != 0x8888) {
172 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
173 for (i = 0; i < 4; i++)
174 if (!(h->left_samples_available & mask[i])) {
175 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
177 av_log(h->avctx, AV_LOG_ERROR,
178 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
179 status, h->mb_x, h->mb_y);
180 return AVERROR_INVALIDDATA;
182 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
188 } // FIXME cleanup like ff_h264_check_intra_pred_mode
191 * Check if the top & left blocks are available if needed and
192 * change the dc mode so it only uses the available blocks.
194 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
196 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
197 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
200 av_log(h->avctx, AV_LOG_ERROR,
201 "out of range intra chroma pred mode at %d %d\n",
203 return AVERROR_INVALIDDATA;
206 if (!(h->top_samples_available & 0x8000)) {
209 av_log(h->avctx, AV_LOG_ERROR,
210 "top block unavailable for requested intra mode at %d %d\n",
212 return AVERROR_INVALIDDATA;
216 if ((h->left_samples_available & 0x8080) != 0x8080) {
218 if (is_chroma && (h->left_samples_available & 0x8080)) {
219 // mad cow disease mode, aka MBAFF + constrained_intra_pred
220 mode = ALZHEIMER_DC_L0T_PRED8x8 +
221 (!(h->left_samples_available & 0x8000)) +
222 2 * (mode == DC_128_PRED8x8);
225 av_log(h->avctx, AV_LOG_ERROR,
226 "left block unavailable for requested intra mode at %d %d\n",
228 return AVERROR_INVALIDDATA;
235 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
236 int *dst_length, int *consumed, int length)
242 // src[0]&0x80; // forbidden bit
243 h->nal_ref_idc = src[0] >> 5;
244 h->nal_unit_type = src[0] & 0x1F;
249 #define STARTCODE_TEST \
250 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
251 if (src[i + 2] != 3) { \
252 /* startcode, so we must be past the end */ \
258 #if HAVE_FAST_UNALIGNED
259 #define FIND_FIRST_ZERO \
260 if (i > 0 && !src[i]) \
266 for (i = 0; i + 1 < length; i += 9) {
267 if (!((~AV_RN64A(src + i) &
268 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
269 0x8000800080008080ULL))
276 for (i = 0; i + 1 < length; i += 5) {
277 if (!((~AV_RN32A(src + i) &
278 (AV_RN32A(src + i) - 0x01000101U)) &
287 for (i = 0; i + 1 < length; i += 2) {
290 if (i > 0 && src[i - 1] == 0)
296 // use second escape buffer for inter data
297 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
299 si = h->rbsp_buffer_size[bufidx];
300 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
301 dst = h->rbsp_buffer[bufidx];
306 if(i>=length-1){ //no escaped 0
308 *consumed= length+1; //+1 for the header
309 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
312 memcpy(dst, src, length);
319 while (si + 2 < length) {
320 // remove escapes (very rare 1:2^22)
321 if (src[si + 2] > 3) {
322 dst[di++] = src[si++];
323 dst[di++] = src[si++];
324 } else if (src[si] == 0 && src[si + 1] == 0) {
325 if (src[si + 2] == 3) { // escape
330 } else // next start code
334 dst[di++] = src[si++];
337 dst[di++] = src[si++];
340 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
343 *consumed = si + 1; // +1 for the header
344 /* FIXME store exact number of bits in the getbitcontext
345 * (it is needed for decoding) */
350 * Identify the exact end of the bitstream
351 * @return the length of the trailing, or 0 if damaged
353 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
358 tprintf(h->avctx, "rbsp trailing %X\n", v);
360 for (r = 1; r < 9; r++) {
368 void ff_h264_free_tables(H264Context *h, int free_rbsp)
373 av_freep(&h->intra4x4_pred_mode);
374 av_freep(&h->chroma_pred_mode_table);
375 av_freep(&h->cbp_table);
376 av_freep(&h->mvd_table[0]);
377 av_freep(&h->mvd_table[1]);
378 av_freep(&h->direct_table);
379 av_freep(&h->non_zero_count);
380 av_freep(&h->slice_table_base);
381 h->slice_table = NULL;
382 av_freep(&h->list_counts);
384 av_freep(&h->mb2b_xy);
385 av_freep(&h->mb2br_xy);
387 av_buffer_pool_uninit(&h->qscale_table_pool);
388 av_buffer_pool_uninit(&h->mb_type_pool);
389 av_buffer_pool_uninit(&h->motion_val_pool);
390 av_buffer_pool_uninit(&h->ref_index_pool);
392 if (free_rbsp && h->DPB) {
393 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
394 ff_h264_unref_picture(h, &h->DPB[i]);
397 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
398 h->DPB[i].needs_realloc = 1;
401 h->cur_pic_ptr = NULL;
403 for (i = 0; i < H264_MAX_THREADS; i++) {
404 hx = h->thread_context[i];
407 av_freep(&hx->top_borders[1]);
408 av_freep(&hx->top_borders[0]);
409 av_freep(&hx->bipred_scratchpad);
410 av_freep(&hx->edge_emu_buffer);
411 av_freep(&hx->dc_val_base);
412 av_freep(&hx->er.mb_index2xy);
413 av_freep(&hx->er.error_status_table);
414 av_freep(&hx->er.er_temp_buffer);
415 av_freep(&hx->er.mbintra_table);
416 av_freep(&hx->er.mbskip_table);
419 av_freep(&hx->rbsp_buffer[1]);
420 av_freep(&hx->rbsp_buffer[0]);
421 hx->rbsp_buffer_size[0] = 0;
422 hx->rbsp_buffer_size[1] = 0;
425 av_freep(&h->thread_context[i]);
429 int ff_h264_alloc_tables(H264Context *h)
431 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
432 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
435 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
436 row_mb_num * 8 * sizeof(uint8_t), fail)
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_OR_GOTO(h->avctx, h->mvd_table[0],
446 16 * row_mb_num * sizeof(uint8_t), fail);
447 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
448 16 * row_mb_num * 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 h264_init_dequant_tables(h);
475 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
477 return AVERROR(ENOMEM);
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_OR_GOTO(h->avctx, h->top_borders[0],
504 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
505 FF_ALLOCZ_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;
519 er->decode_mb = h264_er_decode_mb;
521 er->quarter_sample = 1;
523 er->mb_num = h->mb_num;
524 er->mb_width = h->mb_width;
525 er->mb_height = h->mb_height;
526 er->mb_stride = h->mb_stride;
527 er->b8_stride = h->mb_width * 2 + 1;
529 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
530 fail); // error ressilience code looks cleaner with this
531 for (y = 0; y < h->mb_height; y++)
532 for (x = 0; x < h->mb_width; x++)
533 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
535 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
536 h->mb_stride + h->mb_width;
538 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
539 mb_array_size * sizeof(uint8_t), fail);
541 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
542 memset(er->mbintra_table, 1, mb_array_size);
544 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
546 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
549 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, 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 // Now 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 if (CONFIG_ERROR_RESILIENCE)
653 ff_dsputil_init(&h->dsp, h->avctx);
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->thread_context[0] = h;
679 h->outputed_poc = h->next_outputed_poc = INT_MIN;
680 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
681 h->last_pocs[i] = INT_MIN;
682 h->prev_poc_msb = 1 << 16;
683 h->prev_frame_num = -1;
685 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
686 ff_h264_reset_sei(h);
687 if (avctx->codec_id == AV_CODEC_ID_H264) {
688 if (avctx->ticks_per_frame == 1) {
689 if(h->avctx->time_base.den < INT_MAX/2) {
690 h->avctx->time_base.den *= 2;
692 h->avctx->time_base.num /= 2;
694 avctx->ticks_per_frame = 2;
697 if (avctx->extradata_size > 0 && avctx->extradata) {
698 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
700 ff_h264_free_context(h);
705 if (h->sps.bitstream_restriction_flag &&
706 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
707 h->avctx->has_b_frames = h->sps.num_reorder_frames;
711 avctx->internal->allocate_progress = 1;
713 ff_h264_flush_change(h);
718 static int decode_init_thread_copy(AVCodecContext *avctx)
720 H264Context *h = avctx->priv_data;
722 if (!avctx->internal->is_copy)
724 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
725 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
727 h->rbsp_buffer[0] = NULL;
728 h->rbsp_buffer[1] = NULL;
729 h->rbsp_buffer_size[0] = 0;
730 h->rbsp_buffer_size[1] = 0;
731 h->context_initialized = 0;
737 * Run setup operations that must be run after slice header decoding.
738 * This includes finding the next displayed frame.
740 * @param h h264 master context
741 * @param setup_finished enough NALs have been read that we can call
742 * ff_thread_finish_setup()
744 static void decode_postinit(H264Context *h, int setup_finished)
746 H264Picture *out = h->cur_pic_ptr;
747 H264Picture *cur = h->cur_pic_ptr;
748 int i, pics, out_of_order, out_idx;
750 h->cur_pic_ptr->f.pict_type = h->pict_type;
752 if (h->next_output_pic)
755 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
756 /* FIXME: if we have two PAFF fields in one packet, we can't start
757 * the next thread here. If we have one field per packet, we can.
758 * The check in decode_nal_units() is not good enough to find this
759 * yet, so we assume the worst for now. */
760 // if (setup_finished)
761 // ff_thread_finish_setup(h->avctx);
765 cur->f.interlaced_frame = 0;
766 cur->f.repeat_pict = 0;
768 /* Signal interlacing information externally. */
769 /* Prioritize picture timing SEI information over used
770 * decoding process if it exists. */
772 if (h->sps.pic_struct_present_flag) {
773 switch (h->sei_pic_struct) {
774 case SEI_PIC_STRUCT_FRAME:
776 case SEI_PIC_STRUCT_TOP_FIELD:
777 case SEI_PIC_STRUCT_BOTTOM_FIELD:
778 cur->f.interlaced_frame = 1;
780 case SEI_PIC_STRUCT_TOP_BOTTOM:
781 case SEI_PIC_STRUCT_BOTTOM_TOP:
782 if (FIELD_OR_MBAFF_PICTURE(h))
783 cur->f.interlaced_frame = 1;
785 // try to flag soft telecine progressive
786 cur->f.interlaced_frame = h->prev_interlaced_frame;
788 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
789 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
790 /* Signal the possibility of telecined film externally
791 * (pic_struct 5,6). From these hints, let the applications
792 * decide if they apply deinterlacing. */
793 cur->f.repeat_pict = 1;
795 case SEI_PIC_STRUCT_FRAME_DOUBLING:
796 cur->f.repeat_pict = 2;
798 case SEI_PIC_STRUCT_FRAME_TRIPLING:
799 cur->f.repeat_pict = 4;
803 if ((h->sei_ct_type & 3) &&
804 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
805 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
807 /* Derive interlacing flag from used decoding process. */
808 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
810 h->prev_interlaced_frame = cur->f.interlaced_frame;
812 if (cur->field_poc[0] != cur->field_poc[1]) {
813 /* Derive top_field_first from field pocs. */
814 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
816 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
817 /* Use picture timing SEI information. Even if it is a
818 * information of a past frame, better than nothing. */
819 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
820 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
821 cur->f.top_field_first = 1;
823 cur->f.top_field_first = 0;
825 /* Most likely progressive */
826 cur->f.top_field_first = 0;
830 if (h->sei_frame_packing_present &&
831 h->frame_packing_arrangement_type >= 0 &&
832 h->frame_packing_arrangement_type <= 6 &&
833 h->content_interpretation_type > 0 &&
834 h->content_interpretation_type < 3) {
835 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
839 switch (h->frame_packing_arrangement_type) {
841 stereo->type = AV_STEREO3D_CHECKERBOARD;
844 stereo->type = AV_STEREO3D_LINES;
847 stereo->type = AV_STEREO3D_COLUMNS;
850 if (h->quincunx_subsampling)
851 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
853 stereo->type = AV_STEREO3D_SIDEBYSIDE;
856 stereo->type = AV_STEREO3D_TOPBOTTOM;
859 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
862 stereo->type = AV_STEREO3D_2D;
866 if (h->content_interpretation_type == 2)
867 stereo->flags = AV_STEREO3D_FLAG_INVERT;
870 if (h->sei_display_orientation_present &&
871 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
872 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
873 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
874 AV_FRAME_DATA_DISPLAYMATRIX,
875 sizeof(int32_t) * 9);
879 av_display_rotation_set((int32_t *)rotation->data, angle);
880 av_display_matrix_flip((int32_t *)rotation->data,
881 h->sei_vflip, h->sei_hflip);
884 cur->mmco_reset = h->mmco_reset;
887 // FIXME do something with unavailable reference frames
889 /* Sort B-frames into display order */
891 if (h->sps.bitstream_restriction_flag &&
892 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
893 h->avctx->has_b_frames = h->sps.num_reorder_frames;
897 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
898 !h->sps.bitstream_restriction_flag) {
899 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
903 for (i = 0; 1; i++) {
904 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
906 h->last_pocs[i-1] = cur->poc;
909 h->last_pocs[i-1]= h->last_pocs[i];
912 out_of_order = MAX_DELAYED_PIC_COUNT - i;
913 if( cur->f.pict_type == AV_PICTURE_TYPE_B
914 || (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))
915 out_of_order = FFMAX(out_of_order, 1);
916 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
917 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
918 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
919 h->last_pocs[i] = INT_MIN;
920 h->last_pocs[0] = cur->poc;
922 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
923 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
924 h->avctx->has_b_frames = out_of_order;
929 while (h->delayed_pic[pics])
932 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
934 h->delayed_pic[pics++] = cur;
935 if (cur->reference == 0)
936 cur->reference = DELAYED_PIC_REF;
938 out = h->delayed_pic[0];
940 for (i = 1; h->delayed_pic[i] &&
941 !h->delayed_pic[i]->f.key_frame &&
942 !h->delayed_pic[i]->mmco_reset;
944 if (h->delayed_pic[i]->poc < out->poc) {
945 out = h->delayed_pic[i];
948 if (h->avctx->has_b_frames == 0 &&
949 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
950 h->next_outputed_poc = INT_MIN;
951 out_of_order = out->poc < h->next_outputed_poc;
953 if (out_of_order || pics > h->avctx->has_b_frames) {
954 out->reference &= ~DELAYED_PIC_REF;
955 // for frame threading, the owner must be the second field's thread or
956 // else the first thread can release the picture and reuse it unsafely
957 for (i = out_idx; h->delayed_pic[i]; i++)
958 h->delayed_pic[i] = h->delayed_pic[i + 1];
960 if (!out_of_order && pics > h->avctx->has_b_frames) {
961 h->next_output_pic = out;
962 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
963 h->next_outputed_poc = INT_MIN;
965 h->next_outputed_poc = out->poc;
967 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
970 if (h->next_output_pic) {
971 if (h->next_output_pic->recovered) {
972 // We have reached an recovery point and all frames after it in
973 // display order are "recovered".
974 h->frame_recovered |= FRAME_RECOVERED_SEI;
976 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
979 if (setup_finished && !h->avctx->hwaccel)
980 ff_thread_finish_setup(h->avctx);
983 int ff_pred_weight_table(H264Context *h)
986 int luma_def, chroma_def;
989 h->use_weight_chroma = 0;
990 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
991 if (h->sps.chroma_format_idc)
992 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
993 luma_def = 1 << h->luma_log2_weight_denom;
994 chroma_def = 1 << h->chroma_log2_weight_denom;
996 for (list = 0; list < 2; list++) {
997 h->luma_weight_flag[list] = 0;
998 h->chroma_weight_flag[list] = 0;
999 for (i = 0; i < h->ref_count[list]; i++) {
1000 int luma_weight_flag, chroma_weight_flag;
1002 luma_weight_flag = get_bits1(&h->gb);
1003 if (luma_weight_flag) {
1004 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
1005 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
1006 if (h->luma_weight[i][list][0] != luma_def ||
1007 h->luma_weight[i][list][1] != 0) {
1009 h->luma_weight_flag[list] = 1;
1012 h->luma_weight[i][list][0] = luma_def;
1013 h->luma_weight[i][list][1] = 0;
1016 if (h->sps.chroma_format_idc) {
1017 chroma_weight_flag = get_bits1(&h->gb);
1018 if (chroma_weight_flag) {
1020 for (j = 0; j < 2; j++) {
1021 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1022 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1023 if (h->chroma_weight[i][list][j][0] != chroma_def ||
1024 h->chroma_weight[i][list][j][1] != 0) {
1025 h->use_weight_chroma = 1;
1026 h->chroma_weight_flag[list] = 1;
1031 for (j = 0; j < 2; j++) {
1032 h->chroma_weight[i][list][j][0] = chroma_def;
1033 h->chroma_weight[i][list][j][1] = 0;
1038 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1041 h->use_weight = h->use_weight || h->use_weight_chroma;
1046 * instantaneous decoder refresh.
1048 static void idr(H264Context *h)
1051 ff_h264_remove_all_refs(h);
1052 h->prev_frame_num = 0;
1053 h->prev_frame_num_offset = 0;
1054 h->prev_poc_msb = 1<<16;
1055 h->prev_poc_lsb = 0;
1056 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1057 h->last_pocs[i] = INT_MIN;
1060 /* forget old pics after a seek */
1061 void ff_h264_flush_change(H264Context *h)
1065 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1066 h->prev_interlaced_frame = 1;
1069 h->prev_frame_num = -1;
1070 if (h->cur_pic_ptr) {
1071 h->cur_pic_ptr->reference = 0;
1072 for (j=i=0; h->delayed_pic[i]; i++)
1073 if (h->delayed_pic[i] != h->cur_pic_ptr)
1074 h->delayed_pic[j++] = h->delayed_pic[i];
1075 h->delayed_pic[j] = NULL;
1078 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
1079 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
1080 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
1081 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
1082 ff_h264_reset_sei(h);
1083 h->recovery_frame = -1;
1084 h->frame_recovered = 0;
1086 h->current_slice = 0;
1090 /* forget old pics after a seek */
1091 static void flush_dpb(AVCodecContext *avctx)
1093 H264Context *h = avctx->priv_data;
1096 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
1097 if (h->delayed_pic[i])
1098 h->delayed_pic[i]->reference = 0;
1099 h->delayed_pic[i] = NULL;
1102 ff_h264_flush_change(h);
1105 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1106 ff_h264_unref_picture(h, &h->DPB[i]);
1107 h->cur_pic_ptr = NULL;
1108 ff_h264_unref_picture(h, &h->cur_pic);
1110 h->mb_x = h->mb_y = 0;
1112 h->parse_context.state = -1;
1113 h->parse_context.frame_start_found = 0;
1114 h->parse_context.overread = 0;
1115 h->parse_context.overread_index = 0;
1116 h->parse_context.index = 0;
1117 h->parse_context.last_index = 0;
1119 ff_h264_free_tables(h, 1);
1120 h->context_initialized = 0;
1123 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1125 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1128 h->frame_num_offset = h->prev_frame_num_offset;
1129 if (h->frame_num < h->prev_frame_num)
1130 h->frame_num_offset += max_frame_num;
1132 if (h->sps.poc_type == 0) {
1133 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1135 if (h->poc_lsb < h->prev_poc_lsb &&
1136 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1137 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1138 else if (h->poc_lsb > h->prev_poc_lsb &&
1139 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1140 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1142 h->poc_msb = h->prev_poc_msb;
1144 field_poc[1] = h->poc_msb + h->poc_lsb;
1145 if (h->picture_structure == PICT_FRAME)
1146 field_poc[1] += h->delta_poc_bottom;
1147 } else if (h->sps.poc_type == 1) {
1148 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1151 if (h->sps.poc_cycle_length != 0)
1152 abs_frame_num = h->frame_num_offset + h->frame_num;
1156 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1159 expected_delta_per_poc_cycle = 0;
1160 for (i = 0; i < h->sps.poc_cycle_length; i++)
1161 // FIXME integrate during sps parse
1162 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1164 if (abs_frame_num > 0) {
1165 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1166 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1168 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1169 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1170 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1174 if (h->nal_ref_idc == 0)
1175 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1177 field_poc[0] = expectedpoc + h->delta_poc[0];
1178 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1180 if (h->picture_structure == PICT_FRAME)
1181 field_poc[1] += h->delta_poc[1];
1183 int poc = 2 * (h->frame_num_offset + h->frame_num);
1185 if (!h->nal_ref_idc)
1192 if (h->picture_structure != PICT_BOTTOM_FIELD)
1193 pic_field_poc[0] = field_poc[0];
1194 if (h->picture_structure != PICT_TOP_FIELD)
1195 pic_field_poc[1] = field_poc[1];
1196 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1202 * Compute profile from profile_idc and constraint_set?_flags.
1206 * @return profile as defined by FF_PROFILE_H264_*
1208 int ff_h264_get_profile(SPS *sps)
1210 int profile = sps->profile_idc;
1212 switch (sps->profile_idc) {
1213 case FF_PROFILE_H264_BASELINE:
1214 // constraint_set1_flag set to 1
1215 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1217 case FF_PROFILE_H264_HIGH_10:
1218 case FF_PROFILE_H264_HIGH_422:
1219 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1220 // constraint_set3_flag set to 1
1221 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1228 int ff_h264_set_parameter_from_sps(H264Context *h)
1230 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1231 (h->sps.bitstream_restriction_flag &&
1232 !h->sps.num_reorder_frames)) {
1233 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1234 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1235 "Reenabling low delay requires a codec flush.\n");
1240 if (h->avctx->has_b_frames < 2)
1241 h->avctx->has_b_frames = !h->low_delay;
1243 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1244 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1245 if (h->avctx->codec &&
1246 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
1247 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
1248 av_log(h->avctx, AV_LOG_ERROR,
1249 "VDPAU decoding does not support video colorspace.\n");
1250 return AVERROR_INVALIDDATA;
1252 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
1253 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
1254 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1255 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1256 h->pixel_shift = h->sps.bit_depth_luma > 8;
1258 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1259 h->sps.chroma_format_idc);
1260 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1261 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1262 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1263 h->sps.chroma_format_idc);
1265 if (CONFIG_ERROR_RESILIENCE)
1266 ff_dsputil_init(&h->dsp, h->avctx);
1267 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1269 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1270 h->sps.bit_depth_luma);
1271 return AVERROR_INVALIDDATA;
1277 int ff_set_ref_count(H264Context *h)
1279 int ref_count[2], list_count;
1280 int num_ref_idx_active_override_flag;
1282 // set defaults, might be overridden a few lines later
1283 ref_count[0] = h->pps.ref_count[0];
1284 ref_count[1] = h->pps.ref_count[1];
1286 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1288 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1290 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1291 h->direct_spatial_mv_pred = get_bits1(&h->gb);
1292 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1294 if (num_ref_idx_active_override_flag) {
1295 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1296 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1297 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1299 // full range is spec-ok in this case, even for frames
1303 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1304 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]);
1305 h->ref_count[0] = h->ref_count[1] = 0;
1307 return AVERROR_INVALIDDATA;
1310 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1316 ref_count[0] = ref_count[1] = 0;
1319 if (list_count != h->list_count ||
1320 ref_count[0] != h->ref_count[0] ||
1321 ref_count[1] != h->ref_count[1]) {
1322 h->ref_count[0] = ref_count[0];
1323 h->ref_count[1] = ref_count[1];
1324 h->list_count = list_count;
1331 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1333 static int find_start_code(const uint8_t *buf, int buf_size,
1334 int buf_index, int next_avc)
1336 // start code prefix search
1337 for (; buf_index + 3 < next_avc; buf_index++)
1338 // This should always succeed in the first iteration.
1339 if (buf[buf_index] == 0 &&
1340 buf[buf_index + 1] == 0 &&
1341 buf[buf_index + 2] == 1)
1346 if (buf_index >= buf_size)
1352 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1353 int buf_size, int *buf_index)
1357 if (*buf_index >= buf_size - h->nal_length_size)
1360 for (i = 0; i < h->nal_length_size; i++)
1361 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1362 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1363 av_log(h->avctx, AV_LOG_ERROR,
1364 "AVC: nal size %d\n", nalsize);
1370 static int get_bit_length(H264Context *h, const uint8_t *buf,
1371 const uint8_t *ptr, int dst_length,
1372 int i, int next_avc)
1374 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1375 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1376 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1377 h->workaround_bugs |= FF_BUG_TRUNCATED;
1379 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1380 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1386 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1389 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1391 int next_avc = h->is_avc ? 0 : buf_size;
1394 int nals_needed = 0;
1395 int first_slice = 0;
1399 int dst_length, bit_length, consumed;
1402 if (buf_index >= next_avc) {
1403 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1406 next_avc = buf_index + nalsize;
1408 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1409 if (buf_index >= buf_size)
1411 if (buf_index >= next_avc)
1415 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1416 next_avc - buf_index);
1418 if (ptr == NULL || dst_length < 0)
1419 return AVERROR_INVALIDDATA;
1421 buf_index += consumed;
1423 bit_length = get_bit_length(h, buf, ptr, dst_length,
1424 buf_index, next_avc);
1427 /* packets can sometimes contain multiple PPS/SPS,
1428 * e.g. two PAFF field pictures in one packet, or a demuxer
1429 * which splits NALs strangely if so, when frame threading we
1430 * can't start the next thread until we've read all of them */
1431 switch (h->nal_unit_type) {
1434 nals_needed = nal_index;
1439 init_get_bits(&h->gb, ptr, bit_length);
1440 if (!get_ue_golomb(&h->gb) ||
1442 first_slice != h->nal_unit_type)
1443 nals_needed = nal_index;
1445 first_slice = h->nal_unit_type;
1452 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1453 int parse_extradata)
1455 AVCodecContext *const avctx = h->avctx;
1456 H264Context *hx; ///< thread context
1458 unsigned context_count;
1460 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1465 h->nal_unit_type= 0;
1467 if(!h->slice_context_count)
1468 h->slice_context_count= 1;
1469 h->max_contexts = h->slice_context_count;
1470 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1471 h->current_slice = 0;
1472 if (!h->first_field)
1473 h->cur_pic_ptr = NULL;
1474 ff_h264_reset_sei(h);
1477 if (h->nal_length_size == 4) {
1478 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1480 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1484 if (avctx->active_thread_type & FF_THREAD_FRAME)
1485 nals_needed = get_last_needed_nal(h, buf, buf_size);
1490 next_avc = h->is_avc ? 0 : buf_size;
1500 if (buf_index >= next_avc) {
1501 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1504 next_avc = buf_index + nalsize;
1506 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1507 if (buf_index >= buf_size)
1509 if (buf_index >= next_avc)
1513 hx = h->thread_context[context_count];
1515 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1516 &consumed, next_avc - buf_index);
1517 if (ptr == NULL || dst_length < 0) {
1522 bit_length = get_bit_length(h, buf, ptr, dst_length,
1523 buf_index + consumed, next_avc);
1525 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1526 av_log(h->avctx, AV_LOG_DEBUG,
1527 "NAL %d/%d at %d/%d length %d\n",
1528 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
1530 if (h->is_avc && (nalsize != consumed) && nalsize)
1531 av_log(h->avctx, AV_LOG_DEBUG,
1532 "AVC: Consumed only %d bytes instead of %d\n",
1535 buf_index += consumed;
1538 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1539 h->nal_ref_idc == 0 &&
1540 h->nal_unit_type != NAL_SEI)
1544 if ( !(avctx->active_thread_type & FF_THREAD_FRAME)
1545 || nals_needed >= nal_index)
1547 /* Ignore per frame NAL unit type during extradata
1548 * parsing. Decoding slices is not possible in codec init
1550 if (parse_extradata) {
1551 switch (hx->nal_unit_type) {
1557 av_log(h->avctx, AV_LOG_WARNING,
1558 "Ignoring NAL %d in global header/extradata\n",
1560 // fall through to next case
1561 case NAL_AUXILIARY_SLICE:
1562 hx->nal_unit_type = NAL_FF_IGNORE;
1568 switch (hx->nal_unit_type) {
1570 if (h->nal_unit_type != NAL_IDR_SLICE) {
1571 av_log(h->avctx, AV_LOG_ERROR,
1572 "Invalid mix of idr and non-idr slices\n");
1577 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1579 h->has_recovery_point = 1;
1581 init_get_bits(&hx->gb, ptr, bit_length);
1583 hx->inter_gb_ptr = &hx->gb;
1584 hx->data_partitioning = 0;
1586 if ((err = ff_h264_decode_slice_header(hx, h)))
1589 if (h->sei_recovery_frame_cnt >= 0) {
1590 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
1591 h->valid_recovery_point = 1;
1593 if ( h->recovery_frame < 0
1594 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
1595 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1596 ((1 << h->sps.log2_max_frame_num) - 1);
1598 if (!h->valid_recovery_point)
1599 h->recovery_frame = h->frame_num;
1603 h->cur_pic_ptr->f.key_frame |=
1604 (hx->nal_unit_type == NAL_IDR_SLICE);
1606 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1607 h->recovery_frame == h->frame_num) {
1608 h->recovery_frame = -1;
1609 h->cur_pic_ptr->recovered = 1;
1611 // If we have an IDR, all frames after it in decoded order are
1613 if (hx->nal_unit_type == NAL_IDR_SLICE)
1614 h->frame_recovered |= FRAME_RECOVERED_IDR;
1615 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1616 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1618 h->cur_pic_ptr->recovered |= h->frame_recovered;
1620 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1623 if (h->current_slice == 1) {
1624 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1625 decode_postinit(h, nal_index >= nals_needed);
1627 if (h->avctx->hwaccel &&
1628 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1630 if (CONFIG_H264_VDPAU_DECODER &&
1631 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
1632 ff_vdpau_h264_picture_start(h);
1635 if (hx->redundant_pic_count == 0) {
1636 if (avctx->hwaccel) {
1637 ret = avctx->hwaccel->decode_slice(avctx,
1638 &buf[buf_index - consumed],
1642 } else if (CONFIG_H264_VDPAU_DECODER &&
1643 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
1644 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1646 sizeof(start_code));
1647 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1648 &buf[buf_index - consumed],
1655 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
1656 av_log(h->avctx, AV_LOG_ERROR,
1657 "Decoding in chunks is not supported for "
1658 "partitioned slices.\n");
1659 return AVERROR(ENOSYS);
1662 init_get_bits(&hx->gb, ptr, bit_length);
1664 hx->inter_gb_ptr = NULL;
1666 if ((err = ff_h264_decode_slice_header(hx, h))) {
1667 /* make sure data_partitioning is cleared if it was set
1668 * before, so we don't try decoding a slice without a valid
1669 * slice header later */
1670 h->data_partitioning = 0;
1674 hx->data_partitioning = 1;
1677 init_get_bits(&hx->intra_gb, ptr, bit_length);
1678 hx->intra_gb_ptr = &hx->intra_gb;
1681 init_get_bits(&hx->inter_gb, ptr, bit_length);
1682 hx->inter_gb_ptr = &hx->inter_gb;
1684 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
1687 if (hx->redundant_pic_count == 0 &&
1689 hx->data_partitioning &&
1690 h->cur_pic_ptr && h->context_initialized &&
1691 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
1692 (avctx->skip_frame < AVDISCARD_BIDIR ||
1693 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1694 (avctx->skip_frame < AVDISCARD_NONINTRA ||
1695 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1696 avctx->skip_frame < AVDISCARD_ALL)
1700 init_get_bits(&h->gb, ptr, bit_length);
1701 ret = ff_h264_decode_sei(h);
1702 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1706 init_get_bits(&h->gb, ptr, bit_length);
1707 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
1708 av_log(h->avctx, AV_LOG_DEBUG,
1709 "SPS decoding failure, trying again with the complete NAL\n");
1711 av_assert0(next_avc - buf_index + consumed == nalsize);
1712 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1714 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1715 8*(next_avc - buf_index + consumed - 1));
1716 ff_h264_decode_seq_parameter_set(h);
1721 init_get_bits(&h->gb, ptr, bit_length);
1722 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1723 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1727 case NAL_END_SEQUENCE:
1728 case NAL_END_STREAM:
1729 case NAL_FILLER_DATA:
1731 case NAL_AUXILIARY_SLICE:
1736 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1737 hx->nal_unit_type, bit_length);
1740 if (context_count == h->max_contexts) {
1741 ret = ff_h264_execute_decode_slices(h, context_count);
1742 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1747 if (err < 0 || err == SLICE_SKIPED) {
1749 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1750 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1751 } else if (err == SLICE_SINGLETHREAD) {
1752 /* Slice could not be decoded in parallel mode, copy down
1753 * NAL unit stuff to context 0 and restart. Note that
1754 * rbsp_buffer is not transferred, but since we no longer
1755 * run in parallel mode this should not be an issue. */
1756 h->nal_unit_type = hx->nal_unit_type;
1757 h->nal_ref_idc = hx->nal_ref_idc;
1763 if (context_count) {
1764 ret = ff_h264_execute_decode_slices(h, context_count);
1765 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1772 if (h->cur_pic_ptr && !h->droppable) {
1773 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1774 h->picture_structure == PICT_BOTTOM_FIELD);
1777 return (ret < 0) ? ret : buf_index;
1781 * Return the number of bytes consumed for building the current frame.
1783 static int get_consumed_bytes(int pos, int buf_size)
1786 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
1787 if (pos + 10 > buf_size)
1788 pos = buf_size; // oops ;)
1793 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1795 AVFrame *src = &srcp->f;
1796 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1798 int ret = av_frame_ref(dst, src);
1802 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1804 if (srcp->sei_recovery_frame_cnt == 0)
1809 for (i = 0; i < desc->nb_components; i++) {
1810 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1811 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1812 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1813 (srcp->crop_top >> vshift) * dst->linesize[i];
1814 dst->data[i] += off;
1819 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1820 int *got_frame, AVPacket *avpkt)
1822 const uint8_t *buf = avpkt->data;
1823 int buf_size = avpkt->size;
1824 H264Context *h = avctx->priv_data;
1825 AVFrame *pict = data;
1831 h->flags = avctx->flags;
1832 /* reset data partitioning here, to ensure GetBitContexts from previous
1833 * packets do not get used. */
1834 h->data_partitioning = 0;
1836 /* end of stream, output what is still in the buffers */
1837 if (buf_size == 0) {
1840 h->cur_pic_ptr = NULL;
1843 // FIXME factorize this with the output code below
1844 out = h->delayed_pic[0];
1847 h->delayed_pic[i] &&
1848 !h->delayed_pic[i]->f.key_frame &&
1849 !h->delayed_pic[i]->mmco_reset;
1851 if (h->delayed_pic[i]->poc < out->poc) {
1852 out = h->delayed_pic[i];
1856 for (i = out_idx; h->delayed_pic[i]; i++)
1857 h->delayed_pic[i] = h->delayed_pic[i + 1];
1860 out->reference &= ~DELAYED_PIC_REF;
1861 ret = output_frame(h, pict, out);
1869 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1870 int cnt= buf[5]&0x1f;
1871 const uint8_t *p= buf+6;
1873 int nalsize= AV_RB16(p) + 2;
1874 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1882 int nalsize= AV_RB16(p) + 2;
1883 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1888 return ff_h264_decode_extradata(h, buf, buf_size);
1892 buf_index = decode_nal_units(h, buf, buf_size, 0);
1894 return AVERROR_INVALIDDATA;
1896 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1897 av_assert0(buf_index <= buf_size);
1901 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1902 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1903 buf_size >= 4 && !memcmp("Q264", buf, 4))
1905 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1906 return AVERROR_INVALIDDATA;
1909 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1910 (h->mb_y >= h->mb_height && h->mb_height)) {
1911 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1912 decode_postinit(h, 1);
1914 ff_h264_field_end(h, 0);
1916 /* Wait for second field. */
1918 if (h->next_output_pic && (
1919 h->next_output_pic->recovered)) {
1920 if (!h->next_output_pic->recovered)
1921 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1923 ret = output_frame(h, pict, h->next_output_pic);
1927 if (CONFIG_MPEGVIDEO) {
1928 ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,
1929 h->next_output_pic->mb_type,
1930 h->next_output_pic->qscale_table,
1931 h->next_output_pic->motion_val,
1933 h->mb_width, h->mb_height, h->mb_stride, 1);
1938 assert(pict->buf[0] || !*got_frame);
1940 return get_consumed_bytes(buf_index, buf_size);
1943 av_cold void ff_h264_free_context(H264Context *h)
1947 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1949 for (i = 0; i < MAX_SPS_COUNT; i++)
1950 av_freep(h->sps_buffers + i);
1952 for (i = 0; i < MAX_PPS_COUNT; i++)
1953 av_freep(h->pps_buffers + i);
1956 static av_cold int h264_decode_end(AVCodecContext *avctx)
1958 H264Context *h = avctx->priv_data;
1960 ff_h264_remove_all_refs(h);
1961 ff_h264_free_context(h);
1963 ff_h264_unref_picture(h, &h->cur_pic);
1968 static const AVProfile profiles[] = {
1969 { FF_PROFILE_H264_BASELINE, "Baseline" },
1970 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1971 { FF_PROFILE_H264_MAIN, "Main" },
1972 { FF_PROFILE_H264_EXTENDED, "Extended" },
1973 { FF_PROFILE_H264_HIGH, "High" },
1974 { FF_PROFILE_H264_HIGH_10, "High 10" },
1975 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1976 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1977 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1978 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1979 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1980 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1981 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1982 { FF_PROFILE_UNKNOWN },
1985 static const AVOption h264_options[] = {
1986 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1987 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1991 static const AVClass h264_class = {
1992 .class_name = "H264 Decoder",
1993 .item_name = av_default_item_name,
1994 .option = h264_options,
1995 .version = LIBAVUTIL_VERSION_INT,
1998 static const AVClass h264_vdpau_class = {
1999 .class_name = "H264 VDPAU Decoder",
2000 .item_name = av_default_item_name,
2001 .option = h264_options,
2002 .version = LIBAVUTIL_VERSION_INT,
2005 AVCodec ff_h264_decoder = {
2007 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
2008 .type = AVMEDIA_TYPE_VIDEO,
2009 .id = AV_CODEC_ID_H264,
2010 .priv_data_size = sizeof(H264Context),
2011 .init = ff_h264_decode_init,
2012 .close = h264_decode_end,
2013 .decode = h264_decode_frame,
2014 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
2015 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
2016 CODEC_CAP_FRAME_THREADS,
2018 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
2019 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
2020 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2021 .priv_class = &h264_class,
2024 #if CONFIG_H264_VDPAU_DECODER
2025 AVCodec ff_h264_vdpau_decoder = {
2026 .name = "h264_vdpau",
2027 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
2028 .type = AVMEDIA_TYPE_VIDEO,
2029 .id = AV_CODEC_ID_H264,
2030 .priv_data_size = sizeof(H264Context),
2031 .init = ff_h264_decode_init,
2032 .close = h264_decode_end,
2033 .decode = h264_decode_frame,
2034 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2036 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2038 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2039 .priv_class = &h264_vdpau_class,