2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/avassert.h"
31 #include "libavutil/display.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/stereo3d.h"
35 #include "libavutil/timer.h"
38 #include "cabac_functions.h"
39 #include "error_resilience.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
48 #include "mpegutils.h"
49 #include "rectangle.h"
52 #include "vdpau_internal.h"
54 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
58 H264Context *h = avctx->priv_data;
59 return h ? h->sps.num_reorder_frames : 0;
62 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
64 int mb_x, int mb_y, int mb_intra, int mb_skipped)
66 H264Context *h = opaque;
67 H264SliceContext *sl = &h->slice_ctx[0];
71 h->mb_xy = mb_x + mb_y * h->mb_stride;
72 memset(sl->non_zero_count_cache, 0, sizeof(sl->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 >= sl->ref_count[0])
80 if (!sl->ref_list[0][ref].f.data[0]) {
81 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
84 if ((sl->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(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
91 fill_rectangle(sl->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, &h->slice_ctx[0]);
98 void ff_h264_draw_horiz_band(H264Context *h, H264SliceContext *sl,
101 AVCodecContext *avctx = h->avctx;
102 AVFrame *cur = &h->cur_pic.f;
103 AVFrame *last = sl->ref_list[0][0].f.data[0] ? &sl->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, H264SliceContext *sl)
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 (!(sl->top_samples_available & 0x8000)) {
158 for (i = 0; i < 4; i++) {
159 int status = top[sl->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 sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
171 if ((sl->left_samples_available & 0x8888) != 0x8888) {
172 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
173 for (i = 0; i < 4; i++)
174 if (!(sl->left_samples_available & mask[i])) {
175 int status = left[sl->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 sl->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, H264SliceContext *sl,
195 int mode, int is_chroma)
197 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
198 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
201 av_log(h->avctx, AV_LOG_ERROR,
202 "out of range intra chroma pred mode at %d %d\n",
204 return AVERROR_INVALIDDATA;
207 if (!(sl->top_samples_available & 0x8000)) {
210 av_log(h->avctx, AV_LOG_ERROR,
211 "top block unavailable for requested intra mode at %d %d\n",
213 return AVERROR_INVALIDDATA;
217 if ((sl->left_samples_available & 0x8080) != 0x8080) {
220 av_log(h->avctx, AV_LOG_ERROR,
221 "left block unavailable for requested intra mode at %d %d\n",
223 return AVERROR_INVALIDDATA;
225 if (is_chroma && (sl->left_samples_available & 0x8080)) {
226 // mad cow disease mode, aka MBAFF + constrained_intra_pred
227 mode = ALZHEIMER_DC_L0T_PRED8x8 +
228 (!(sl->left_samples_available & 0x8000)) +
229 2 * (mode == DC_128_PRED8x8);
236 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
237 int *dst_length, int *consumed, int length)
243 // src[0]&0x80; // forbidden bit
244 h->nal_ref_idc = src[0] >> 5;
245 h->nal_unit_type = src[0] & 0x1F;
250 #define STARTCODE_TEST \
251 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
252 if (src[i + 2] != 3 && src[i + 2] != 0) { \
253 /* startcode, so we must be past the end */ \
259 #if HAVE_FAST_UNALIGNED
260 #define FIND_FIRST_ZERO \
261 if (i > 0 && !src[i]) \
267 for (i = 0; i + 1 < length; i += 9) {
268 if (!((~AV_RN64A(src + i) &
269 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
270 0x8000800080008080ULL))
277 for (i = 0; i + 1 < length; i += 5) {
278 if (!((~AV_RN32A(src + i) &
279 (AV_RN32A(src + i) - 0x01000101U)) &
288 for (i = 0; i + 1 < length; i += 2) {
291 if (i > 0 && src[i - 1] == 0)
297 // use second escape buffer for inter data
298 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
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 && src[si + 2] != 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]);
395 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
398 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
399 h->DPB[i].needs_realloc = 1;
402 h->cur_pic_ptr = NULL;
404 for (i = 0; i < H264_MAX_THREADS; i++) {
405 hx = h->thread_context[i];
408 av_freep(&hx->top_borders[1]);
409 av_freep(&hx->top_borders[0]);
410 av_freep(&hx->bipred_scratchpad);
411 av_freep(&hx->edge_emu_buffer);
412 av_freep(&hx->dc_val_base);
413 av_freep(&hx->er.mb_index2xy);
414 av_freep(&hx->er.error_status_table);
415 av_freep(&hx->er.er_temp_buffer);
416 av_freep(&hx->er.mbintra_table);
417 av_freep(&hx->er.mbskip_table);
420 av_freep(&hx->rbsp_buffer[1]);
421 av_freep(&hx->rbsp_buffer[0]);
422 hx->rbsp_buffer_size[0] = 0;
423 hx->rbsp_buffer_size[1] = 0;
426 av_freep(&h->thread_context[i]);
430 int ff_h264_alloc_tables(H264Context *h)
432 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
433 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
436 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
437 row_mb_num, 8 * sizeof(uint8_t), fail)
438 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
440 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
441 big_mb_num * 48 * sizeof(uint8_t), fail)
442 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
443 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
444 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
445 big_mb_num * sizeof(uint16_t), fail)
446 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
447 big_mb_num * sizeof(uint8_t), fail)
448 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
449 row_mb_num, 16 * sizeof(uint8_t), fail);
450 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
451 row_mb_num, 16 * sizeof(uint8_t), fail);
452 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
453 4 * big_mb_num * sizeof(uint8_t), fail);
454 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
455 big_mb_num * sizeof(uint8_t), fail)
457 memset(h->slice_table_base, -1,
458 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
459 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
461 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
462 big_mb_num * sizeof(uint32_t), fail);
463 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
464 big_mb_num * sizeof(uint32_t), fail);
465 for (y = 0; y < h->mb_height; y++)
466 for (x = 0; x < h->mb_width; x++) {
467 const int mb_xy = x + y * h->mb_stride;
468 const int b_xy = 4 * x + 4 * y * h->b_stride;
470 h->mb2b_xy[mb_xy] = b_xy;
471 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
474 if (!h->dequant4_coeff[0])
475 ff_h264_init_dequant_tables(h);
478 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
481 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
482 av_frame_unref(&h->DPB[i].f);
483 av_frame_unref(&h->cur_pic.f);
489 ff_h264_free_tables(h, 1);
490 return AVERROR(ENOMEM);
495 * Allocate buffers which are not shared amongst multiple threads.
497 int ff_h264_context_init(H264Context *h)
499 ERContext *er = &h->er;
500 int mb_array_size = h->mb_height * h->mb_stride;
501 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
502 int c_size = h->mb_stride * (h->mb_height + 1);
503 int yc_size = y_size + 2 * c_size;
506 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->top_borders[0],
507 h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
508 FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->top_borders[1],
509 h->mb_width, 16 * 3 * sizeof(uint8_t) * 2, fail)
511 for (i = 0; i < h->nb_slice_ctx; i++) {
512 h->slice_ctx[i].ref_cache[0][scan8[5] + 1] =
513 h->slice_ctx[i].ref_cache[0][scan8[7] + 1] =
514 h->slice_ctx[i].ref_cache[0][scan8[13] + 1] =
515 h->slice_ctx[i].ref_cache[1][scan8[5] + 1] =
516 h->slice_ctx[i].ref_cache[1][scan8[7] + 1] =
517 h->slice_ctx[i].ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
520 if (CONFIG_ERROR_RESILIENCE) {
522 er->avctx = h->avctx;
523 er->decode_mb = h264_er_decode_mb;
525 er->quarter_sample = 1;
527 er->mb_num = h->mb_num;
528 er->mb_width = h->mb_width;
529 er->mb_height = h->mb_height;
530 er->mb_stride = h->mb_stride;
531 er->b8_stride = h->mb_width * 2 + 1;
533 // error resilience code looks cleaner with this
534 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
535 (h->mb_num + 1) * sizeof(int), fail);
537 for (y = 0; y < h->mb_height; y++)
538 for (x = 0; x < h->mb_width; x++)
539 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
541 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
542 h->mb_stride + h->mb_width;
544 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
545 mb_array_size * sizeof(uint8_t), fail);
547 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
548 memset(er->mbintra_table, 1, mb_array_size);
550 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
552 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
553 h->mb_height * h->mb_stride, fail);
555 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base,
556 yc_size * sizeof(int16_t), fail);
557 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
558 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
559 er->dc_val[2] = er->dc_val[1] + c_size;
560 for (i = 0; i < yc_size; i++)
561 h->dc_val_base[i] = 1024;
567 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
570 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
571 int parse_extradata);
573 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
575 AVCodecContext *avctx = h->avctx;
578 if (!buf || size <= 0)
583 const unsigned char *p = buf;
588 av_log(avctx, AV_LOG_ERROR,
589 "avcC %d too short\n", size);
590 return AVERROR_INVALIDDATA;
592 /* sps and pps in the avcC always have length coded with 2 bytes,
593 * so put a fake nal_length_size = 2 while parsing them */
594 h->nal_length_size = 2;
595 // Decode sps from avcC
596 cnt = *(p + 5) & 0x1f; // Number of sps
598 for (i = 0; i < cnt; i++) {
599 nalsize = AV_RB16(p) + 2;
600 if(nalsize > size - (p-buf))
601 return AVERROR_INVALIDDATA;
602 ret = decode_nal_units(h, p, nalsize, 1);
604 av_log(avctx, AV_LOG_ERROR,
605 "Decoding sps %d from avcC failed\n", i);
610 // Decode pps from avcC
611 cnt = *(p++); // Number of pps
612 for (i = 0; i < cnt; i++) {
613 nalsize = AV_RB16(p) + 2;
614 if(nalsize > size - (p-buf))
615 return AVERROR_INVALIDDATA;
616 ret = decode_nal_units(h, p, nalsize, 1);
618 av_log(avctx, AV_LOG_ERROR,
619 "Decoding pps %d from avcC failed\n", i);
624 // Store right nal length size that will be used to parse all other nals
625 h->nal_length_size = (buf[4] & 0x03) + 1;
628 ret = decode_nal_units(h, buf, size, 1);
635 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
637 H264Context *h = avctx->priv_data;
643 h->bit_depth_luma = 8;
644 h->chroma_format_idc = 1;
646 h->avctx->bits_per_raw_sample = 8;
647 h->cur_chroma_format_idc = 1;
649 ff_h264dsp_init(&h->h264dsp, 8, 1);
650 av_assert0(h->sps.bit_depth_chroma == 0);
651 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
652 ff_h264qpel_init(&h->h264qpel, 8);
653 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
655 h->dequant_coeff_pps = -1;
656 h->current_sps_id = -1;
658 /* needed so that IDCT permutation is known early */
659 ff_videodsp_init(&h->vdsp, 8);
661 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
662 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
664 h->picture_structure = PICT_FRAME;
665 h->slice_context_count = 1;
666 h->workaround_bugs = avctx->workaround_bugs;
667 h->flags = avctx->flags;
670 // s->decode_mb = ff_h263_decode_mb;
671 if (!avctx->has_b_frames)
674 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
676 ff_h264_decode_init_vlc();
678 ff_init_cabac_states();
681 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
683 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
684 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
687 return AVERROR(ENOMEM);
690 h->thread_context[0] = h;
691 for (i = 0; i < h->nb_slice_ctx; i++)
692 h->slice_ctx[i].h264 = h->thread_context[0];
694 h->outputed_poc = h->next_outputed_poc = INT_MIN;
695 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
696 h->last_pocs[i] = INT_MIN;
697 h->prev_poc_msb = 1 << 16;
698 h->prev_frame_num = -1;
700 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
701 ff_h264_reset_sei(h);
702 if (avctx->codec_id == AV_CODEC_ID_H264) {
703 if (avctx->ticks_per_frame == 1) {
704 if(h->avctx->time_base.den < INT_MAX/2) {
705 h->avctx->time_base.den *= 2;
707 h->avctx->time_base.num /= 2;
709 avctx->ticks_per_frame = 2;
712 if (avctx->extradata_size > 0 && avctx->extradata) {
713 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
715 ff_h264_free_context(h);
720 if (h->sps.bitstream_restriction_flag &&
721 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
722 h->avctx->has_b_frames = h->sps.num_reorder_frames;
726 avctx->internal->allocate_progress = 1;
728 ff_h264_flush_change(h);
733 static int decode_init_thread_copy(AVCodecContext *avctx)
735 H264Context *h = avctx->priv_data;
738 if (!avctx->internal->is_copy)
740 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
741 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
743 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
744 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
747 return AVERROR(ENOMEM);
750 for (i = 0; i < h->nb_slice_ctx; i++)
751 h->slice_ctx[i].h264 = h;
754 h->rbsp_buffer[0] = NULL;
755 h->rbsp_buffer[1] = NULL;
756 h->rbsp_buffer_size[0] = 0;
757 h->rbsp_buffer_size[1] = 0;
758 h->context_initialized = 0;
764 * Run setup operations that must be run after slice header decoding.
765 * This includes finding the next displayed frame.
767 * @param h h264 master context
768 * @param setup_finished enough NALs have been read that we can call
769 * ff_thread_finish_setup()
771 static void decode_postinit(H264Context *h, int setup_finished)
773 H264Picture *out = h->cur_pic_ptr;
774 H264Picture *cur = h->cur_pic_ptr;
775 int i, pics, out_of_order, out_idx;
777 h->cur_pic_ptr->f.pict_type = h->pict_type;
779 if (h->next_output_pic)
782 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
783 /* FIXME: if we have two PAFF fields in one packet, we can't start
784 * the next thread here. If we have one field per packet, we can.
785 * The check in decode_nal_units() is not good enough to find this
786 * yet, so we assume the worst for now. */
787 // if (setup_finished)
788 // ff_thread_finish_setup(h->avctx);
789 if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
791 if (h->avctx->hwaccel || h->missing_fields <=1)
795 cur->f.interlaced_frame = 0;
796 cur->f.repeat_pict = 0;
798 /* Signal interlacing information externally. */
799 /* Prioritize picture timing SEI information over used
800 * decoding process if it exists. */
802 if (h->sps.pic_struct_present_flag) {
803 switch (h->sei_pic_struct) {
804 case SEI_PIC_STRUCT_FRAME:
806 case SEI_PIC_STRUCT_TOP_FIELD:
807 case SEI_PIC_STRUCT_BOTTOM_FIELD:
808 cur->f.interlaced_frame = 1;
810 case SEI_PIC_STRUCT_TOP_BOTTOM:
811 case SEI_PIC_STRUCT_BOTTOM_TOP:
812 if (FIELD_OR_MBAFF_PICTURE(h))
813 cur->f.interlaced_frame = 1;
815 // try to flag soft telecine progressive
816 cur->f.interlaced_frame = h->prev_interlaced_frame;
818 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
819 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
820 /* Signal the possibility of telecined film externally
821 * (pic_struct 5,6). From these hints, let the applications
822 * decide if they apply deinterlacing. */
823 cur->f.repeat_pict = 1;
825 case SEI_PIC_STRUCT_FRAME_DOUBLING:
826 cur->f.repeat_pict = 2;
828 case SEI_PIC_STRUCT_FRAME_TRIPLING:
829 cur->f.repeat_pict = 4;
833 if ((h->sei_ct_type & 3) &&
834 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
835 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
837 /* Derive interlacing flag from used decoding process. */
838 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
840 h->prev_interlaced_frame = cur->f.interlaced_frame;
842 if (cur->field_poc[0] != cur->field_poc[1]) {
843 /* Derive top_field_first from field pocs. */
844 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
846 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
847 /* Use picture timing SEI information. Even if it is a
848 * information of a past frame, better than nothing. */
849 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
850 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
851 cur->f.top_field_first = 1;
853 cur->f.top_field_first = 0;
855 /* Most likely progressive */
856 cur->f.top_field_first = 0;
860 if (h->sei_frame_packing_present &&
861 h->frame_packing_arrangement_type >= 0 &&
862 h->frame_packing_arrangement_type <= 6 &&
863 h->content_interpretation_type > 0 &&
864 h->content_interpretation_type < 3) {
865 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
867 switch (h->frame_packing_arrangement_type) {
869 stereo->type = AV_STEREO3D_CHECKERBOARD;
872 stereo->type = AV_STEREO3D_COLUMNS;
875 stereo->type = AV_STEREO3D_LINES;
878 if (h->quincunx_subsampling)
879 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
881 stereo->type = AV_STEREO3D_SIDEBYSIDE;
884 stereo->type = AV_STEREO3D_TOPBOTTOM;
887 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
890 stereo->type = AV_STEREO3D_2D;
894 if (h->content_interpretation_type == 2)
895 stereo->flags = AV_STEREO3D_FLAG_INVERT;
899 if (h->sei_display_orientation_present &&
900 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
901 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
902 AVFrameSideData *rotation = av_frame_new_side_data(&cur->f,
903 AV_FRAME_DATA_DISPLAYMATRIX,
904 sizeof(int32_t) * 9);
906 av_display_rotation_set((int32_t *)rotation->data, angle);
907 av_display_matrix_flip((int32_t *)rotation->data,
908 h->sei_hflip, h->sei_vflip);
912 cur->mmco_reset = h->mmco_reset;
915 // FIXME do something with unavailable reference frames
917 /* Sort B-frames into display order */
919 if (h->sps.bitstream_restriction_flag &&
920 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
921 h->avctx->has_b_frames = h->sps.num_reorder_frames;
925 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
926 !h->sps.bitstream_restriction_flag) {
927 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
931 for (i = 0; 1; i++) {
932 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
934 h->last_pocs[i-1] = cur->poc;
937 h->last_pocs[i-1]= h->last_pocs[i];
940 out_of_order = MAX_DELAYED_PIC_COUNT - i;
941 if( cur->f.pict_type == AV_PICTURE_TYPE_B
942 || (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))
943 out_of_order = FFMAX(out_of_order, 1);
944 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
945 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
946 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
947 h->last_pocs[i] = INT_MIN;
948 h->last_pocs[0] = cur->poc;
950 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
951 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
952 h->avctx->has_b_frames = out_of_order;
957 while (h->delayed_pic[pics])
960 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
962 h->delayed_pic[pics++] = cur;
963 if (cur->reference == 0)
964 cur->reference = DELAYED_PIC_REF;
966 out = h->delayed_pic[0];
968 for (i = 1; h->delayed_pic[i] &&
969 !h->delayed_pic[i]->f.key_frame &&
970 !h->delayed_pic[i]->mmco_reset;
972 if (h->delayed_pic[i]->poc < out->poc) {
973 out = h->delayed_pic[i];
976 if (h->avctx->has_b_frames == 0 &&
977 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
978 h->next_outputed_poc = INT_MIN;
979 out_of_order = out->poc < h->next_outputed_poc;
981 if (out_of_order || pics > h->avctx->has_b_frames) {
982 out->reference &= ~DELAYED_PIC_REF;
983 // for frame threading, the owner must be the second field's thread or
984 // else the first thread can release the picture and reuse it unsafely
985 for (i = out_idx; h->delayed_pic[i]; i++)
986 h->delayed_pic[i] = h->delayed_pic[i + 1];
988 if (!out_of_order && pics > h->avctx->has_b_frames) {
989 h->next_output_pic = out;
990 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
991 h->next_outputed_poc = INT_MIN;
993 h->next_outputed_poc = out->poc;
995 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
998 if (h->next_output_pic) {
999 if (h->next_output_pic->recovered) {
1000 // We have reached an recovery point and all frames after it in
1001 // display order are "recovered".
1002 h->frame_recovered |= FRAME_RECOVERED_SEI;
1004 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
1007 if (setup_finished && !h->avctx->hwaccel)
1008 ff_thread_finish_setup(h->avctx);
1011 int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
1014 int luma_def, chroma_def;
1017 sl->use_weight_chroma = 0;
1018 sl->luma_log2_weight_denom = get_ue_golomb(&h->gb);
1019 if (h->sps.chroma_format_idc)
1020 sl->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
1022 if (sl->luma_log2_weight_denom > 7U) {
1023 av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
1024 sl->luma_log2_weight_denom = 0;
1026 if (sl->chroma_log2_weight_denom > 7U) {
1027 av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
1028 sl->chroma_log2_weight_denom = 0;
1031 luma_def = 1 << sl->luma_log2_weight_denom;
1032 chroma_def = 1 << sl->chroma_log2_weight_denom;
1034 for (list = 0; list < 2; list++) {
1035 sl->luma_weight_flag[list] = 0;
1036 sl->chroma_weight_flag[list] = 0;
1037 for (i = 0; i < sl->ref_count[list]; i++) {
1038 int luma_weight_flag, chroma_weight_flag;
1040 luma_weight_flag = get_bits1(&h->gb);
1041 if (luma_weight_flag) {
1042 sl->luma_weight[i][list][0] = get_se_golomb(&h->gb);
1043 sl->luma_weight[i][list][1] = get_se_golomb(&h->gb);
1044 if (sl->luma_weight[i][list][0] != luma_def ||
1045 sl->luma_weight[i][list][1] != 0) {
1047 sl->luma_weight_flag[list] = 1;
1050 sl->luma_weight[i][list][0] = luma_def;
1051 sl->luma_weight[i][list][1] = 0;
1054 if (h->sps.chroma_format_idc) {
1055 chroma_weight_flag = get_bits1(&h->gb);
1056 if (chroma_weight_flag) {
1058 for (j = 0; j < 2; j++) {
1059 sl->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
1060 sl->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
1061 if (sl->chroma_weight[i][list][j][0] != chroma_def ||
1062 sl->chroma_weight[i][list][j][1] != 0) {
1063 sl->use_weight_chroma = 1;
1064 sl->chroma_weight_flag[list] = 1;
1069 for (j = 0; j < 2; j++) {
1070 sl->chroma_weight[i][list][j][0] = chroma_def;
1071 sl->chroma_weight[i][list][j][1] = 0;
1076 if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
1079 sl->use_weight = sl->use_weight || sl->use_weight_chroma;
1084 * instantaneous decoder refresh.
1086 static void idr(H264Context *h)
1089 ff_h264_remove_all_refs(h);
1091 h->prev_frame_num_offset = 0;
1092 h->prev_poc_msb = 1<<16;
1093 h->prev_poc_lsb = 0;
1094 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1095 h->last_pocs[i] = INT_MIN;
1098 /* forget old pics after a seek */
1099 void ff_h264_flush_change(H264Context *h)
1103 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1104 h->prev_interlaced_frame = 1;
1107 h->prev_frame_num = -1;
1108 if (h->cur_pic_ptr) {
1109 h->cur_pic_ptr->reference = 0;
1110 for (j=i=0; h->delayed_pic[i]; i++)
1111 if (h->delayed_pic[i] != h->cur_pic_ptr)
1112 h->delayed_pic[j++] = h->delayed_pic[i];
1113 h->delayed_pic[j] = NULL;
1115 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1118 ff_h264_reset_sei(h);
1119 h->recovery_frame = -1;
1120 h->frame_recovered = 0;
1121 h->current_slice = 0;
1123 for (i = 0; i < h->nb_slice_ctx; i++)
1124 h->slice_ctx[i].list_count = 0;
1127 /* forget old pics after a seek */
1128 static void flush_dpb(AVCodecContext *avctx)
1130 H264Context *h = avctx->priv_data;
1133 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
1135 ff_h264_flush_change(h);
1138 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1139 ff_h264_unref_picture(h, &h->DPB[i]);
1140 h->cur_pic_ptr = NULL;
1141 ff_h264_unref_picture(h, &h->cur_pic);
1143 h->mb_x = h->mb_y = 0;
1145 ff_h264_free_tables(h, 1);
1146 h->context_initialized = 0;
1149 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
1151 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
1154 h->frame_num_offset = h->prev_frame_num_offset;
1155 if (h->frame_num < h->prev_frame_num)
1156 h->frame_num_offset += max_frame_num;
1158 if (h->sps.poc_type == 0) {
1159 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
1161 if (h->poc_lsb < h->prev_poc_lsb &&
1162 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1163 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1164 else if (h->poc_lsb > h->prev_poc_lsb &&
1165 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1166 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1168 h->poc_msb = h->prev_poc_msb;
1170 field_poc[1] = h->poc_msb + h->poc_lsb;
1171 if (h->picture_structure == PICT_FRAME)
1172 field_poc[1] += h->delta_poc_bottom;
1173 } else if (h->sps.poc_type == 1) {
1174 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1177 if (h->sps.poc_cycle_length != 0)
1178 abs_frame_num = h->frame_num_offset + h->frame_num;
1182 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1185 expected_delta_per_poc_cycle = 0;
1186 for (i = 0; i < h->sps.poc_cycle_length; i++)
1187 // FIXME integrate during sps parse
1188 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1190 if (abs_frame_num > 0) {
1191 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1192 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1194 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1195 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1196 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1200 if (h->nal_ref_idc == 0)
1201 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1203 field_poc[0] = expectedpoc + h->delta_poc[0];
1204 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1206 if (h->picture_structure == PICT_FRAME)
1207 field_poc[1] += h->delta_poc[1];
1209 int poc = 2 * (h->frame_num_offset + h->frame_num);
1211 if (!h->nal_ref_idc)
1218 if (h->picture_structure != PICT_BOTTOM_FIELD)
1219 pic_field_poc[0] = field_poc[0];
1220 if (h->picture_structure != PICT_TOP_FIELD)
1221 pic_field_poc[1] = field_poc[1];
1222 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1228 * Compute profile from profile_idc and constraint_set?_flags.
1232 * @return profile as defined by FF_PROFILE_H264_*
1234 int ff_h264_get_profile(SPS *sps)
1236 int profile = sps->profile_idc;
1238 switch (sps->profile_idc) {
1239 case FF_PROFILE_H264_BASELINE:
1240 // constraint_set1_flag set to 1
1241 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1243 case FF_PROFILE_H264_HIGH_10:
1244 case FF_PROFILE_H264_HIGH_422:
1245 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1246 // constraint_set3_flag set to 1
1247 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1254 int ff_h264_set_parameter_from_sps(H264Context *h)
1256 if (h->flags & CODEC_FLAG_LOW_DELAY ||
1257 (h->sps.bitstream_restriction_flag &&
1258 !h->sps.num_reorder_frames)) {
1259 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1260 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1261 "Reenabling low delay requires a codec flush.\n");
1266 if (h->avctx->has_b_frames < 2)
1267 h->avctx->has_b_frames = !h->low_delay;
1269 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
1270 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
1271 if (h->avctx->codec &&
1272 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
1273 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
1274 av_log(h->avctx, AV_LOG_ERROR,
1275 "VDPAU decoding does not support video colorspace.\n");
1276 return AVERROR_INVALIDDATA;
1278 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
1279 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
1280 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1281 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
1282 h->pixel_shift = h->sps.bit_depth_luma > 8;
1284 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
1285 h->sps.chroma_format_idc);
1286 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1287 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
1288 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
1289 h->sps.chroma_format_idc);
1291 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
1293 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1294 h->sps.bit_depth_luma);
1295 return AVERROR_INVALIDDATA;
1301 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1303 int ref_count[2], list_count;
1304 int num_ref_idx_active_override_flag;
1306 // set defaults, might be overridden a few lines later
1307 ref_count[0] = h->pps.ref_count[0];
1308 ref_count[1] = h->pps.ref_count[1];
1310 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1312 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
1314 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1315 sl->direct_spatial_mv_pred = get_bits1(&h->gb);
1316 num_ref_idx_active_override_flag = get_bits1(&h->gb);
1318 if (num_ref_idx_active_override_flag) {
1319 ref_count[0] = get_ue_golomb(&h->gb) + 1;
1320 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1321 ref_count[1] = get_ue_golomb(&h->gb) + 1;
1323 // full range is spec-ok in this case, even for frames
1327 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
1328 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]);
1329 sl->ref_count[0] = sl->ref_count[1] = 0;
1331 return AVERROR_INVALIDDATA;
1334 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1340 ref_count[0] = ref_count[1] = 0;
1343 if (list_count != sl->list_count ||
1344 ref_count[0] != sl->ref_count[0] ||
1345 ref_count[1] != sl->ref_count[1]) {
1346 sl->ref_count[0] = ref_count[0];
1347 sl->ref_count[1] = ref_count[1];
1348 sl->list_count = list_count;
1355 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
1357 static int get_bit_length(H264Context *h, const uint8_t *buf,
1358 const uint8_t *ptr, int dst_length,
1359 int i, int next_avc)
1361 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1362 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1363 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1364 h->workaround_bugs |= FF_BUG_TRUNCATED;
1366 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1367 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1373 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1376 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1378 int next_avc = h->is_avc ? 0 : buf_size;
1381 int nals_needed = 0;
1382 int first_slice = 0;
1386 int dst_length, bit_length, consumed;
1389 if (buf_index >= next_avc) {
1390 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1393 next_avc = buf_index + nalsize;
1395 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1396 if (buf_index >= buf_size)
1398 if (buf_index >= next_avc)
1402 ptr = ff_h264_decode_nal(h, buf + buf_index, &dst_length, &consumed,
1403 next_avc - buf_index);
1405 if (!ptr || dst_length < 0)
1406 return AVERROR_INVALIDDATA;
1408 buf_index += consumed;
1410 bit_length = get_bit_length(h, buf, ptr, dst_length,
1411 buf_index, next_avc);
1414 /* packets can sometimes contain multiple PPS/SPS,
1415 * e.g. two PAFF field pictures in one packet, or a demuxer
1416 * which splits NALs strangely if so, when frame threading we
1417 * can't start the next thread until we've read all of them */
1418 switch (h->nal_unit_type) {
1421 nals_needed = nal_index;
1426 init_get_bits(&h->gb, ptr, bit_length);
1427 if (!get_ue_golomb(&h->gb) ||
1429 first_slice != h->nal_unit_type)
1430 nals_needed = nal_index;
1432 first_slice = h->nal_unit_type;
1439 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1440 int parse_extradata)
1442 AVCodecContext *const avctx = h->avctx;
1443 H264Context *hx; ///< thread context
1444 H264SliceContext *sl;
1446 unsigned context_count;
1448 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1453 h->nal_unit_type= 0;
1455 if(!h->slice_context_count)
1456 h->slice_context_count= 1;
1457 h->max_contexts = h->slice_context_count;
1458 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
1459 h->current_slice = 0;
1460 if (!h->first_field)
1461 h->cur_pic_ptr = NULL;
1462 ff_h264_reset_sei(h);
1465 if (h->nal_length_size == 4) {
1466 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
1468 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
1472 if (avctx->active_thread_type & FF_THREAD_FRAME)
1473 nals_needed = get_last_needed_nal(h, buf, buf_size);
1478 next_avc = h->is_avc ? 0 : buf_size;
1488 if (buf_index >= next_avc) {
1489 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1492 next_avc = buf_index + nalsize;
1494 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1495 if (buf_index >= buf_size)
1497 if (buf_index >= next_avc)
1501 hx = h->thread_context[context_count];
1502 sl = &h->slice_ctx[context_count];
1504 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
1505 &consumed, next_avc - buf_index);
1506 if (!ptr || dst_length < 0) {
1511 bit_length = get_bit_length(h, buf, ptr, dst_length,
1512 buf_index + consumed, next_avc);
1514 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1515 av_log(h->avctx, AV_LOG_DEBUG,
1516 "NAL %d/%d at %d/%d length %d\n",
1517 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length);
1519 if (h->is_avc && (nalsize != consumed) && nalsize)
1520 av_log(h->avctx, AV_LOG_DEBUG,
1521 "AVC: Consumed only %d bytes instead of %d\n",
1524 buf_index += consumed;
1527 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1528 h->nal_ref_idc == 0 &&
1529 h->nal_unit_type != NAL_SEI)
1533 if ( (!(avctx->active_thread_type & FF_THREAD_FRAME) || nals_needed >= nal_index)
1534 && !h->current_slice)
1536 /* Ignore per frame NAL unit type during extradata
1537 * parsing. Decoding slices is not possible in codec init
1539 if (parse_extradata) {
1540 switch (hx->nal_unit_type) {
1546 av_log(h->avctx, AV_LOG_WARNING,
1547 "Ignoring NAL %d in global header/extradata\n",
1549 // fall through to next case
1550 case NAL_AUXILIARY_SLICE:
1551 hx->nal_unit_type = NAL_FF_IGNORE;
1557 switch (hx->nal_unit_type) {
1559 if ((ptr[0] & 0xFC) == 0x98) {
1560 av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
1561 h->next_outputed_poc = INT_MIN;
1565 if (h->nal_unit_type != NAL_IDR_SLICE) {
1566 av_log(h->avctx, AV_LOG_ERROR,
1567 "Invalid mix of idr and non-idr slices\n");
1572 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1574 h->has_recovery_point = 1;
1576 init_get_bits(&hx->gb, ptr, bit_length);
1578 hx->inter_gb_ptr = &hx->gb;
1580 if ((err = ff_h264_decode_slice_header(hx, sl, h)))
1583 if (h->sei_recovery_frame_cnt >= 0) {
1584 if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1585 h->valid_recovery_point = 1;
1587 if ( h->recovery_frame < 0
1588 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
1589 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1590 ((1 << h->sps.log2_max_frame_num) - 1);
1592 if (!h->valid_recovery_point)
1593 h->recovery_frame = h->frame_num;
1597 h->cur_pic_ptr->f.key_frame |=
1598 (hx->nal_unit_type == NAL_IDR_SLICE);
1600 if (hx->nal_unit_type == NAL_IDR_SLICE ||
1601 h->recovery_frame == h->frame_num) {
1602 h->recovery_frame = -1;
1603 h->cur_pic_ptr->recovered = 1;
1605 // If we have an IDR, all frames after it in decoded order are
1607 if (hx->nal_unit_type == NAL_IDR_SLICE)
1608 h->frame_recovered |= FRAME_RECOVERED_IDR;
1609 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
1610 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
1612 h->cur_pic_ptr->recovered |= h->frame_recovered;
1614 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1617 if (h->current_slice == 1) {
1618 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
1619 decode_postinit(h, nal_index >= nals_needed);
1621 if (h->avctx->hwaccel &&
1622 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1624 if (CONFIG_H264_VDPAU_DECODER &&
1625 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
1626 ff_vdpau_h264_picture_start(h);
1629 if (hx->redundant_pic_count == 0) {
1630 if (avctx->hwaccel) {
1631 ret = avctx->hwaccel->decode_slice(avctx,
1632 &buf[buf_index - consumed],
1636 } else if (CONFIG_H264_VDPAU_DECODER &&
1637 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
1638 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1640 sizeof(start_code));
1641 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
1642 &buf[buf_index - consumed],
1651 avpriv_request_sample(avctx, "data partitioning");
1652 ret = AVERROR(ENOSYS);
1656 init_get_bits(&h->gb, ptr, bit_length);
1657 ret = ff_h264_decode_sei(h);
1658 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1662 init_get_bits(&h->gb, ptr, bit_length);
1663 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
1664 av_log(h->avctx, AV_LOG_DEBUG,
1665 "SPS decoding failure, trying again with the complete NAL\n");
1667 av_assert0(next_avc - buf_index + consumed == nalsize);
1668 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
1670 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
1671 8*(next_avc - buf_index + consumed - 1));
1672 ff_h264_decode_seq_parameter_set(h);
1677 init_get_bits(&h->gb, ptr, bit_length);
1678 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1679 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1683 case NAL_END_SEQUENCE:
1684 case NAL_END_STREAM:
1685 case NAL_FILLER_DATA:
1687 case NAL_AUXILIARY_SLICE:
1692 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1693 hx->nal_unit_type, bit_length);
1696 if (context_count == h->max_contexts) {
1697 ret = ff_h264_execute_decode_slices(h, context_count);
1698 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1703 if (err < 0 || err == SLICE_SKIPED) {
1705 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1706 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1707 } else if (err == SLICE_SINGLETHREAD) {
1708 /* Slice could not be decoded in parallel mode, copy down
1709 * NAL unit stuff to context 0 and restart. Note that
1710 * rbsp_buffer is not transferred, but since we no longer
1711 * run in parallel mode this should not be an issue. */
1712 h->nal_unit_type = hx->nal_unit_type;
1713 h->nal_ref_idc = hx->nal_ref_idc;
1715 sl = &h->slice_ctx[0];
1720 if (context_count) {
1721 ret = ff_h264_execute_decode_slices(h, context_count);
1722 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1729 if (h->cur_pic_ptr && !h->droppable) {
1730 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1731 h->picture_structure == PICT_BOTTOM_FIELD);
1734 return (ret < 0) ? ret : buf_index;
1738 * Return the number of bytes consumed for building the current frame.
1740 static int get_consumed_bytes(int pos, int buf_size)
1743 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1744 if (pos + 10 > buf_size)
1745 pos = buf_size; // oops ;)
1750 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
1752 AVFrame *src = &srcp->f;
1753 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
1755 int ret = av_frame_ref(dst, src);
1759 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
1761 if (srcp->sei_recovery_frame_cnt == 0)
1766 for (i = 0; i < desc->nb_components; i++) {
1767 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
1768 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
1769 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
1770 (srcp->crop_top >> vshift) * dst->linesize[i];
1771 dst->data[i] += off;
1776 static int is_extra(const uint8_t *buf, int buf_size)
1778 int cnt= buf[5]&0x1f;
1779 const uint8_t *p= buf+6;
1781 int nalsize= AV_RB16(p) + 2;
1782 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
1790 int nalsize= AV_RB16(p) + 2;
1791 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
1798 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1799 int *got_frame, AVPacket *avpkt)
1801 const uint8_t *buf = avpkt->data;
1802 int buf_size = avpkt->size;
1803 H264Context *h = avctx->priv_data;
1804 AVFrame *pict = data;
1810 h->flags = avctx->flags;
1812 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1814 /* end of stream, output what is still in the buffers */
1815 if (buf_size == 0) {
1818 h->cur_pic_ptr = NULL;
1821 // FIXME factorize this with the output code below
1822 out = h->delayed_pic[0];
1825 h->delayed_pic[i] &&
1826 !h->delayed_pic[i]->f.key_frame &&
1827 !h->delayed_pic[i]->mmco_reset;
1829 if (h->delayed_pic[i]->poc < out->poc) {
1830 out = h->delayed_pic[i];
1834 for (i = out_idx; h->delayed_pic[i]; i++)
1835 h->delayed_pic[i] = h->delayed_pic[i + 1];
1838 out->reference &= ~DELAYED_PIC_REF;
1839 ret = output_frame(h, pict, out);
1847 if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
1849 uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
1850 if (is_extra(side, side_size))
1851 ff_h264_decode_extradata(h, side, side_size);
1853 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
1854 if (is_extra(buf, buf_size))
1855 return ff_h264_decode_extradata(h, buf, buf_size);
1858 buf_index = decode_nal_units(h, buf, buf_size, 0);
1860 return AVERROR_INVALIDDATA;
1862 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1863 av_assert0(buf_index <= buf_size);
1867 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1868 if (avctx->skip_frame >= AVDISCARD_NONREF ||
1869 buf_size >= 4 && !memcmp("Q264", buf, 4))
1871 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1872 return AVERROR_INVALIDDATA;
1875 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
1876 (h->mb_y >= h->mb_height && h->mb_height)) {
1877 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
1878 decode_postinit(h, 1);
1880 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1882 /* Wait for second field. */
1884 if (h->next_output_pic && (
1885 h->next_output_pic->recovered)) {
1886 if (!h->next_output_pic->recovered)
1887 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
1889 if (!h->avctx->hwaccel &&
1890 (h->next_output_pic->field_poc[0] == INT_MAX ||
1891 h->next_output_pic->field_poc[1] == INT_MAX)
1894 AVFrame *f = &h->next_output_pic->f;
1895 int field = h->next_output_pic->field_poc[0] == INT_MAX;
1896 uint8_t *dst_data[4];
1898 const uint8_t *src_data[4];
1900 av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
1902 for (p = 0; p<4; p++) {
1903 dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
1904 src_data[p] = f->data[p] + field *f->linesize[p];
1905 linesizes[p] = 2*f->linesize[p];
1908 av_image_copy(dst_data, linesizes, src_data, linesizes,
1909 f->format, f->width, f->height>>1);
1912 ret = output_frame(h, pict, h->next_output_pic);
1916 if (CONFIG_MPEGVIDEO) {
1917 ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,
1918 h->next_output_pic->mb_type,
1919 h->next_output_pic->qscale_table,
1920 h->next_output_pic->motion_val,
1922 h->mb_width, h->mb_height, h->mb_stride, 1);
1927 av_assert0(pict->buf[0] || !*got_frame);
1929 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1931 return get_consumed_bytes(buf_index, buf_size);
1934 av_cold void ff_h264_free_context(H264Context *h)
1938 ff_h264_free_tables(h, 1); // FIXME cleanup init stuff perhaps
1940 av_freep(&h->slice_ctx);
1941 h->nb_slice_ctx = 0;
1943 for (i = 0; i < MAX_SPS_COUNT; i++)
1944 av_freep(h->sps_buffers + i);
1946 for (i = 0; i < MAX_PPS_COUNT; i++)
1947 av_freep(h->pps_buffers + i);
1950 static av_cold int h264_decode_end(AVCodecContext *avctx)
1952 H264Context *h = avctx->priv_data;
1954 ff_h264_remove_all_refs(h);
1955 ff_h264_free_context(h);
1957 ff_h264_unref_picture(h, &h->cur_pic);
1958 ff_h264_unref_picture(h, &h->last_pic_for_ec);
1963 static const AVProfile profiles[] = {
1964 { FF_PROFILE_H264_BASELINE, "Baseline" },
1965 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
1966 { FF_PROFILE_H264_MAIN, "Main" },
1967 { FF_PROFILE_H264_EXTENDED, "Extended" },
1968 { FF_PROFILE_H264_HIGH, "High" },
1969 { FF_PROFILE_H264_HIGH_10, "High 10" },
1970 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
1971 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
1972 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
1973 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
1974 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
1975 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
1976 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
1977 { FF_PROFILE_UNKNOWN },
1980 static const AVOption h264_options[] = {
1981 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
1982 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
1986 static const AVClass h264_class = {
1987 .class_name = "H264 Decoder",
1988 .item_name = av_default_item_name,
1989 .option = h264_options,
1990 .version = LIBAVUTIL_VERSION_INT,
1993 AVCodec ff_h264_decoder = {
1995 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1996 .type = AVMEDIA_TYPE_VIDEO,
1997 .id = AV_CODEC_ID_H264,
1998 .priv_data_size = sizeof(H264Context),
1999 .init = ff_h264_decode_init,
2000 .close = h264_decode_end,
2001 .decode = h264_decode_frame,
2002 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
2003 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
2004 CODEC_CAP_FRAME_THREADS,
2006 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
2007 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
2008 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2009 .priv_class = &h264_class,
2012 #if CONFIG_H264_VDPAU_DECODER
2013 static const AVClass h264_vdpau_class = {
2014 .class_name = "H264 VDPAU Decoder",
2015 .item_name = av_default_item_name,
2016 .option = h264_options,
2017 .version = LIBAVUTIL_VERSION_INT,
2020 AVCodec ff_h264_vdpau_decoder = {
2021 .name = "h264_vdpau",
2022 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
2023 .type = AVMEDIA_TYPE_VIDEO,
2024 .id = AV_CODEC_ID_H264,
2025 .priv_data_size = sizeof(H264Context),
2026 .init = ff_h264_decode_init,
2027 .close = h264_decode_end,
2028 .decode = h264_decode_frame,
2029 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
2031 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
2033 .profiles = NULL_IF_CONFIG_SMALL(profiles),
2034 .priv_class = &h264_vdpau_class,