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/imgutils.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/stereo3d.h"
34 #include "libavutil/timer.h"
37 #include "cabac_functions.h"
39 #include "error_resilience.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
47 #include "mpegutils.h"
48 #include "rectangle.h"
51 #include "vdpau_internal.h"
55 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
57 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
59 H264Context *h = avctx->priv_data;
60 return h ? h->sps.num_reorder_frames : 0;
63 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
65 int mb_x, int mb_y, int mb_intra, int mb_skipped)
67 H264Context *h = opaque;
71 h->mb_xy = mb_x + mb_y * h->mb_stride;
72 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
74 /* FIXME: It is possible albeit uncommon that slice references
75 * differ between slices. We take the easy approach and ignore
76 * it for now. If this turns out to have any relevance in
77 * practice then correct remapping should be added. */
78 if (ref >= h->ref_count[0])
80 if (!h->ref_list[0][ref].f.data[0]) {
81 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
84 if ((h->ref_list[0][ref].reference&3) != 3) {
85 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
88 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
90 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
91 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
92 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
94 h->mb_field_decoding_flag = 0;
95 ff_h264_hl_decode_mb(h);
98 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
100 AVCodecContext *avctx = h->avctx;
101 AVFrame *cur = &h->cur_pic.f;
102 AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
103 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
104 int vshift = desc->log2_chroma_h;
105 const int field_pic = h->picture_structure != PICT_FRAME;
111 height = FFMIN(height, avctx->height - y);
113 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
116 if (avctx->draw_horiz_band) {
118 int offset[AV_NUM_DATA_POINTERS];
121 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
122 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
129 offset[0] = y * src->linesize[0];
131 offset[2] = (y >> vshift) * src->linesize[1];
132 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
137 avctx->draw_horiz_band(avctx, src, offset,
138 y, h->picture_structure, height);
143 * Check if the top & left blocks are available if needed and
144 * change the dc mode so it only uses the available blocks.
146 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
148 static const int8_t top[12] = {
149 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
151 static const int8_t left[12] = {
152 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
156 if (!(h->top_samples_available & 0x8000)) {
157 for (i = 0; i < 4; i++) {
158 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
160 av_log(h->avctx, AV_LOG_ERROR,
161 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
162 status, h->mb_x, h->mb_y);
163 return AVERROR_INVALIDDATA;
165 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
170 if ((h->left_samples_available & 0x8888) != 0x8888) {
171 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
172 for (i = 0; i < 4; i++)
173 if (!(h->left_samples_available & mask[i])) {
174 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
176 av_log(h->avctx, AV_LOG_ERROR,
177 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
178 status, h->mb_x, h->mb_y);
179 return AVERROR_INVALIDDATA;
181 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
187 } // FIXME cleanup like ff_h264_check_intra_pred_mode
190 * Check if the top & left blocks are available if needed and
191 * change the dc mode so it only uses the available blocks.
193 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
195 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
196 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
199 av_log(h->avctx, AV_LOG_ERROR,
200 "out of range intra chroma pred mode at %d %d\n",
202 return AVERROR_INVALIDDATA;
205 if (!(h->top_samples_available & 0x8000)) {
208 av_log(h->avctx, AV_LOG_ERROR,
209 "top block unavailable for requested intra mode at %d %d\n",
211 return AVERROR_INVALIDDATA;
215 if ((h->left_samples_available & 0x8080) != 0x8080) {
217 if (is_chroma && (h->left_samples_available & 0x8080)) {
218 // mad cow disease mode, aka MBAFF + constrained_intra_pred
219 mode = ALZHEIMER_DC_L0T_PRED8x8 +
220 (!(h->left_samples_available & 0x8000)) +
221 2 * (mode == DC_128_PRED8x8);
224 av_log(h->avctx, AV_LOG_ERROR,
225 "left block unavailable for requested intra mode at %d %d\n",
227 return AVERROR_INVALIDDATA;
234 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
235 int *dst_length, int *consumed, int length)
241 // src[0]&0x80; // forbidden bit
242 h->nal_ref_idc = src[0] >> 5;
243 h->nal_unit_type = src[0] & 0x1F;
248 #define STARTCODE_TEST \
249 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
250 if (src[i + 2] != 3) { \
251 /* startcode, so we must be past the end */ \
257 #if HAVE_FAST_UNALIGNED
258 #define FIND_FIRST_ZERO \
259 if (i > 0 && !src[i]) \
265 for (i = 0; i + 1 < length; i += 9) {
266 if (!((~AV_RN64A(src + i) &
267 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
268 0x8000800080008080ULL))
275 for (i = 0; i + 1 < length; i += 5) {
276 if (!((~AV_RN32A(src + i) &
277 (AV_RN32A(src + i) - 0x01000101U)) &
286 for (i = 0; i + 1 < length; i += 2) {
289 if (i > 0 && src[i - 1] == 0)
295 // use second escape buffer for inter data
296 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
298 si = h->rbsp_buffer_size[bufidx];
299 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
300 dst = h->rbsp_buffer[bufidx];
305 if(i>=length-1){ //no escaped 0
307 *consumed= length+1; //+1 for the header
308 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
311 memcpy(dst, src, length);
318 while (si + 2 < length) {
319 // remove escapes (very rare 1:2^22)
320 if (src[si + 2] > 3) {
321 dst[di++] = src[si++];
322 dst[di++] = src[si++];
323 } else if (src[si] == 0 && src[si + 1] == 0) {
324 if (src[si + 2] == 3) { // escape
329 } else // next start code
333 dst[di++] = src[si++];
336 dst[di++] = src[si++];
339 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
342 *consumed = si + 1; // +1 for the header
343 /* FIXME store exact number of bits in the getbitcontext
344 * (it is needed for decoding) */
349 * Identify the exact end of the bitstream
350 * @return the length of the trailing, or 0 if damaged
352 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
357 tprintf(h->avctx, "rbsp trailing %X\n", v);
359 for (r = 1; r < 9; r++) {
367 void ff_h264_free_tables(H264Context *h, int free_rbsp)
372 av_freep(&h->intra4x4_pred_mode);
373 av_freep(&h->chroma_pred_mode_table);
374 av_freep(&h->cbp_table);
375 av_freep(&h->mvd_table[0]);
376 av_freep(&h->mvd_table[1]);
377 av_freep(&h->direct_table);
378 av_freep(&h->non_zero_count);
379 av_freep(&h->slice_table_base);
380 h->slice_table = NULL;
381 av_freep(&h->list_counts);
383 av_freep(&h->mb2b_xy);
384 av_freep(&h->mb2br_xy);
386 av_buffer_pool_uninit(&h->qscale_table_pool);
387 av_buffer_pool_uninit(&h->mb_type_pool);
388 av_buffer_pool_uninit(&h->motion_val_pool);
389 av_buffer_pool_uninit(&h->ref_index_pool);
391 if (free_rbsp && h->DPB) {
392 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
393 ff_h264_unref_picture(h, &h->DPB[i]);
396 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
397 h->DPB[i].needs_realloc = 1;
400 h->cur_pic_ptr = NULL;
402 for (i = 0; i < H264_MAX_THREADS; i++) {
403 hx = h->thread_context[i];
406 av_freep(&hx->top_borders[1]);
407 av_freep(&hx->top_borders[0]);
408 av_freep(&hx->bipred_scratchpad);
409 av_freep(&hx->edge_emu_buffer);
410 av_freep(&hx->dc_val_base);
411 av_freep(&hx->er.mb_index2xy);
412 av_freep(&hx->er.error_status_table);
413 av_freep(&hx->er.er_temp_buffer);
414 av_freep(&hx->er.mbintra_table);
415 av_freep(&hx->er.mbskip_table);
418 av_freep(&hx->rbsp_buffer[1]);
419 av_freep(&hx->rbsp_buffer[0]);
420 hx->rbsp_buffer_size[0] = 0;
421 hx->rbsp_buffer_size[1] = 0;
424 av_freep(&h->thread_context[i]);
428 int ff_h264_alloc_tables(H264Context *h)
430 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
431 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
434 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
435 row_mb_num * 8 * sizeof(uint8_t), fail)
436 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
437 big_mb_num * 48 * sizeof(uint8_t), fail)
438 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
439 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
440 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
441 big_mb_num * sizeof(uint16_t), fail)
442 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
443 big_mb_num * sizeof(uint8_t), fail)
444 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
445 16 * row_mb_num * sizeof(uint8_t), fail);
446 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
447 16 * row_mb_num * sizeof(uint8_t), fail);
448 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
449 4 * big_mb_num * sizeof(uint8_t), fail);
450 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
451 big_mb_num * sizeof(uint8_t), fail)
453 memset(h->slice_table_base, -1,
454 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
455 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
457 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
458 big_mb_num * sizeof(uint32_t), fail);
459 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
460 big_mb_num * sizeof(uint32_t), fail);
461 for (y = 0; y < h->mb_height; y++)
462 for (x = 0; x < h->mb_width; x++) {
463 const int mb_xy = x + y * h->mb_stride;
464 const int b_xy = 4 * x + 4 * y * h->b_stride;
466 h->mb2b_xy[mb_xy] = b_xy;
467 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
470 if (!h->dequant4_coeff[0])
471 h264_init_dequant_tables(h);
474 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
476 return AVERROR(ENOMEM);
477 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
478 av_frame_unref(&h->DPB[i].f);
479 av_frame_unref(&h->cur_pic.f);
485 ff_h264_free_tables(h, 1);
486 return AVERROR(ENOMEM);
491 * Allocate buffers which are not shared amongst multiple threads.
493 int ff_h264_context_init(H264Context *h)
495 ERContext *er = &h->er;
496 int mb_array_size = h->mb_height * h->mb_stride;
497 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
498 int c_size = h->mb_stride * (h->mb_height + 1);
499 int yc_size = y_size + 2 * c_size;
502 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
503 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
504 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
505 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
507 h->ref_cache[0][scan8[5] + 1] =
508 h->ref_cache[0][scan8[7] + 1] =
509 h->ref_cache[0][scan8[13] + 1] =
510 h->ref_cache[1][scan8[5] + 1] =
511 h->ref_cache[1][scan8[7] + 1] =
512 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
514 if (CONFIG_ERROR_RESILIENCE) {
516 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 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
529 fail); // error ressilience code looks cleaner with this
530 for (y = 0; y < h->mb_height; y++)
531 for (x = 0; x < h->mb_width; x++)
532 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
534 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
535 h->mb_stride + h->mb_width;
537 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
538 mb_array_size * sizeof(uint8_t), fail);
540 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
541 memset(er->mbintra_table, 1, mb_array_size);
543 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
545 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
548 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
549 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
550 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
551 er->dc_val[2] = er->dc_val[1] + c_size;
552 for (i = 0; i < yc_size; i++)
553 h->dc_val_base[i] = 1024;
559 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
562 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
563 int parse_extradata);
565 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
567 AVCodecContext *avctx = h->avctx;
570 if (!buf || size <= 0)
575 const unsigned char *p = buf;
580 av_log(avctx, AV_LOG_ERROR,
581 "avcC %d too short\n", size);
582 return AVERROR_INVALIDDATA;
584 /* sps and pps in the avcC always have length coded with 2 bytes,
585 * so put a fake nal_length_size = 2 while parsing them */
586 h->nal_length_size = 2;
587 // Decode sps from avcC
588 cnt = *(p + 5) & 0x1f; // Number of sps
590 for (i = 0; i < cnt; i++) {
591 nalsize = AV_RB16(p) + 2;
592 if(nalsize > size - (p-buf))
593 return AVERROR_INVALIDDATA;
594 ret = decode_nal_units(h, p, nalsize, 1);
596 av_log(avctx, AV_LOG_ERROR,
597 "Decoding sps %d from avcC failed\n", i);
602 // Decode pps from avcC
603 cnt = *(p++); // Number of pps
604 for (i = 0; i < cnt; i++) {
605 nalsize = AV_RB16(p) + 2;
606 if(nalsize > size - (p-buf))
607 return AVERROR_INVALIDDATA;
608 ret = decode_nal_units(h, p, nalsize, 1);
610 av_log(avctx, AV_LOG_ERROR,
611 "Decoding pps %d from avcC failed\n", i);
616 // Now store right nal length size, that will be used to parse all other nals
617 h->nal_length_size = (buf[4] & 0x03) + 1;
620 ret = decode_nal_units(h, buf, size, 1);
627 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
629 H264Context *h = avctx->priv_data;
635 h->bit_depth_luma = 8;
636 h->chroma_format_idc = 1;
638 h->avctx->bits_per_raw_sample = 8;
639 h->cur_chroma_format_idc = 1;
641 ff_h264dsp_init(&h->h264dsp, 8, 1);
642 av_assert0(h->sps.bit_depth_chroma == 0);
643 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
644 ff_h264qpel_init(&h->h264qpel, 8);
645 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
647 h->dequant_coeff_pps = -1;
648 h->current_sps_id = -1;
650 /* needed so that IDCT permutation is known early */
651 if (CONFIG_ERROR_RESILIENCE)
652 ff_dsputil_init(&h->dsp, h->avctx);
653 ff_videodsp_init(&h->vdsp, 8);
655 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
656 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
658 h->picture_structure = PICT_FRAME;
659 h->slice_context_count = 1;
660 h->workaround_bugs = avctx->workaround_bugs;
661 h->flags = avctx->flags;
664 // s->decode_mb = ff_h263_decode_mb;
665 if (!avctx->has_b_frames)
668 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
670 ff_h264_decode_init_vlc();
672 ff_init_cabac_states();
675 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
677 h->thread_context[0] = h;
678 h->outputed_poc = h->next_outputed_poc = INT_MIN;
679 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
680 h->last_pocs[i] = INT_MIN;
681 h->prev_poc_msb = 1 << 16;
682 h->prev_frame_num = -1;
684 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
685 ff_h264_reset_sei(h);
686 if (avctx->codec_id == AV_CODEC_ID_H264) {
687 if (avctx->ticks_per_frame == 1) {
688 if(h->avctx->time_base.den < INT_MAX/2) {
689 h->avctx->time_base.den *= 2;
691 h->avctx->time_base.num /= 2;
693 avctx->ticks_per_frame = 2;
696 if (avctx->extradata_size > 0 && avctx->extradata) {
697 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
699 ff_h264_free_context(h);
704 if (h->sps.bitstream_restriction_flag &&
705 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
706 h->avctx->has_b_frames = h->sps.num_reorder_frames;
710 avctx->internal->allocate_progress = 1;
712 ff_h264_flush_change(h);
717 static int decode_init_thread_copy(AVCodecContext *avctx)
719 H264Context *h = avctx->priv_data;
721 if (!avctx->internal->is_copy)
723 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
724 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
726 h->rbsp_buffer[0] = NULL;
727 h->rbsp_buffer[1] = NULL;
728 h->rbsp_buffer_size[0] = 0;
729 h->rbsp_buffer_size[1] = 0;
730 h->context_initialized = 0;
736 * Run setup operations that must be run after slice header decoding.
737 * This includes finding the next displayed frame.
739 * @param h h264 master context
740 * @param setup_finished enough NALs have been read that we can call
741 * ff_thread_finish_setup()
743 static void decode_postinit(H264Context *h, int setup_finished)
745 H264Picture *out = h->cur_pic_ptr;
746 H264Picture *cur = h->cur_pic_ptr;
747 int i, pics, out_of_order, out_idx;
749 h->cur_pic_ptr->f.pict_type = h->pict_type;
751 if (h->next_output_pic)
754 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
755 /* FIXME: if we have two PAFF fields in one packet, we can't start
756 * the next thread here. If we have one field per packet, we can.
757 * The check in decode_nal_units() is not good enough to find this
758 * yet, so we assume the worst for now. */
759 // if (setup_finished)
760 // ff_thread_finish_setup(h->avctx);
764 cur->f.interlaced_frame = 0;
765 cur->f.repeat_pict = 0;
767 /* Signal interlacing information externally. */
768 /* Prioritize picture timing SEI information over used
769 * decoding process if it exists. */
771 if (h->sps.pic_struct_present_flag) {
772 switch (h->sei_pic_struct) {
773 case SEI_PIC_STRUCT_FRAME:
775 case SEI_PIC_STRUCT_TOP_FIELD:
776 case SEI_PIC_STRUCT_BOTTOM_FIELD:
777 cur->f.interlaced_frame = 1;
779 case SEI_PIC_STRUCT_TOP_BOTTOM:
780 case SEI_PIC_STRUCT_BOTTOM_TOP:
781 if (FIELD_OR_MBAFF_PICTURE(h))
782 cur->f.interlaced_frame = 1;
784 // try to flag soft telecine progressive
785 cur->f.interlaced_frame = h->prev_interlaced_frame;
787 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
788 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
789 /* Signal the possibility of telecined film externally
790 * (pic_struct 5,6). From these hints, let the applications
791 * decide if they apply deinterlacing. */
792 cur->f.repeat_pict = 1;
794 case SEI_PIC_STRUCT_FRAME_DOUBLING:
795 cur->f.repeat_pict = 2;
797 case SEI_PIC_STRUCT_FRAME_TRIPLING:
798 cur->f.repeat_pict = 4;
802 if ((h->sei_ct_type & 3) &&
803 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
804 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
806 /* Derive interlacing flag from used decoding process. */
807 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
809 h->prev_interlaced_frame = cur->f.interlaced_frame;
811 if (cur->field_poc[0] != cur->field_poc[1]) {
812 /* Derive top_field_first from field pocs. */
813 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
815 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
816 /* Use picture timing SEI information. Even if it is a
817 * information of a past frame, better than nothing. */
818 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
819 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
820 cur->f.top_field_first = 1;
822 cur->f.top_field_first = 0;
824 /* Most likely progressive */
825 cur->f.top_field_first = 0;
829 if (h->sei_frame_packing_present &&
830 h->frame_packing_arrangement_type >= 0 &&
831 h->frame_packing_arrangement_type <= 6 &&
832 h->content_interpretation_type > 0 &&
833 h->content_interpretation_type < 3) {
834 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
838 switch (h->frame_packing_arrangement_type) {
840 stereo->type = AV_STEREO3D_CHECKERBOARD;
843 stereo->type = AV_STEREO3D_LINES;
846 stereo->type = AV_STEREO3D_COLUMNS;
849 if (h->quincunx_subsampling)
850 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
852 stereo->type = AV_STEREO3D_SIDEBYSIDE;
855 stereo->type = AV_STEREO3D_TOPBOTTOM;
858 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
861 stereo->type = AV_STEREO3D_2D;
865 if (h->content_interpretation_type == 2)
866 stereo->flags = AV_STEREO3D_FLAG_INVERT;
869 cur->mmco_reset = h->mmco_reset;
872 // FIXME do something with unavailable reference frames
874 /* Sort B-frames into display order */
876 if (h->sps.bitstream_restriction_flag &&
877 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
878 h->avctx->has_b_frames = h->sps.num_reorder_frames;
882 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
883 !h->sps.bitstream_restriction_flag) {
884 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
888 for (i = 0; 1; i++) {
889 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
891 h->last_pocs[i-1] = cur->poc;
894 h->last_pocs[i-1]= h->last_pocs[i];
897 out_of_order = MAX_DELAYED_PIC_COUNT - i;
898 if( cur->f.pict_type == AV_PICTURE_TYPE_B
899 || (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))
900 out_of_order = FFMAX(out_of_order, 1);
901 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
902 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
903 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
904 h->last_pocs[i] = INT_MIN;
905 h->last_pocs[0] = cur->poc;
907 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
908 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
909 h->avctx->has_b_frames = out_of_order;
914 while (h->delayed_pic[pics])
917 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
919 h->delayed_pic[pics++] = cur;
920 if (cur->reference == 0)
921 cur->reference = DELAYED_PIC_REF;
923 out = h->delayed_pic[0];
925 for (i = 1; h->delayed_pic[i] &&
926 !h->delayed_pic[i]->f.key_frame &&
927 !h->delayed_pic[i]->mmco_reset;
929 if (h->delayed_pic[i]->poc < out->poc) {
930 out = h->delayed_pic[i];
933 if (h->avctx->has_b_frames == 0 &&
934 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
935 h->next_outputed_poc = INT_MIN;
936 out_of_order = out->poc < h->next_outputed_poc;
938 if (out_of_order || pics > h->avctx->has_b_frames) {
939 out->reference &= ~DELAYED_PIC_REF;
940 // for frame threading, the owner must be the second field's thread or
941 // else the first thread can release the picture and reuse it unsafely
942 for (i = out_idx; h->delayed_pic[i]; i++)
943 h->delayed_pic[i] = h->delayed_pic[i + 1];
945 if (!out_of_order && pics > h->avctx->has_b_frames) {
946 h->next_output_pic = out;
947 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
948 h->next_outputed_poc = INT_MIN;
950 h->next_outputed_poc = out->poc;
952 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
955 if (h->next_output_pic) {
956 if (h->next_output_pic->recovered) {
957 // We have reached an recovery point and all frames after it in
958 // display order are "recovered".
959 h->frame_recovered |= FRAME_RECOVERED_SEI;
961 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
964 if (setup_finished && !h->avctx->hwaccel)
965 ff_thread_finish_setup(h->avctx);
968 int ff_pred_weight_table(H264Context *h)
971 int luma_def, chroma_def;
974 h->use_weight_chroma = 0;
975 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
976 if (h->sps.chroma_format_idc)
977 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
978 luma_def = 1 << h->luma_log2_weight_denom;
979 chroma_def = 1 << h->chroma_log2_weight_denom;
981 for (list = 0; list < 2; list++) {
982 h->luma_weight_flag[list] = 0;
983 h->chroma_weight_flag[list] = 0;
984 for (i = 0; i < h->ref_count[list]; i++) {
985 int luma_weight_flag, chroma_weight_flag;
987 luma_weight_flag = get_bits1(&h->gb);
988 if (luma_weight_flag) {
989 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
990 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
991 if (h->luma_weight[i][list][0] != luma_def ||
992 h->luma_weight[i][list][1] != 0) {
994 h->luma_weight_flag[list] = 1;
997 h->luma_weight[i][list][0] = luma_def;
998 h->luma_weight[i][list][1] = 0;
1001 if (h->sps.chroma_format_idc) {
1002 chroma_weight_flag = get_bits1(&h->gb);
1003 if (chroma_weight_flag) {
1005 for (j = 0; j < 2; j++) {
1006 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1007 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1008 if (h->chroma_weight[i][list][j][0] != chroma_def ||
1009 h->chroma_weight[i][list][j][1] != 0) {
1010 h->use_weight_chroma = 1;
1011 h->chroma_weight_flag[list] = 1;
1016 for (j = 0; j < 2; j++) {
1017 h->chroma_weight[i][list][j][0] = chroma_def;
1018 h->chroma_weight[i][list][j][1] = 0;
1023 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
1026 h->use_weight = h->use_weight || h->use_weight_chroma;
1031 * instantaneous decoder refresh.
1033 static void idr(H264Context *h)
1036 ff_h264_remove_all_refs(h);
1037 h->prev_frame_num = 0;
1038 h->prev_frame_num_offset = 0;
1039 h->prev_poc_msb = 1<<16;
1040 h->prev_poc_lsb = 0;
1041 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1042 h->last_pocs[i] = INT_MIN;
1045 /* forget old pics after a seek */
1046 void ff_h264_flush_change(H264Context *h)
1050 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1051 h->prev_interlaced_frame = 1;
1054 h->prev_frame_num = -1;
1055 if (h->cur_pic_ptr) {
1056 h->cur_pic_ptr->reference = 0;
1057 for (j=i=0; h->delayed_pic[i]; i++)
1058 if (h->delayed_pic[i] != h->cur_pic_ptr)
1059 h->delayed_pic[j++] = h->delayed_pic[i];
1060 h->delayed_pic[j] = NULL;
1063 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
1064 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
1065 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
1066 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
1067 ff_h264_reset_sei(h);
1068 h->recovery_frame = -1;
1069 h->frame_recovered = 0;
1071 h->current_slice = 0;
1075 /* forget old pics after a seek */
1076 static void flush_dpb(AVCodecContext *avctx)
1078 H264Context *h = avctx->priv_data;
1081 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
1082 if (h->delayed_pic[i])
1083 h->delayed_pic[i]->reference = 0;
1084 h->delayed_pic[i] = NULL;
1087 ff_h264_flush_change(h);
1090 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1091 ff_h264_unref_picture(h, &h->DPB[i]);
1092 h->cur_pic_ptr = NULL;
1093 ff_h264_unref_picture(h, &h->cur_pic);
1095 h->mb_x = h->mb_y = 0;
1097 h->parse_context.state = -1;
1098 h->parse_context.frame_start_found = 0;
1099 h->parse_context.overread = 0;
1100 h->parse_context.overread_index = 0;
1101 h->parse_context.index = 0;
1102 h->parse_context.last_index = 0;
1104 ff_h264_free_tables(h, 1);
1105 h->context_initialized = 0;
1108 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1110 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1113 h->frame_num_offset = h->prev_frame_num_offset;
1114 if (h->frame_num < h->prev_frame_num)
1115 h->frame_num_offset += max_frame_num;
1117 if (h->sps.poc_type == 0) {
1118 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1120 if (h->poc_lsb < h->prev_poc_lsb &&
1121 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1122 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1123 else if (h->poc_lsb > h->prev_poc_lsb &&
1124 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1125 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1127 h->poc_msb = h->prev_poc_msb;
1129 field_poc[1] = h->poc_msb + h->poc_lsb;
1130 if (h->picture_structure == PICT_FRAME)
1131 field_poc[1] += h->delta_poc_bottom;
1132 } else if (h->sps.poc_type == 1) {
1133 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1136 if (h->sps.poc_cycle_length != 0)
1137 abs_frame_num = h->frame_num_offset + h->frame_num;
1141 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1144 expected_delta_per_poc_cycle = 0;
1145 for (i = 0; i < h->sps.poc_cycle_length; i++)
1146 // FIXME integrate during sps parse
1147 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1149 if (abs_frame_num > 0) {
1150 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1151 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1153 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1154 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1155 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1159 if (h->nal_ref_idc == 0)
1160 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1162 field_poc[0] = expectedpoc + h->delta_poc[0];
1163 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1165 if (h->picture_structure == PICT_FRAME)
1166 field_poc[1] += h->delta_poc[1];
1168 int poc = 2 * (h->frame_num_offset + h->frame_num);
1170 if (!h->nal_ref_idc)
1177 if (h->picture_structure != PICT_BOTTOM_FIELD)
1178 pic_field_poc[0] = field_poc[0];
1179 if (h->picture_structure != PICT_TOP_FIELD)
1180 pic_field_poc[1] = field_poc[1];
1181 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1187 * Compute profile from profile_idc and constraint_set?_flags.
1191 * @return profile as defined by FF_PROFILE_H264_*
1193 int ff_h264_get_profile(SPS *sps)
1195 int profile = sps->profile_idc;
1197 switch (sps->profile_idc) {
1198 case FF_PROFILE_H264_BASELINE:
1199 // constraint_set1_flag set to 1
1200 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1202 case FF_PROFILE_H264_HIGH_10:
1203 case FF_PROFILE_H264_HIGH_422:
1204 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1205 // constraint_set3_flag set to 1
1206 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1213 int ff_h264_set_parameter_from_sps(H264Context *h)
1215 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1216 (h->sps.bitstream_restriction_flag &&
1217 !h->sps.num_reorder_frames)) {
1218 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1219 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1220 "Reenabling low delay requires a codec flush.\n");
1225 if (h->avctx->has_b_frames < 2)
1226 h->avctx->has_b_frames = !h->low_delay;
1228 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1229 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1230 if (h->avctx->codec &&
1231 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
1232 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
1233 av_log(h->avctx, AV_LOG_ERROR,
1234 "VDPAU decoding does not support video colorspace.\n");
1235 return AVERROR_INVALIDDATA;
1237 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
1238 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
1239 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1240 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1241 h->pixel_shift = h->sps.bit_depth_luma > 8;
1243 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1244 h->sps.chroma_format_idc);
1245 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1246 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1247 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1248 h->sps.chroma_format_idc);
1250 if (CONFIG_ERROR_RESILIENCE)
1251 ff_dsputil_init(&h->dsp, h->avctx);
1252 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1254 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1255 h->sps.bit_depth_luma);
1256 return AVERROR_INVALIDDATA;
1262 int ff_set_ref_count(H264Context *h)
1264 int ref_count[2], list_count;
1265 int num_ref_idx_active_override_flag;
1267 // set defaults, might be overridden a few lines later
1268 ref_count[0] = h->pps.ref_count[0];
1269 ref_count[1] = h->pps.ref_count[1];
1271 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
1273 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1275 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1276 h->direct_spatial_mv_pred = get_bits1(&h->gb);
1277 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1279 if (num_ref_idx_active_override_flag) {
1280 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1281 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
1282 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1284 // full range is spec-ok in this case, even for frames
1288 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1289 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]);
1290 h->ref_count[0] = h->ref_count[1] = 0;
1292 return AVERROR_INVALIDDATA;
1295 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
1301 ref_count[0] = ref_count[1] = 0;
1304 if (list_count != h->list_count ||
1305 ref_count[0] != h->ref_count[0] ||
1306 ref_count[1] != h->ref_count[1]) {
1307 h->ref_count[0] = ref_count[0];
1308 h->ref_count[1] = ref_count[1];
1309 h->list_count = list_count;
1316 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1318 static int find_start_code(const uint8_t *buf, int buf_size,
1319 int buf_index, int next_avc)
1321 // start code prefix search
1322 for (; buf_index + 3 < next_avc; buf_index++)
1323 // This should always succeed in the first iteration.
1324 if (buf[buf_index] == 0 &&
1325 buf[buf_index + 1] == 0 &&
1326 buf[buf_index + 2] == 1)
1331 if (buf_index >= buf_size)
1337 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1338 int buf_size, int *buf_index)
1342 if (*buf_index >= buf_size - h->nal_length_size)
1345 for (i = 0; i < h->nal_length_size; i++)
1346 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1347 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1348 av_log(h->avctx, AV_LOG_ERROR,
1349 "AVC: nal size %d\n", nalsize);
1355 static int get_bit_length(H264Context *h, const uint8_t *buf,
1356 const uint8_t *ptr, int dst_length,
1357 int i, int next_avc)
1359 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1360 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1361 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1362 h->workaround_bugs |= FF_BUG_TRUNCATED;
1364 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1365 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1371 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1374 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1376 int next_avc = h->is_avc ? 0 : buf_size;
1379 int nals_needed = 0;
1380 int first_slice = 0;
1384 int dst_length, bit_length, consumed;
1387 if (buf_index >= next_avc) {
1388 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1391 next_avc = buf_index + nalsize;
1393 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1394 if (buf_index >= buf_size)
1396 if (buf_index >= next_avc)
1400 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1401 next_avc - buf_index);
1403 if (ptr == NULL || dst_length < 0)
1404 return AVERROR_INVALIDDATA;
1406 buf_index += consumed;
1408 bit_length = get_bit_length(h, buf, ptr, dst_length,
1409 buf_index, next_avc);
1412 /* packets can sometimes contain multiple PPS/SPS,
1413 * e.g. two PAFF field pictures in one packet, or a demuxer
1414 * which splits NALs strangely if so, when frame threading we
1415 * can't start the next thread until we've read all of them */
1416 switch (h->nal_unit_type) {
1419 nals_needed = nal_index;
1424 init_get_bits(&h->gb, ptr, bit_length);
1425 if (!get_ue_golomb(&h->gb) ||
1427 first_slice != h->nal_unit_type)
1428 nals_needed = nal_index;
1430 first_slice = h->nal_unit_type;
1437 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1438 int parse_extradata)
1440 AVCodecContext *const avctx = h->avctx;
1441 H264Context *hx; ///< thread context
1443 unsigned context_count;
1445 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1450 h->nal_unit_type= 0;
1452 if(!h->slice_context_count)
1453 h->slice_context_count= 1;
1454 h->max_contexts = h->slice_context_count;
1455 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1456 h->current_slice = 0;
1457 if (!h->first_field)
1458 h->cur_pic_ptr = NULL;
1459 ff_h264_reset_sei(h);
1462 if (h->nal_length_size == 4) {
1463 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1465 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1469 if (avctx->active_thread_type & FF_THREAD_FRAME)
1470 nals_needed = get_last_needed_nal(h, buf, buf_size);
1475 next_avc = h->is_avc ? 0 : buf_size;
1485 if (buf_index >= next_avc) {
1486 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1489 next_avc = buf_index + nalsize;
1491 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1492 if (buf_index >= buf_size)
1494 if (buf_index >= next_avc)
1498 hx = h->thread_context[context_count];
1500 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1501 &consumed, next_avc - buf_index);
1502 if (ptr == NULL || dst_length < 0) {
1507 bit_length = get_bit_length(h, buf, ptr, dst_length,
1508 buf_index + consumed, next_avc);
1510 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1511 av_log(h->avctx, AV_LOG_DEBUG,
1512 "NAL %d/%d at %d/%d length %d\n",
1513 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
1515 if (h->is_avc && (nalsize != consumed) && nalsize)
1516 av_log(h->avctx, AV_LOG_DEBUG,
1517 "AVC: Consumed only %d bytes instead of %d\n",
1520 buf_index += consumed;
1523 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1524 h->nal_ref_idc == 0 &&
1525 h->nal_unit_type != NAL_SEI)
1529 if ( !(avctx->active_thread_type & FF_THREAD_FRAME)
1530 || nals_needed >= nal_index)
1532 /* Ignore per frame NAL unit type during extradata
1533 * parsing. Decoding slices is not possible in codec init
1535 if (parse_extradata) {
1536 switch (hx->nal_unit_type) {
1542 av_log(h->avctx, AV_LOG_WARNING,
1543 "Ignoring NAL %d in global header/extradata\n",
1545 // fall through to next case
1546 case NAL_AUXILIARY_SLICE:
1547 hx->nal_unit_type = NAL_FF_IGNORE;
1553 switch (hx->nal_unit_type) {
1555 if (h->nal_unit_type != NAL_IDR_SLICE) {
1556 av_log(h->avctx, AV_LOG_ERROR,
1557 "Invalid mix of idr and non-idr slices\n");
1562 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1565 init_get_bits(&hx->gb, ptr, bit_length);
1567 hx->inter_gb_ptr = &hx->gb;
1568 hx->data_partitioning = 0;
1570 if ((err = ff_h264_decode_slice_header(hx, h)))
1573 if (h->sei_recovery_frame_cnt >= 0) {
1574 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
1575 h->valid_recovery_point = 1;
1577 if ( h->recovery_frame < 0
1578 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
1579 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1580 ((1 << h->sps.log2_max_frame_num) - 1);
1582 if (!h->valid_recovery_point)
1583 h->recovery_frame = h->frame_num;
1587 h->cur_pic_ptr->f.key_frame |=
1588 (hx->nal_unit_type == NAL_IDR_SLICE);
1590 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1591 h->recovery_frame == h->frame_num) {
1592 h->recovery_frame = -1;
1593 h->cur_pic_ptr->recovered = 1;
1595 // If we have an IDR, all frames after it in decoded order are
1597 if (hx->nal_unit_type == NAL_IDR_SLICE)
1598 h->frame_recovered |= FRAME_RECOVERED_IDR;
1599 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1600 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1602 h->cur_pic_ptr->recovered |= h->frame_recovered;
1604 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1607 if (h->current_slice == 1) {
1608 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1609 decode_postinit(h, nal_index >= nals_needed);
1611 if (h->avctx->hwaccel &&
1612 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1614 if (CONFIG_H264_VDPAU_DECODER &&
1615 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
1616 ff_vdpau_h264_picture_start(h);
1619 if (hx->redundant_pic_count == 0 &&
1620 (avctx->skip_frame < AVDISCARD_NONREF ||
1622 (avctx->skip_frame < AVDISCARD_BIDIR ||
1623 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1624 (avctx->skip_frame < AVDISCARD_NONKEY ||
1625 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1626 avctx->skip_frame < AVDISCARD_ALL) {
1627 if (avctx->hwaccel) {
1628 ret = avctx->hwaccel->decode_slice(avctx,
1629 &buf[buf_index - consumed],
1633 } else if (CONFIG_H264_VDPAU_DECODER &&
1634 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
1635 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1637 sizeof(start_code));
1638 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1639 &buf[buf_index - consumed],
1646 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
1647 av_log(h->avctx, AV_LOG_ERROR,
1648 "Decoding in chunks is not supported for "
1649 "partitioned slices.\n");
1650 return AVERROR(ENOSYS);
1653 init_get_bits(&hx->gb, ptr, bit_length);
1655 hx->inter_gb_ptr = NULL;
1657 if ((err = ff_h264_decode_slice_header(hx, h)) < 0) {
1658 /* make sure data_partitioning is cleared if it was set
1659 * before, so we don't try decoding a slice without a valid
1660 * slice header later */
1661 h->data_partitioning = 0;
1665 hx->data_partitioning = 1;
1668 init_get_bits(&hx->intra_gb, ptr, bit_length);
1669 hx->intra_gb_ptr = &hx->intra_gb;
1672 init_get_bits(&hx->inter_gb, ptr, bit_length);
1673 hx->inter_gb_ptr = &hx->inter_gb;
1675 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
1678 if (hx->redundant_pic_count == 0 &&
1680 hx->data_partitioning &&
1681 h->cur_pic_ptr && h->context_initialized &&
1682 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
1683 (avctx->skip_frame < AVDISCARD_BIDIR ||
1684 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
1685 (avctx->skip_frame < AVDISCARD_NONKEY ||
1686 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
1687 avctx->skip_frame < AVDISCARD_ALL)
1691 init_get_bits(&h->gb, ptr, bit_length);
1692 ff_h264_decode_sei(h);
1695 init_get_bits(&h->gb, ptr, bit_length);
1696 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
1697 av_log(h->avctx, AV_LOG_DEBUG,
1698 "SPS decoding failure, trying again with the complete NAL\n");
1700 av_assert0(next_avc - buf_index + consumed == nalsize);
1701 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1703 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1704 8*(next_avc - buf_index + consumed - 1));
1705 ff_h264_decode_seq_parameter_set(h);
1710 init_get_bits(&h->gb, ptr, bit_length);
1711 ff_h264_decode_picture_parameter_set(h, bit_length);
1714 case NAL_END_SEQUENCE:
1715 case NAL_END_STREAM:
1716 case NAL_FILLER_DATA:
1718 case NAL_AUXILIARY_SLICE:
1723 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1724 hx->nal_unit_type, bit_length);
1727 if (context_count == h->max_contexts) {
1728 ff_h264_execute_decode_slices(h, context_count);
1733 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1734 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
1735 } else if (err == 1) {
1736 /* Slice could not be decoded in parallel mode, copy down
1737 * NAL unit stuff to context 0 and restart. Note that
1738 * rbsp_buffer is not transferred, but since we no longer
1739 * run in parallel mode this should not be an issue. */
1740 h->nal_unit_type = hx->nal_unit_type;
1741 h->nal_ref_idc = hx->nal_ref_idc;
1748 ff_h264_execute_decode_slices(h, context_count);
1752 if (h->cur_pic_ptr && !h->droppable) {
1753 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1754 h->picture_structure == PICT_BOTTOM_FIELD);
1757 return (ret < 0) ? ret : buf_index;
1761 * Return the number of bytes consumed for building the current frame.
1763 static int get_consumed_bytes(int pos, int buf_size)
1766 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
1767 if (pos + 10 > buf_size)
1768 pos = buf_size; // oops ;)
1773 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1775 AVFrame *src = &srcp->f;
1776 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1778 int ret = av_frame_ref(dst, src);
1782 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1784 if (srcp->sei_recovery_frame_cnt == 0)
1789 for (i = 0; i < desc->nb_components; i++) {
1790 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1791 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1792 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1793 (srcp->crop_top >> vshift) * dst->linesize[i];
1794 dst->data[i] += off;
1799 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1800 int *got_frame, AVPacket *avpkt)
1802 const uint8_t *buf = avpkt->data;
1803 int buf_size = avpkt->size;
1804 H264Context *h = avctx->priv_data;
1805 AVFrame *pict = data;
1811 h->flags = avctx->flags;
1812 /* reset data partitioning here, to ensure GetBitContexts from previous
1813 * packets do not get used. */
1814 h->data_partitioning = 0;
1816 /* end of stream, output what is still in the buffers */
1817 if (buf_size == 0) {
1820 h->cur_pic_ptr = NULL;
1823 // FIXME factorize this with the output code below
1824 out = h->delayed_pic[0];
1827 h->delayed_pic[i] &&
1828 !h->delayed_pic[i]->f.key_frame &&
1829 !h->delayed_pic[i]->mmco_reset;
1831 if (h->delayed_pic[i]->poc < out->poc) {
1832 out = h->delayed_pic[i];
1836 for (i = out_idx; h->delayed_pic[i]; i++)
1837 h->delayed_pic[i] = h->delayed_pic[i + 1];
1840 out->reference &= ~DELAYED_PIC_REF;
1841 ret = output_frame(h, pict, out);
1849 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1850 int cnt= buf[5]&0x1f;
1851 const uint8_t *p= buf+6;
1853 int nalsize= AV_RB16(p) + 2;
1854 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1862 int nalsize= AV_RB16(p) + 2;
1863 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1868 return ff_h264_decode_extradata(h, buf, buf_size);
1872 buf_index = decode_nal_units(h, buf, buf_size, 0);
1874 return AVERROR_INVALIDDATA;
1876 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1877 av_assert0(buf_index <= buf_size);
1881 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1882 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1883 buf_size >= 4 && !memcmp("Q264", buf, 4))
1885 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1886 return AVERROR_INVALIDDATA;
1889 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1890 (h->mb_y >= h->mb_height && h->mb_height)) {
1891 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1892 decode_postinit(h, 1);
1894 ff_h264_field_end(h, 0);
1896 /* Wait for second field. */
1898 if (h->next_output_pic && (
1899 h->next_output_pic->recovered)) {
1900 if (!h->next_output_pic->recovered)
1901 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1903 ret = output_frame(h, pict, h->next_output_pic);
1907 if (CONFIG_MPEGVIDEO) {
1908 ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,
1909 h->next_output_pic->mb_type,
1910 h->next_output_pic->qscale_table,
1911 h->next_output_pic->motion_val,
1913 h->mb_width, h->mb_height, h->mb_stride, 1);
1918 assert(pict->buf[0] || !*got_frame);
1920 return get_consumed_bytes(buf_index, buf_size);
1923 av_cold void ff_h264_free_context(H264Context *h)
1927 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1929 for (i = 0; i < MAX_SPS_COUNT; i++)
1930 av_freep(h->sps_buffers + i);
1932 for (i = 0; i < MAX_PPS_COUNT; i++)
1933 av_freep(h->pps_buffers + i);
1936 static av_cold int h264_decode_end(AVCodecContext *avctx)
1938 H264Context *h = avctx->priv_data;
1940 ff_h264_remove_all_refs(h);
1941 ff_h264_free_context(h);
1943 ff_h264_unref_picture(h, &h->cur_pic);
1948 static const AVProfile profiles[] = {
1949 { FF_PROFILE_H264_BASELINE, "Baseline" },
1950 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1951 { FF_PROFILE_H264_MAIN, "Main" },
1952 { FF_PROFILE_H264_EXTENDED, "Extended" },
1953 { FF_PROFILE_H264_HIGH, "High" },
1954 { FF_PROFILE_H264_HIGH_10, "High 10" },
1955 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1956 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1957 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1958 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1959 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1960 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1961 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1962 { FF_PROFILE_UNKNOWN },
1965 static const AVOption h264_options[] = {
1966 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1967 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1971 static const AVClass h264_class = {
1972 .class_name = "H264 Decoder",
1973 .item_name = av_default_item_name,
1974 .option = h264_options,
1975 .version = LIBAVUTIL_VERSION_INT,
1978 static const AVClass h264_vdpau_class = {
1979 .class_name = "H264 VDPAU Decoder",
1980 .item_name = av_default_item_name,
1981 .option = h264_options,
1982 .version = LIBAVUTIL_VERSION_INT,
1985 AVCodec ff_h264_decoder = {
1987 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1988 .type = AVMEDIA_TYPE_VIDEO,
1989 .id = AV_CODEC_ID_H264,
1990 .priv_data_size = sizeof(H264Context),
1991 .init = ff_h264_decode_init,
1992 .close = h264_decode_end,
1993 .decode = h264_decode_frame,
1994 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
1995 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
1996 CODEC_CAP_FRAME_THREADS,
1998 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1999 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
2000 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2001 .priv_class = &h264_class,
2004 #if CONFIG_H264_VDPAU_DECODER
2005 AVCodec ff_h264_vdpau_decoder = {
2006 .name = "h264_vdpau",
2007 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
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_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2016 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2018 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2019 .priv_class = &h264_vdpau_class,