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 Libav.
7 * Libav 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 * Libav 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 Libav; 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 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/stereo3d.h"
33 #include "libavutil/timer.h"
35 #include "bytestream.h"
37 #include "cabac_functions.h"
38 #include "error_resilience.h"
42 #include "h264chroma.h"
43 #include "h264_mvpred.h"
47 #include "mpegutils.h"
49 #include "rectangle.h"
54 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
58 int mb_x, int mb_y, int mb_intra, int mb_skipped)
60 H264Context *h = opaque;
61 H264SliceContext *sl = &h->slice_ctx[0];
65 sl->mb_xy = mb_x + mb_y * h->mb_stride;
66 memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
68 /* FIXME: It is possible albeit uncommon that slice references
69 * differ between slices. We take the easy approach and ignore
70 * it for now. If this turns out to have any relevance in
71 * practice then correct remapping should be added. */
72 if (ref >= sl->ref_count[0])
74 fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
76 fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
77 fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
78 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
79 assert(!FRAME_MBAFF(h));
80 ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
83 void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
86 AVCodecContext *avctx = h->avctx;
87 const AVFrame *src = h->cur_pic.f;
88 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
89 int vshift = desc->log2_chroma_h;
90 const int field_pic = h->picture_structure != PICT_FRAME;
96 height = FFMIN(height, avctx->height - y);
98 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
101 if (avctx->draw_horiz_band) {
102 int offset[AV_NUM_DATA_POINTERS];
105 offset[0] = y * src->linesize[0];
107 offset[2] = (y >> vshift) * src->linesize[1];
108 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
113 avctx->draw_horiz_band(avctx, src, offset,
114 y, h->picture_structure, height);
118 const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
120 int *dst_length, int *consumed, int length)
125 // src[0]&0x80; // forbidden bit
126 h->nal_ref_idc = src[0] >> 5;
127 h->nal_unit_type = src[0] & 0x1F;
132 #define STARTCODE_TEST \
133 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
134 if (src[i + 2] != 3) { \
135 /* startcode, so we must be past the end */ \
141 #if HAVE_FAST_UNALIGNED
142 #define FIND_FIRST_ZERO \
143 if (i > 0 && !src[i]) \
149 for (i = 0; i + 1 < length; i += 9) {
150 if (!((~AV_RN64A(src + i) &
151 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
152 0x8000800080008080ULL))
159 for (i = 0; i + 1 < length; i += 5) {
160 if (!((~AV_RN32A(src + i) &
161 (AV_RN32A(src + i) - 0x01000101U)) &
170 for (i = 0; i + 1 < length; i += 2) {
173 if (i > 0 && src[i - 1] == 0)
179 if (i >= length - 1) { // no escaped 0
180 *dst_length = length;
181 *consumed = length + 1; // +1 for the header
185 av_fast_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size,
186 length + AV_INPUT_BUFFER_PADDING_SIZE);
187 dst = sl->rbsp_buffer;
194 while (si + 2 < length) {
195 // remove escapes (very rare 1:2^22)
196 if (src[si + 2] > 3) {
197 dst[di++] = src[si++];
198 dst[di++] = src[si++];
199 } else if (src[si] == 0 && src[si + 1] == 0) {
200 if (src[si + 2] == 3) { // escape
205 } else // next start code
209 dst[di++] = src[si++];
212 dst[di++] = src[si++];
215 memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
218 *consumed = si + 1; // +1 for the header
219 /* FIXME store exact number of bits in the getbitcontext
220 * (it is needed for decoding) */
225 * Identify the exact end of the bitstream
226 * @return the length of the trailing, or 0 if damaged
228 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
233 ff_tlog(h->avctx, "rbsp trailing %X\n", v);
235 for (r = 1; r < 9; r++) {
243 void ff_h264_free_tables(H264Context *h)
247 av_freep(&h->intra4x4_pred_mode);
248 av_freep(&h->chroma_pred_mode_table);
249 av_freep(&h->cbp_table);
250 av_freep(&h->mvd_table[0]);
251 av_freep(&h->mvd_table[1]);
252 av_freep(&h->direct_table);
253 av_freep(&h->non_zero_count);
254 av_freep(&h->slice_table_base);
255 h->slice_table = NULL;
256 av_freep(&h->list_counts);
258 av_freep(&h->mb2b_xy);
259 av_freep(&h->mb2br_xy);
261 av_buffer_pool_uninit(&h->qscale_table_pool);
262 av_buffer_pool_uninit(&h->mb_type_pool);
263 av_buffer_pool_uninit(&h->motion_val_pool);
264 av_buffer_pool_uninit(&h->ref_index_pool);
266 for (i = 0; i < h->nb_slice_ctx; i++) {
267 H264SliceContext *sl = &h->slice_ctx[i];
269 av_freep(&sl->dc_val_base);
270 av_freep(&sl->er.mb_index2xy);
271 av_freep(&sl->er.error_status_table);
272 av_freep(&sl->er.er_temp_buffer);
274 av_freep(&sl->bipred_scratchpad);
275 av_freep(&sl->edge_emu_buffer);
276 av_freep(&sl->top_borders[0]);
277 av_freep(&sl->top_borders[1]);
279 sl->bipred_scratchpad_allocated = 0;
280 sl->edge_emu_buffer_allocated = 0;
281 sl->top_borders_allocated[0] = 0;
282 sl->top_borders_allocated[1] = 0;
286 int ff_h264_alloc_tables(H264Context *h)
288 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
289 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
292 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
293 row_mb_num * 8 * sizeof(uint8_t), fail)
294 h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
296 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
297 big_mb_num * 48 * sizeof(uint8_t), fail)
298 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
299 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
300 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
301 big_mb_num * sizeof(uint16_t), fail)
302 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
303 big_mb_num * sizeof(uint8_t), fail)
304 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
305 16 * row_mb_num * sizeof(uint8_t), fail);
306 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
307 16 * row_mb_num * sizeof(uint8_t), fail);
308 h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
309 h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
311 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
312 4 * big_mb_num * sizeof(uint8_t), fail);
313 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
314 big_mb_num * sizeof(uint8_t), fail)
316 memset(h->slice_table_base, -1,
317 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
318 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
320 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
321 big_mb_num * sizeof(uint32_t), fail);
322 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
323 big_mb_num * sizeof(uint32_t), fail);
324 for (y = 0; y < h->mb_height; y++)
325 for (x = 0; x < h->mb_width; x++) {
326 const int mb_xy = x + y * h->mb_stride;
327 const int b_xy = 4 * x + 4 * y * h->b_stride;
329 h->mb2b_xy[mb_xy] = b_xy;
330 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
333 if (!h->dequant4_coeff[0])
334 h264_init_dequant_tables(h);
339 ff_h264_free_tables(h);
340 return AVERROR(ENOMEM);
345 * Allocate buffers which are not shared amongst multiple threads.
347 int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
349 ERContext *er = &sl->er;
350 int mb_array_size = h->mb_height * h->mb_stride;
351 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
352 int c_size = h->mb_stride * (h->mb_height + 1);
353 int yc_size = y_size + 2 * c_size;
356 sl->ref_cache[0][scan8[5] + 1] =
357 sl->ref_cache[0][scan8[7] + 1] =
358 sl->ref_cache[0][scan8[13] + 1] =
359 sl->ref_cache[1][scan8[5] + 1] =
360 sl->ref_cache[1][scan8[7] + 1] =
361 sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
363 if (CONFIG_ERROR_RESILIENCE) {
365 er->avctx = h->avctx;
366 er->decode_mb = h264_er_decode_mb;
368 er->quarter_sample = 1;
370 er->mb_num = h->mb_num;
371 er->mb_width = h->mb_width;
372 er->mb_height = h->mb_height;
373 er->mb_stride = h->mb_stride;
374 er->b8_stride = h->mb_width * 2 + 1;
376 // error resilience code looks cleaner with this
377 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
378 (h->mb_num + 1) * sizeof(int), fail);
380 for (y = 0; y < h->mb_height; y++)
381 for (x = 0; x < h->mb_width; x++)
382 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
384 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
385 h->mb_stride + h->mb_width;
387 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
388 mb_array_size * sizeof(uint8_t), fail);
390 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
391 h->mb_height * h->mb_stride, fail);
393 FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
394 yc_size * sizeof(int16_t), fail);
395 er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
396 er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
397 er->dc_val[2] = er->dc_val[1] + c_size;
398 for (i = 0; i < yc_size; i++)
399 sl->dc_val_base[i] = 1024;
405 return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
408 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
409 int parse_extradata);
411 /* There are (invalid) samples in the wild with mp4-style extradata, where the
412 * parameter sets are stored unescaped (i.e. as RBSP).
413 * This function catches the parameter set decoding failure and tries again
414 * after escaping it */
415 static int decode_extradata_ps_mp4(H264Context *h, const uint8_t *buf, int buf_size)
419 ret = decode_nal_units(h, buf, buf_size, 1);
420 if (ret < 0 && !(h->avctx->err_recognition & AV_EF_EXPLODE)) {
423 uint8_t *escaped_buf;
424 int escaped_buf_size;
426 av_log(h->avctx, AV_LOG_WARNING,
427 "SPS decoding failure, trying again after escaping the NAL\n");
429 if (buf_size / 2 >= (INT16_MAX - AV_INPUT_BUFFER_PADDING_SIZE) / 3)
430 return AVERROR(ERANGE);
431 escaped_buf_size = buf_size * 3 / 2 + AV_INPUT_BUFFER_PADDING_SIZE;
432 escaped_buf = av_mallocz(escaped_buf_size);
434 return AVERROR(ENOMEM);
436 bytestream2_init(&gbc, buf, buf_size);
437 bytestream2_init_writer(&pbc, escaped_buf, escaped_buf_size);
439 while (bytestream2_get_bytes_left(&gbc)) {
440 if (bytestream2_get_bytes_left(&gbc) >= 3 &&
441 bytestream2_peek_be24(&gbc) <= 3) {
442 bytestream2_put_be24(&pbc, 3);
443 bytestream2_skip(&gbc, 2);
445 bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));
448 escaped_buf_size = bytestream2_tell_p(&pbc);
449 AV_WB16(escaped_buf, escaped_buf_size - 2);
451 ret = decode_nal_units(h, escaped_buf, escaped_buf_size, 1);
452 av_freep(&escaped_buf);
460 int ff_h264_decode_extradata(H264Context *h)
462 AVCodecContext *avctx = h->avctx;
465 if (avctx->extradata[0] == 1) {
467 unsigned char *p = avctx->extradata;
471 if (avctx->extradata_size < 7) {
472 av_log(avctx, AV_LOG_ERROR,
473 "avcC %d too short\n", avctx->extradata_size);
474 return AVERROR_INVALIDDATA;
476 /* sps and pps in the avcC always have length coded with 2 bytes,
477 * so put a fake nal_length_size = 2 while parsing them */
478 h->nal_length_size = 2;
479 // Decode sps from avcC
480 cnt = *(p + 5) & 0x1f; // Number of sps
482 for (i = 0; i < cnt; i++) {
483 nalsize = AV_RB16(p) + 2;
484 if (p - avctx->extradata + nalsize > avctx->extradata_size)
485 return AVERROR_INVALIDDATA;
486 ret = decode_extradata_ps_mp4(h, p, nalsize);
488 av_log(avctx, AV_LOG_ERROR,
489 "Decoding sps %d from avcC failed\n", i);
494 // Decode pps from avcC
495 cnt = *(p++); // Number of pps
496 for (i = 0; i < cnt; i++) {
497 nalsize = AV_RB16(p) + 2;
498 if (p - avctx->extradata + nalsize > avctx->extradata_size)
499 return AVERROR_INVALIDDATA;
500 ret = decode_extradata_ps_mp4(h, p, nalsize);
502 av_log(avctx, AV_LOG_ERROR,
503 "Decoding pps %d from avcC failed\n", i);
508 // Store right nal length size that will be used to parse all other nals
509 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
512 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
519 static int h264_init_context(AVCodecContext *avctx, H264Context *h)
524 h->dequant_coeff_pps = -1;
526 h->picture_structure = PICT_FRAME;
527 h->slice_context_count = 1;
528 h->workaround_bugs = avctx->workaround_bugs;
529 h->flags = avctx->flags;
530 h->prev_poc_msb = 1 << 16;
532 h->recovery_frame = -1;
533 h->frame_recovered = 0;
535 h->next_outputed_poc = INT_MIN;
536 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
537 h->last_pocs[i] = INT_MIN;
539 ff_h264_reset_sei(h);
541 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
543 h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
544 h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
547 return AVERROR(ENOMEM);
550 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
551 h->DPB[i].f = av_frame_alloc();
553 return AVERROR(ENOMEM);
556 h->cur_pic.f = av_frame_alloc();
558 return AVERROR(ENOMEM);
560 for (i = 0; i < h->nb_slice_ctx; i++)
561 h->slice_ctx[i].h264 = h;
566 static AVOnce h264_vlc_init = AV_ONCE_INIT;
568 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
570 H264Context *h = avctx->priv_data;
573 ret = h264_init_context(avctx, h);
578 if (!avctx->has_b_frames)
581 ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
583 av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
584 return AVERROR_UNKNOWN;
587 if (avctx->codec_id == AV_CODEC_ID_H264) {
588 if (avctx->ticks_per_frame == 1)
589 h->avctx->framerate.num *= 2;
590 avctx->ticks_per_frame = 2;
593 if (avctx->extradata_size > 0 && avctx->extradata) {
594 ret = ff_h264_decode_extradata(h);
596 ff_h264_free_context(h);
601 if (h->sps.bitstream_restriction_flag &&
602 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
603 h->avctx->has_b_frames = h->sps.num_reorder_frames;
607 avctx->internal->allocate_progress = 1;
610 av_log(avctx, AV_LOG_WARNING,
611 "Error resilience is enabled. It is unsafe and unsupported and may crash. "
612 "Use it at your own risk\n");
618 static int decode_init_thread_copy(AVCodecContext *avctx)
620 H264Context *h = avctx->priv_data;
623 if (!avctx->internal->is_copy)
626 memset(h, 0, sizeof(*h));
628 ret = h264_init_context(avctx, h);
632 h->context_initialized = 0;
638 * Run setup operations that must be run after slice header decoding.
639 * This includes finding the next displayed frame.
641 * @param h h264 master context
642 * @param setup_finished enough NALs have been read that we can call
643 * ff_thread_finish_setup()
645 static void decode_postinit(H264Context *h, int setup_finished)
647 H264Picture *out = h->cur_pic_ptr;
648 H264Picture *cur = h->cur_pic_ptr;
649 int i, pics, out_of_order, out_idx;
650 int invalid = 0, cnt = 0;
652 h->cur_pic_ptr->f->pict_type = h->pict_type;
654 if (h->next_output_pic)
657 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
658 /* FIXME: if we have two PAFF fields in one packet, we can't start
659 * the next thread here. If we have one field per packet, we can.
660 * The check in decode_nal_units() is not good enough to find this
661 * yet, so we assume the worst for now. */
662 // if (setup_finished)
663 // ff_thread_finish_setup(h->avctx);
667 cur->f->interlaced_frame = 0;
668 cur->f->repeat_pict = 0;
670 /* Signal interlacing information externally. */
671 /* Prioritize picture timing SEI information over used
672 * decoding process if it exists. */
674 if (h->sps.pic_struct_present_flag) {
675 switch (h->sei_pic_struct) {
676 case SEI_PIC_STRUCT_FRAME:
678 case SEI_PIC_STRUCT_TOP_FIELD:
679 case SEI_PIC_STRUCT_BOTTOM_FIELD:
680 cur->f->interlaced_frame = 1;
682 case SEI_PIC_STRUCT_TOP_BOTTOM:
683 case SEI_PIC_STRUCT_BOTTOM_TOP:
684 if (FIELD_OR_MBAFF_PICTURE(h))
685 cur->f->interlaced_frame = 1;
687 // try to flag soft telecine progressive
688 cur->f->interlaced_frame = h->prev_interlaced_frame;
690 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
691 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
692 /* Signal the possibility of telecined film externally
693 * (pic_struct 5,6). From these hints, let the applications
694 * decide if they apply deinterlacing. */
695 cur->f->repeat_pict = 1;
697 case SEI_PIC_STRUCT_FRAME_DOUBLING:
698 cur->f->repeat_pict = 2;
700 case SEI_PIC_STRUCT_FRAME_TRIPLING:
701 cur->f->repeat_pict = 4;
705 if ((h->sei_ct_type & 3) &&
706 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
707 cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
709 /* Derive interlacing flag from used decoding process. */
710 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
712 h->prev_interlaced_frame = cur->f->interlaced_frame;
714 if (cur->field_poc[0] != cur->field_poc[1]) {
715 /* Derive top_field_first from field pocs. */
716 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
718 if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
719 /* Use picture timing SEI information. Even if it is a
720 * information of a past frame, better than nothing. */
721 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
722 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
723 cur->f->top_field_first = 1;
725 cur->f->top_field_first = 0;
727 /* Most likely progressive */
728 cur->f->top_field_first = 0;
732 if (h->sei_frame_packing_present &&
733 h->frame_packing_arrangement_type >= 0 &&
734 h->frame_packing_arrangement_type <= 6 &&
735 h->content_interpretation_type > 0 &&
736 h->content_interpretation_type < 3) {
737 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
741 switch (h->frame_packing_arrangement_type) {
743 stereo->type = AV_STEREO3D_CHECKERBOARD;
746 stereo->type = AV_STEREO3D_COLUMNS;
749 stereo->type = AV_STEREO3D_LINES;
752 if (h->quincunx_subsampling)
753 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
755 stereo->type = AV_STEREO3D_SIDEBYSIDE;
758 stereo->type = AV_STEREO3D_TOPBOTTOM;
761 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
764 stereo->type = AV_STEREO3D_2D;
768 if (h->content_interpretation_type == 2)
769 stereo->flags = AV_STEREO3D_FLAG_INVERT;
772 if (h->sei_display_orientation_present &&
773 (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
774 double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
775 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
776 AV_FRAME_DATA_DISPLAYMATRIX,
777 sizeof(int32_t) * 9);
781 av_display_rotation_set((int32_t *)rotation->data, angle);
782 av_display_matrix_flip((int32_t *)rotation->data,
783 h->sei_hflip, h->sei_vflip);
786 if (h->sei_reguserdata_afd_present) {
787 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
792 *sd->data = h->active_format_description;
793 h->sei_reguserdata_afd_present = 0;
796 if (h->a53_caption) {
797 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
798 AV_FRAME_DATA_A53_CC,
799 h->a53_caption_size);
803 memcpy(sd->data, h->a53_caption, h->a53_caption_size);
804 av_freep(&h->a53_caption);
805 h->a53_caption_size = 0;
808 // FIXME do something with unavailable reference frames
810 /* Sort B-frames into display order */
811 if (h->sps.bitstream_restriction_flag ||
812 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
813 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
815 h->low_delay = !h->avctx->has_b_frames;
818 while (h->delayed_pic[pics])
821 assert(pics <= MAX_DELAYED_PIC_COUNT);
823 h->delayed_pic[pics++] = cur;
824 if (cur->reference == 0)
825 cur->reference = DELAYED_PIC_REF;
827 /* Frame reordering. This code takes pictures from coding order and sorts
828 * them by their incremental POC value into display order. It supports POC
829 * gaps, MMCO reset codes and random resets.
830 * A "display group" can start either with a IDR frame (f.key_frame = 1),
831 * and/or can be closed down with a MMCO reset code. In sequences where
832 * there is no delay, we can't detect that (since the frame was already
833 * output to the user), so we also set h->mmco_reset to detect the MMCO
835 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
836 * we increase the delay between input and output. All frames affected by
837 * the lag (e.g. those that should have been output before another frame
838 * that we already returned to the user) will be dropped. This is a bug
839 * that we will fix later. */
840 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
841 cnt += out->poc < h->last_pocs[i];
842 invalid += out->poc == INT_MIN;
844 if (!h->mmco_reset && !cur->f->key_frame &&
845 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
848 h->delayed_pic[pics - 2]->mmco_reset = 2;
850 if (h->mmco_reset || cur->f->key_frame) {
851 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
852 h->last_pocs[i] = INT_MIN;
854 invalid = MAX_DELAYED_PIC_COUNT;
856 out = h->delayed_pic[0];
858 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
860 !h->delayed_pic[i - 1]->mmco_reset &&
861 !h->delayed_pic[i]->f->key_frame;
863 if (h->delayed_pic[i]->poc < out->poc) {
864 out = h->delayed_pic[i];
867 if (h->avctx->has_b_frames == 0 &&
868 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
869 h->next_outputed_poc = INT_MIN;
870 out_of_order = !out->f->key_frame && !h->mmco_reset &&
871 (out->poc < h->next_outputed_poc);
873 if (h->sps.bitstream_restriction_flag &&
874 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
875 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
876 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
877 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
878 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
881 } else if (h->low_delay &&
882 ((h->next_outputed_poc != INT_MIN &&
883 out->poc > h->next_outputed_poc + 2) ||
884 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
886 h->avctx->has_b_frames++;
889 if (pics > h->avctx->has_b_frames) {
890 out->reference &= ~DELAYED_PIC_REF;
891 // for frame threading, the owner must be the second field's thread or
892 // else the first thread can release the picture and reuse it unsafely
893 for (i = out_idx; h->delayed_pic[i]; i++)
894 h->delayed_pic[i] = h->delayed_pic[i + 1];
896 memmove(h->last_pocs, &h->last_pocs[1],
897 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
898 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
899 if (!out_of_order && pics > h->avctx->has_b_frames) {
900 h->next_output_pic = out;
901 if (out->mmco_reset) {
903 h->next_outputed_poc = out->poc;
904 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
906 h->next_outputed_poc = INT_MIN;
909 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
910 h->next_outputed_poc = INT_MIN;
912 h->next_outputed_poc = out->poc;
917 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
920 if (h->next_output_pic) {
921 if (h->next_output_pic->recovered) {
922 // We have reached an recovery point and all frames after it in
923 // display order are "recovered".
924 h->frame_recovered |= FRAME_RECOVERED_SEI;
926 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
929 if (setup_finished && !h->avctx->hwaccel) {
930 ff_thread_finish_setup(h->avctx);
932 if (h->avctx->active_thread_type & FF_THREAD_FRAME)
933 h->setup_finished = 1;
938 * instantaneous decoder refresh.
940 static void idr(H264Context *h)
942 ff_h264_remove_all_refs(h);
944 h->prev_frame_num_offset =
949 /* forget old pics after a seek */
950 void ff_h264_flush_change(H264Context *h)
953 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
954 h->last_pocs[i] = INT_MIN;
955 h->next_outputed_poc = INT_MIN;
956 h->prev_interlaced_frame = 1;
959 h->cur_pic_ptr->reference = 0;
961 ff_h264_reset_sei(h);
962 h->recovery_frame = -1;
963 h->frame_recovered = 0;
966 /* forget old pics after a seek */
967 static void flush_dpb(AVCodecContext *avctx)
969 H264Context *h = avctx->priv_data;
972 memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
974 ff_h264_flush_change(h);
976 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
977 ff_h264_unref_picture(h, &h->DPB[i]);
978 h->cur_pic_ptr = NULL;
979 ff_h264_unref_picture(h, &h->cur_pic);
983 ff_h264_free_tables(h);
984 h->context_initialized = 0;
987 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
989 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
992 h->frame_num_offset = h->prev_frame_num_offset;
993 if (h->frame_num < h->prev_frame_num)
994 h->frame_num_offset += max_frame_num;
996 if (h->sps.poc_type == 0) {
997 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
999 if (h->poc_lsb < h->prev_poc_lsb &&
1000 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
1001 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
1002 else if (h->poc_lsb > h->prev_poc_lsb &&
1003 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
1004 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
1006 h->poc_msb = h->prev_poc_msb;
1008 field_poc[1] = h->poc_msb + h->poc_lsb;
1009 if (h->picture_structure == PICT_FRAME)
1010 field_poc[1] += h->delta_poc_bottom;
1011 } else if (h->sps.poc_type == 1) {
1012 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
1015 if (h->sps.poc_cycle_length != 0)
1016 abs_frame_num = h->frame_num_offset + h->frame_num;
1020 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
1023 expected_delta_per_poc_cycle = 0;
1024 for (i = 0; i < h->sps.poc_cycle_length; i++)
1025 // FIXME integrate during sps parse
1026 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
1028 if (abs_frame_num > 0) {
1029 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
1030 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
1032 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
1033 for (i = 0; i <= frame_num_in_poc_cycle; i++)
1034 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
1038 if (h->nal_ref_idc == 0)
1039 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
1041 field_poc[0] = expectedpoc + h->delta_poc[0];
1042 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
1044 if (h->picture_structure == PICT_FRAME)
1045 field_poc[1] += h->delta_poc[1];
1047 int poc = 2 * (h->frame_num_offset + h->frame_num);
1049 if (!h->nal_ref_idc)
1056 if (h->picture_structure != PICT_BOTTOM_FIELD)
1057 pic_field_poc[0] = field_poc[0];
1058 if (h->picture_structure != PICT_TOP_FIELD)
1059 pic_field_poc[1] = field_poc[1];
1060 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
1066 * Compute profile from profile_idc and constraint_set?_flags.
1070 * @return profile as defined by FF_PROFILE_H264_*
1072 int ff_h264_get_profile(SPS *sps)
1074 int profile = sps->profile_idc;
1076 switch (sps->profile_idc) {
1077 case FF_PROFILE_H264_BASELINE:
1078 // constraint_set1_flag set to 1
1079 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
1081 case FF_PROFILE_H264_HIGH_10:
1082 case FF_PROFILE_H264_HIGH_422:
1083 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
1084 // constraint_set3_flag set to 1
1085 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
1092 int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
1094 int ref_count[2], list_count;
1095 int num_ref_idx_active_override_flag, max_refs;
1097 // set defaults, might be overridden a few lines later
1098 ref_count[0] = h->pps.ref_count[0];
1099 ref_count[1] = h->pps.ref_count[1];
1101 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1102 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1103 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1104 num_ref_idx_active_override_flag = get_bits1(&sl->gb);
1106 if (num_ref_idx_active_override_flag) {
1107 ref_count[0] = get_ue_golomb(&sl->gb) + 1;
1108 if (ref_count[0] < 1)
1109 return AVERROR_INVALIDDATA;
1110 if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1111 ref_count[1] = get_ue_golomb(&sl->gb) + 1;
1112 if (ref_count[1] < 1)
1113 return AVERROR_INVALIDDATA;
1117 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1123 ref_count[0] = ref_count[1] = 0;
1126 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
1128 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
1129 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
1130 sl->ref_count[0] = sl->ref_count[1] = 0;
1131 return AVERROR_INVALIDDATA;
1134 if (list_count != sl->list_count ||
1135 ref_count[0] != sl->ref_count[0] ||
1136 ref_count[1] != sl->ref_count[1]) {
1137 sl->ref_count[0] = ref_count[0];
1138 sl->ref_count[1] = ref_count[1];
1139 sl->list_count = list_count;
1146 static int find_start_code(const uint8_t *buf, int buf_size,
1147 int buf_index, int next_avc)
1149 // start code prefix search
1150 for (; buf_index + 3 < next_avc; buf_index++)
1151 // This should always succeed in the first iteration.
1152 if (buf[buf_index] == 0 &&
1153 buf[buf_index + 1] == 0 &&
1154 buf[buf_index + 2] == 1)
1157 if (buf_index + 3 >= buf_size)
1160 return buf_index + 3;
1163 static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
1164 int buf_size, int *buf_index)
1168 if (*buf_index >= buf_size - h->nal_length_size) {
1169 // the end of the buffer is reached, refill it.
1170 return AVERROR(EAGAIN);
1173 for (i = 0; i < h->nal_length_size; i++)
1174 nalsize = (nalsize << 8) | buf[(*buf_index)++];
1175 if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
1176 av_log(h->avctx, AV_LOG_ERROR,
1177 "AVC: nal size %d\n", nalsize);
1178 return AVERROR_INVALIDDATA;
1183 static int get_bit_length(H264Context *h, const uint8_t *buf,
1184 const uint8_t *ptr, int dst_length,
1185 int i, int next_avc)
1187 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
1188 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
1189 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
1190 h->workaround_bugs |= FF_BUG_TRUNCATED;
1192 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
1193 while (dst_length > 0 && ptr[dst_length - 1] == 0)
1199 return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
1202 static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
1204 int next_avc = h->is_avc ? 0 : buf_size;
1207 int nals_needed = 0;
1212 int dst_length, bit_length, consumed;
1215 if (buf_index >= next_avc) {
1216 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1219 next_avc = buf_index + nalsize;
1221 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1222 if (buf_index >= buf_size)
1226 ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
1227 next_avc - buf_index);
1229 if (!ptr || dst_length < 0)
1230 return AVERROR_INVALIDDATA;
1232 buf_index += consumed;
1234 bit_length = get_bit_length(h, buf, ptr, dst_length,
1235 buf_index, next_avc);
1238 /* packets can sometimes contain multiple PPS/SPS,
1239 * e.g. two PAFF field pictures in one packet, or a demuxer
1240 * which splits NALs strangely if so, when frame threading we
1241 * can't start the next thread until we've read all of them */
1242 switch (h->nal_unit_type) {
1245 nals_needed = nal_index;
1250 init_get_bits(&gb, ptr, bit_length);
1251 if (!get_ue_golomb(&gb))
1252 nals_needed = nal_index;
1259 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1260 int parse_extradata)
1262 AVCodecContext *const avctx = h->avctx;
1263 H264SliceContext *sl;
1265 unsigned context_count;
1267 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
1271 h->max_contexts = h->slice_context_count;
1272 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
1273 h->current_slice = 0;
1274 if (!h->first_field)
1275 h->cur_pic_ptr = NULL;
1276 ff_h264_reset_sei(h);
1279 if (avctx->active_thread_type & FF_THREAD_FRAME)
1280 nals_needed = get_last_needed_nal(h, buf, buf_size);
1285 next_avc = h->is_avc ? 0 : buf_size;
1295 if (buf_index >= next_avc) {
1296 nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
1299 next_avc = buf_index + nalsize;
1301 buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
1302 if (buf_index >= buf_size)
1304 if (buf_index >= next_avc)
1308 sl = &h->slice_ctx[context_count];
1310 ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
1311 &consumed, next_avc - buf_index);
1312 if (!ptr || dst_length < 0) {
1317 bit_length = get_bit_length(h, buf, ptr, dst_length,
1318 buf_index + consumed, next_avc);
1320 if (h->avctx->debug & FF_DEBUG_STARTCODE)
1321 av_log(h->avctx, AV_LOG_DEBUG,
1322 "NAL %d at %d/%d length %d\n",
1323 h->nal_unit_type, buf_index, buf_size, dst_length);
1325 if (h->is_avc && (nalsize != consumed) && nalsize)
1326 av_log(h->avctx, AV_LOG_DEBUG,
1327 "AVC: Consumed only %d bytes instead of %d\n",
1330 buf_index += consumed;
1333 if (avctx->skip_frame >= AVDISCARD_NONREF &&
1334 h->nal_ref_idc == 0 &&
1335 h->nal_unit_type != NAL_SEI)
1339 /* Ignore every NAL unit type except PPS and SPS during extradata
1340 * parsing. Decoding slices is not possible in codec init
1342 if (parse_extradata && HAVE_THREADS &&
1343 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
1344 (h->nal_unit_type != NAL_PPS &&
1345 h->nal_unit_type != NAL_SPS)) {
1346 if (h->nal_unit_type < NAL_AUD ||
1347 h->nal_unit_type > NAL_AUXILIARY_SLICE)
1348 av_log(avctx, AV_LOG_INFO,
1349 "Ignoring NAL unit %d during extradata parsing\n",
1351 h->nal_unit_type = NAL_FF_IGNORE;
1354 switch (h->nal_unit_type) {
1356 if (h->nal_unit_type != NAL_IDR_SLICE) {
1357 av_log(h->avctx, AV_LOG_ERROR,
1358 "Invalid mix of idr and non-idr slices\n");
1362 idr(h); // FIXME ensure we don't lose some frames if there is reordering
1364 init_get_bits(&sl->gb, ptr, bit_length);
1366 if ((err = ff_h264_decode_slice_header(h, sl)))
1369 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1370 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
1371 ((1 << h->sps.log2_max_frame_num) - 1);
1374 h->cur_pic_ptr->f->key_frame |=
1375 (h->nal_unit_type == NAL_IDR_SLICE) ||
1376 (h->sei_recovery_frame_cnt >= 0);
1378 if (h->nal_unit_type == NAL_IDR_SLICE ||
1379 h->recovery_frame == h->frame_num) {
1380 h->recovery_frame = -1;
1381 h->cur_pic_ptr->recovered = 1;
1383 // If we have an IDR, all frames after it in decoded order are
1385 if (h->nal_unit_type == NAL_IDR_SLICE)
1386 h->frame_recovered |= FRAME_RECOVERED_IDR;
1387 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1389 if (h->current_slice == 1) {
1390 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
1391 decode_postinit(h, nal_index >= nals_needed);
1393 if (h->avctx->hwaccel &&
1394 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
1398 if (sl->redundant_pic_count == 0 &&
1399 (avctx->skip_frame < AVDISCARD_NONREF ||
1401 (avctx->skip_frame < AVDISCARD_BIDIR ||
1402 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1403 (avctx->skip_frame < AVDISCARD_NONKEY ||
1404 h->cur_pic_ptr->f->key_frame) &&
1405 avctx->skip_frame < AVDISCARD_ALL) {
1406 if (avctx->hwaccel) {
1407 ret = avctx->hwaccel->decode_slice(avctx,
1408 &buf[buf_index - consumed],
1419 avpriv_request_sample(avctx, "data partitioning");
1420 ret = AVERROR(ENOSYS);
1424 init_get_bits(&h->gb, ptr, bit_length);
1425 ret = ff_h264_decode_sei(h);
1426 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1430 init_get_bits(&h->gb, ptr, bit_length);
1431 ret = ff_h264_decode_seq_parameter_set(h);
1432 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1436 init_get_bits(&h->gb, ptr, bit_length);
1437 ret = ff_h264_decode_picture_parameter_set(h, bit_length);
1438 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1442 case NAL_END_SEQUENCE:
1443 case NAL_END_STREAM:
1444 case NAL_FILLER_DATA:
1446 case NAL_AUXILIARY_SLICE:
1451 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
1452 h->nal_unit_type, bit_length);
1455 if (context_count == h->max_contexts) {
1456 ret = ff_h264_execute_decode_slices(h, context_count);
1457 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1463 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
1464 sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
1465 } else if (err == 1) {
1466 /* Slice could not be decoded in parallel mode, restart. Note
1467 * that rbsp_buffer is not transferred, but since we no longer
1468 * run in parallel mode this should not be an issue. */
1469 sl = &h->slice_ctx[0];
1474 if (context_count) {
1475 ret = ff_h264_execute_decode_slices(h, context_count);
1476 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1483 if (h->cur_pic_ptr && !h->droppable) {
1484 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1485 h->picture_structure == PICT_BOTTOM_FIELD);
1488 return (ret < 0) ? ret : buf_index;
1492 * Return the number of bytes consumed for building the current frame.
1494 static int get_consumed_bytes(int pos, int buf_size)
1497 pos = 1; // avoid infinite loops (I doubt that is needed but...)
1498 if (pos + 10 > buf_size)
1499 pos = buf_size; // oops ;)
1504 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
1507 int ret = av_frame_ref(dst, src);
1514 for (i = 0; i < 3; i++) {
1515 int hshift = (i > 0) ? h->chroma_x_shift : 0;
1516 int vshift = (i > 0) ? h->chroma_y_shift : 0;
1517 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
1518 (h->sps.crop_top >> vshift) * dst->linesize[i];
1519 dst->data[i] += off;
1524 static int h264_decode_frame(AVCodecContext *avctx, void *data,
1525 int *got_frame, AVPacket *avpkt)
1527 const uint8_t *buf = avpkt->data;
1528 int buf_size = avpkt->size;
1529 H264Context *h = avctx->priv_data;
1530 AVFrame *pict = data;
1534 h->flags = avctx->flags;
1535 h->setup_finished = 0;
1537 /* end of stream, output what is still in the buffers */
1539 if (buf_size == 0) {
1543 h->cur_pic_ptr = NULL;
1545 // FIXME factorize this with the output code below
1546 out = h->delayed_pic[0];
1549 h->delayed_pic[i] &&
1550 !h->delayed_pic[i]->f->key_frame &&
1551 !h->delayed_pic[i]->mmco_reset;
1553 if (h->delayed_pic[i]->poc < out->poc) {
1554 out = h->delayed_pic[i];
1558 for (i = out_idx; h->delayed_pic[i]; i++)
1559 h->delayed_pic[i] = h->delayed_pic[i + 1];
1562 ret = output_frame(h, pict, out->f);
1571 buf_index = decode_nal_units(h, buf, buf_size, 0);
1573 return AVERROR_INVALIDDATA;
1575 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
1580 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
1581 if (avctx->skip_frame >= AVDISCARD_NONREF)
1583 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
1584 return AVERROR_INVALIDDATA;
1587 if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
1588 (h->mb_y >= h->mb_height && h->mb_height)) {
1589 if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
1590 decode_postinit(h, 1);
1592 ff_h264_field_end(h, &h->slice_ctx[0], 0);
1595 if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
1596 h->next_output_pic->recovered)) {
1597 if (!h->next_output_pic->recovered)
1598 h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
1600 ret = output_frame(h, pict, h->next_output_pic->f);
1607 assert(pict->buf[0] || !*got_frame);
1609 return get_consumed_bytes(buf_index, buf_size);
1612 av_cold void ff_h264_free_context(H264Context *h)
1616 ff_h264_free_tables(h);
1618 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1619 ff_h264_unref_picture(h, &h->DPB[i]);
1620 av_frame_free(&h->DPB[i].f);
1623 h->cur_pic_ptr = NULL;
1625 for (i = 0; i < h->nb_slice_ctx; i++)
1626 av_freep(&h->slice_ctx[i].rbsp_buffer);
1627 av_freep(&h->slice_ctx);
1628 h->nb_slice_ctx = 0;
1630 for (i = 0; i < MAX_SPS_COUNT; i++)
1631 av_freep(h->sps_buffers + i);
1633 for (i = 0; i < MAX_PPS_COUNT; i++)
1634 av_freep(h->pps_buffers + i);
1637 static av_cold int h264_decode_end(AVCodecContext *avctx)
1639 H264Context *h = avctx->priv_data;
1641 ff_h264_free_context(h);
1643 ff_h264_unref_picture(h, &h->cur_pic);
1644 av_frame_free(&h->cur_pic.f);
1649 #define OFFSET(x) offsetof(H264Context, x)
1650 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1651 static const AVOption h264_options[] = {
1652 { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1656 static const AVClass h264_class = {
1657 .class_name = "h264",
1658 .item_name = av_default_item_name,
1659 .option = h264_options,
1660 .version = LIBAVUTIL_VERSION_INT,
1663 AVCodec ff_h264_decoder = {
1665 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
1666 .type = AVMEDIA_TYPE_VIDEO,
1667 .id = AV_CODEC_ID_H264,
1668 .priv_data_size = sizeof(H264Context),
1669 .init = ff_h264_decode_init,
1670 .close = h264_decode_end,
1671 .decode = h264_decode_frame,
1672 .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
1673 AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
1674 AV_CODEC_CAP_FRAME_THREADS,
1675 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
1677 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
1678 .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
1679 .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
1680 .priv_class = &h264_class,