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/imgutils.h"
31 #include "cabac_functions.h"
33 #include "error_resilience.h"
35 #include "mpegvideo.h"
38 #include "h264chroma.h"
39 #include "h264_mvpred.h"
42 #include "rectangle.h"
45 #include "vdpau_internal.h"
46 #include "libavutil/avassert.h"
51 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
53 static const uint8_t rem6[QP_MAX_NUM + 1] = {
54 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
55 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
56 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
59 static const uint8_t div6[QP_MAX_NUM + 1] = {
60 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
61 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
62 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
65 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
66 #if CONFIG_H264_DXVA2_HWACCEL
69 #if CONFIG_H264_VAAPI_HWACCEL
72 #if CONFIG_H264_VDA_HWACCEL
75 #if CONFIG_H264_VDPAU_HWACCEL
82 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
83 #if CONFIG_H264_DXVA2_HWACCEL
86 #if CONFIG_H264_VAAPI_HWACCEL
89 #if CONFIG_H264_VDA_HWACCEL
92 #if CONFIG_H264_VDPAU_HWACCEL
99 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
101 int mb_x, int mb_y, int mb_intra, int mb_skipped)
103 H264Context *h = opaque;
107 h->mb_xy = mb_x + mb_y * h->mb_stride;
108 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
110 /* FIXME: It is possible albeit uncommon that slice references
111 * differ between slices. We take the easy approach and ignore
112 * it for now. If this turns out to have any relevance in
113 * practice then correct remapping should be added. */
114 if (ref >= h->ref_count[0])
116 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
118 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
119 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
120 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
121 assert(!FRAME_MBAFF);
122 ff_h264_hl_decode_mb(h);
125 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
127 AVCodecContext *avctx = h->avctx;
128 Picture *cur = &h->cur_pic;
129 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
130 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
131 int vshift = desc->log2_chroma_h;
132 const int field_pic = h->picture_structure != PICT_FRAME;
138 height = FFMIN(height, avctx->height - y);
140 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
143 if (avctx->draw_horiz_band) {
145 int offset[AV_NUM_DATA_POINTERS];
148 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
149 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
156 offset[0] = y * src->linesize[0];
158 offset[2] = (y >> vshift) * src->linesize[1];
159 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
164 avctx->draw_horiz_band(avctx, src, offset,
165 y, h->picture_structure, height);
169 static void unref_picture(H264Context *h, Picture *pic)
171 int off = offsetof(Picture, tf) + sizeof(pic->tf);
177 ff_thread_release_buffer(h->avctx, &pic->tf);
178 av_buffer_unref(&pic->hwaccel_priv_buf);
180 av_buffer_unref(&pic->qscale_table_buf);
181 av_buffer_unref(&pic->mb_type_buf);
182 for (i = 0; i < 2; i++) {
183 av_buffer_unref(&pic->motion_val_buf[i]);
184 av_buffer_unref(&pic->ref_index_buf[i]);
187 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
190 static void release_unused_pictures(H264Context *h, int remove_current)
194 /* release non reference frames */
195 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
196 if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&
197 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
198 unref_picture(h, &h->DPB[i]);
203 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
207 av_assert0(!dst->f.buf[0]);
208 av_assert0(src->f.buf[0]);
212 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
217 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
218 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
219 if (!dst->qscale_table_buf || !dst->mb_type_buf)
221 dst->qscale_table = src->qscale_table;
222 dst->mb_type = src->mb_type;
224 for (i = 0; i < 2; i ++) {
225 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
226 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
227 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
229 dst->motion_val[i] = src->motion_val[i];
230 dst->ref_index[i] = src->ref_index[i];
233 if (src->hwaccel_picture_private) {
234 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
235 if (!dst->hwaccel_priv_buf)
237 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
240 for (i = 0; i < 2; i++)
241 dst->field_poc[i] = src->field_poc[i];
243 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
244 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
247 dst->frame_num = src->frame_num;
248 dst->mmco_reset = src->mmco_reset;
249 dst->pic_id = src->pic_id;
250 dst->long_ref = src->long_ref;
251 dst->mbaff = src->mbaff;
252 dst->field_picture = src->field_picture;
253 dst->needs_realloc = src->needs_realloc;
254 dst->reference = src->reference;
258 unref_picture(h, dst);
263 static int alloc_scratch_buffers(H264Context *h, int linesize)
265 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
267 if (h->bipred_scratchpad)
270 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
271 // edge emu needs blocksize + filter length - 1
272 // (= 21x21 for h264)
273 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
274 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
276 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
277 av_freep(&h->bipred_scratchpad);
278 av_freep(&h->edge_emu_buffer);
279 av_freep(&h->me.scratchpad);
280 return AVERROR(ENOMEM);
283 h->me.temp = h->me.scratchpad;
288 static int init_table_pools(H264Context *h)
290 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
291 const int mb_array_size = h->mb_stride * h->mb_height;
292 const int b4_stride = h->mb_width * 4 + 1;
293 const int b4_array_size = b4_stride * h->mb_height * 4;
295 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
297 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
298 sizeof(uint32_t), av_buffer_allocz);
299 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
300 sizeof(int16_t), av_buffer_allocz);
301 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
303 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
304 !h->ref_index_pool) {
305 av_buffer_pool_uninit(&h->qscale_table_pool);
306 av_buffer_pool_uninit(&h->mb_type_pool);
307 av_buffer_pool_uninit(&h->motion_val_pool);
308 av_buffer_pool_uninit(&h->ref_index_pool);
309 return AVERROR(ENOMEM);
315 static int alloc_picture(H264Context *h, Picture *pic)
319 av_assert0(!pic->f.data[0]);
321 if (h->avctx->hwaccel) {
322 const AVHWAccel *hwaccel = h->avctx->hwaccel;
323 av_assert0(!pic->hwaccel_picture_private);
324 if (hwaccel->priv_data_size) {
325 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
326 if (!pic->hwaccel_priv_buf)
327 return AVERROR(ENOMEM);
328 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
332 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
333 AV_GET_BUFFER_FLAG_REF : 0);
337 h->linesize = pic->f.linesize[0];
338 h->uvlinesize = pic->f.linesize[1];
340 if (!h->qscale_table_pool) {
341 ret = init_table_pools(h);
346 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
347 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
348 if (!pic->qscale_table_buf || !pic->mb_type_buf)
351 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
352 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
354 for (i = 0; i < 2; i++) {
355 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
356 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
357 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
360 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
361 pic->ref_index[i] = pic->ref_index_buf[i]->data;
363 pic->f.motion_subsample_log2 = 2;
367 unref_picture(h, pic);
368 return (ret < 0) ? ret : AVERROR(ENOMEM);
371 static inline int pic_is_unused(H264Context *h, Picture *pic)
373 if (pic->f.data[0] == NULL)
375 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
380 static int find_unused_picture(H264Context *h)
384 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
385 if (pic_is_unused(h, &h->DPB[i]))
388 if (i == MAX_PICTURE_COUNT)
389 return AVERROR_INVALIDDATA;
391 if (h->DPB[i].needs_realloc) {
392 h->DPB[i].needs_realloc = 0;
393 unref_picture(h, &h->DPB[i]);
400 * Check if the top & left blocks are available if needed and
401 * change the dc mode so it only uses the available blocks.
403 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
405 static const int8_t top[12] = {
406 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
408 static const int8_t left[12] = {
409 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
413 if (!(h->top_samples_available & 0x8000)) {
414 for (i = 0; i < 4; i++) {
415 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
417 av_log(h->avctx, AV_LOG_ERROR,
418 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
419 status, h->mb_x, h->mb_y);
422 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
427 if ((h->left_samples_available & 0x8888) != 0x8888) {
428 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
429 for (i = 0; i < 4; i++)
430 if (!(h->left_samples_available & mask[i])) {
431 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
433 av_log(h->avctx, AV_LOG_ERROR,
434 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
435 status, h->mb_x, h->mb_y);
438 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
444 } // FIXME cleanup like ff_h264_check_intra_pred_mode
447 * Check if the top & left blocks are available if needed and
448 * change the dc mode so it only uses the available blocks.
450 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
452 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
453 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
456 av_log(h->avctx, AV_LOG_ERROR,
457 "out of range intra chroma pred mode at %d %d\n",
462 if (!(h->top_samples_available & 0x8000)) {
465 av_log(h->avctx, AV_LOG_ERROR,
466 "top block unavailable for requested intra mode at %d %d\n",
472 if ((h->left_samples_available & 0x8080) != 0x8080) {
474 if (is_chroma && (h->left_samples_available & 0x8080)) {
475 // mad cow disease mode, aka MBAFF + constrained_intra_pred
476 mode = ALZHEIMER_DC_L0T_PRED8x8 +
477 (!(h->left_samples_available & 0x8000)) +
478 2 * (mode == DC_128_PRED8x8);
481 av_log(h->avctx, AV_LOG_ERROR,
482 "left block unavailable for requested intra mode at %d %d\n",
491 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
492 int *dst_length, int *consumed, int length)
498 // src[0]&0x80; // forbidden bit
499 h->nal_ref_idc = src[0] >> 5;
500 h->nal_unit_type = src[0] & 0x1F;
505 #define STARTCODE_TEST \
506 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
507 if (src[i + 2] != 3) { \
508 /* startcode, so we must be past the end */ \
513 #if HAVE_FAST_UNALIGNED
514 #define FIND_FIRST_ZERO \
515 if (i > 0 && !src[i]) \
520 for (i = 0; i + 1 < length; i += 9) {
521 if (!((~AV_RN64A(src + i) &
522 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
523 0x8000800080008080ULL))
530 for (i = 0; i + 1 < length; i += 5) {
531 if (!((~AV_RN32A(src + i) &
532 (AV_RN32A(src + i) - 0x01000101U)) &
541 for (i = 0; i + 1 < length; i += 2) {
544 if (i > 0 && src[i - 1] == 0)
550 if (i >= length - 1) { // no escaped 0
551 *dst_length = length;
552 *consumed = length + 1; // +1 for the header
556 // use second escape buffer for inter data
557 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
558 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
559 length + FF_INPUT_BUFFER_PADDING_SIZE);
560 dst = h->rbsp_buffer[bufidx];
567 while (si + 2 < length) {
568 // remove escapes (very rare 1:2^22)
569 if (src[si + 2] > 3) {
570 dst[di++] = src[si++];
571 dst[di++] = src[si++];
572 } else if (src[si] == 0 && src[si + 1] == 0) {
573 if (src[si + 2] == 3) { // escape
578 } else // next start code
582 dst[di++] = src[si++];
585 dst[di++] = src[si++];
588 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
591 *consumed = si + 1; // +1 for the header
592 /* FIXME store exact number of bits in the getbitcontext
593 * (it is needed for decoding) */
598 * Identify the exact end of the bitstream
599 * @return the length of the trailing, or 0 if damaged
601 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
606 tprintf(h->avctx, "rbsp trailing %X\n", v);
608 for (r = 1; r < 9; r++) {
616 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
617 int height, int y_offset, int list)
619 int raw_my = h->mv_cache[list][scan8[n]][1];
620 int filter_height_up = (raw_my & 3) ? 2 : 0;
621 int filter_height_down = (raw_my & 3) ? 3 : 0;
622 int full_my = (raw_my >> 2) + y_offset;
623 int top = full_my - filter_height_up;
624 int bottom = full_my + filter_height_down + height;
626 return FFMAX(abs(top), bottom);
629 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
630 int height, int y_offset, int list0,
631 int list1, int *nrefs)
635 y_offset += 16 * (h->mb_y >> MB_FIELD);
638 int ref_n = h->ref_cache[0][scan8[n]];
639 Picture *ref = &h->ref_list[0][ref_n];
641 // Error resilience puts the current picture in the ref list.
642 // Don't try to wait on these as it will cause a deadlock.
643 // Fields can wait on each other, though.
644 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
645 (ref->reference & 3) != h->picture_structure) {
646 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
647 if (refs[0][ref_n] < 0)
649 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
654 int ref_n = h->ref_cache[1][scan8[n]];
655 Picture *ref = &h->ref_list[1][ref_n];
657 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
658 (ref->reference & 3) != h->picture_structure) {
659 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
660 if (refs[1][ref_n] < 0)
662 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
668 * Wait until all reference frames are available for MC operations.
670 * @param h the H264 context
672 static void await_references(H264Context *h)
674 const int mb_xy = h->mb_xy;
675 const int mb_type = h->cur_pic.mb_type[mb_xy];
677 int nrefs[2] = { 0 };
680 memset(refs, -1, sizeof(refs));
682 if (IS_16X16(mb_type)) {
683 get_lowest_part_y(h, refs, 0, 16, 0,
684 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
685 } else if (IS_16X8(mb_type)) {
686 get_lowest_part_y(h, refs, 0, 8, 0,
687 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
688 get_lowest_part_y(h, refs, 8, 8, 8,
689 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
690 } else if (IS_8X16(mb_type)) {
691 get_lowest_part_y(h, refs, 0, 16, 0,
692 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
693 get_lowest_part_y(h, refs, 4, 16, 0,
694 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
698 assert(IS_8X8(mb_type));
700 for (i = 0; i < 4; i++) {
701 const int sub_mb_type = h->sub_mb_type[i];
703 int y_offset = (i & 2) << 2;
705 if (IS_SUB_8X8(sub_mb_type)) {
706 get_lowest_part_y(h, refs, n, 8, y_offset,
707 IS_DIR(sub_mb_type, 0, 0),
708 IS_DIR(sub_mb_type, 0, 1),
710 } else if (IS_SUB_8X4(sub_mb_type)) {
711 get_lowest_part_y(h, refs, n, 4, y_offset,
712 IS_DIR(sub_mb_type, 0, 0),
713 IS_DIR(sub_mb_type, 0, 1),
715 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
716 IS_DIR(sub_mb_type, 0, 0),
717 IS_DIR(sub_mb_type, 0, 1),
719 } else if (IS_SUB_4X8(sub_mb_type)) {
720 get_lowest_part_y(h, refs, n, 8, y_offset,
721 IS_DIR(sub_mb_type, 0, 0),
722 IS_DIR(sub_mb_type, 0, 1),
724 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
725 IS_DIR(sub_mb_type, 0, 0),
726 IS_DIR(sub_mb_type, 0, 1),
730 assert(IS_SUB_4X4(sub_mb_type));
731 for (j = 0; j < 4; j++) {
732 int sub_y_offset = y_offset + 2 * (j & 2);
733 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
734 IS_DIR(sub_mb_type, 0, 0),
735 IS_DIR(sub_mb_type, 0, 1),
742 for (list = h->list_count - 1; list >= 0; list--)
743 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
744 int row = refs[list][ref];
746 Picture *ref_pic = &h->ref_list[list][ref];
747 int ref_field = ref_pic->reference - 1;
748 int ref_field_picture = ref_pic->field_picture;
749 int pic_height = 16 * h->mb_height >> ref_field_picture;
754 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
755 ff_thread_await_progress(&ref_pic->tf,
756 FFMIN((row >> 1) - !(row & 1),
759 ff_thread_await_progress(&ref_pic->tf,
760 FFMIN((row >> 1), pic_height - 1),
762 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
763 ff_thread_await_progress(&ref_pic->tf,
764 FFMIN(row * 2 + ref_field,
767 } else if (FIELD_PICTURE) {
768 ff_thread_await_progress(&ref_pic->tf,
769 FFMIN(row, pic_height - 1),
772 ff_thread_await_progress(&ref_pic->tf,
773 FFMIN(row, pic_height - 1),
780 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
781 int n, int square, int height,
783 uint8_t *dest_y, uint8_t *dest_cb,
785 int src_x_offset, int src_y_offset,
786 qpel_mc_func *qpix_op,
787 h264_chroma_mc_func chroma_op,
788 int pixel_shift, int chroma_idc)
790 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
791 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
792 const int luma_xy = (mx & 3) + ((my & 3) << 2);
793 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
794 uint8_t *src_y = pic->f.data[0] + offset;
795 uint8_t *src_cb, *src_cr;
797 int extra_height = 0;
799 const int full_mx = mx >> 2;
800 const int full_my = my >> 2;
801 const int pic_width = 16 * h->mb_width;
802 const int pic_height = 16 * h->mb_height >> MB_FIELD;
810 if (full_mx < 0 - extra_width ||
811 full_my < 0 - extra_height ||
812 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
813 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
814 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
815 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
817 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
818 full_my - 2, pic_width, pic_height);
819 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
823 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
825 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
827 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
830 if (chroma_idc == 3 /* yuv444 */) {
831 src_cb = pic->f.data[1] + offset;
833 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
834 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
836 16 + 5, 16 + 5 /*FIXME*/,
837 full_mx - 2, full_my - 2,
838 pic_width, pic_height);
839 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
841 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
843 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
845 src_cr = pic->f.data[2] + offset;
847 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
848 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
850 16 + 5, 16 + 5 /*FIXME*/,
851 full_mx - 2, full_my - 2,
852 pic_width, pic_height);
853 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
855 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
857 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
861 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
862 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
863 // chroma offset when predicting from a field of opposite parity
864 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
865 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
868 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
869 (my >> ysh) * h->mb_uvlinesize;
870 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
871 (my >> ysh) * h->mb_uvlinesize;
874 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
875 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
876 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
877 src_cb = h->edge_emu_buffer;
879 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
880 height >> (chroma_idc == 1 /* yuv420 */),
881 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
884 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
885 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
886 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
887 src_cr = h->edge_emu_buffer;
889 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
890 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
893 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
894 int height, int delta,
895 uint8_t *dest_y, uint8_t *dest_cb,
897 int x_offset, int y_offset,
898 qpel_mc_func *qpix_put,
899 h264_chroma_mc_func chroma_put,
900 qpel_mc_func *qpix_avg,
901 h264_chroma_mc_func chroma_avg,
902 int list0, int list1,
903 int pixel_shift, int chroma_idc)
905 qpel_mc_func *qpix_op = qpix_put;
906 h264_chroma_mc_func chroma_op = chroma_put;
908 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
909 if (chroma_idc == 3 /* yuv444 */) {
910 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
911 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
912 } else if (chroma_idc == 2 /* yuv422 */) {
913 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
914 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
915 } else { /* yuv420 */
916 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
917 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
919 x_offset += 8 * h->mb_x;
920 y_offset += 8 * (h->mb_y >> MB_FIELD);
923 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
924 mc_dir_part(h, ref, n, square, height, delta, 0,
925 dest_y, dest_cb, dest_cr, x_offset, y_offset,
926 qpix_op, chroma_op, pixel_shift, chroma_idc);
929 chroma_op = chroma_avg;
933 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
934 mc_dir_part(h, ref, n, square, height, delta, 1,
935 dest_y, dest_cb, dest_cr, x_offset, y_offset,
936 qpix_op, chroma_op, pixel_shift, chroma_idc);
940 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
941 int height, int delta,
942 uint8_t *dest_y, uint8_t *dest_cb,
944 int x_offset, int y_offset,
945 qpel_mc_func *qpix_put,
946 h264_chroma_mc_func chroma_put,
947 h264_weight_func luma_weight_op,
948 h264_weight_func chroma_weight_op,
949 h264_biweight_func luma_weight_avg,
950 h264_biweight_func chroma_weight_avg,
951 int list0, int list1,
952 int pixel_shift, int chroma_idc)
956 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
957 if (chroma_idc == 3 /* yuv444 */) {
958 chroma_height = height;
959 chroma_weight_avg = luma_weight_avg;
960 chroma_weight_op = luma_weight_op;
961 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
962 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
963 } else if (chroma_idc == 2 /* yuv422 */) {
964 chroma_height = height;
965 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
966 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
967 } else { /* yuv420 */
968 chroma_height = height >> 1;
969 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
970 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
972 x_offset += 8 * h->mb_x;
973 y_offset += 8 * (h->mb_y >> MB_FIELD);
975 if (list0 && list1) {
976 /* don't optimize for luma-only case, since B-frames usually
977 * use implicit weights => chroma too. */
978 uint8_t *tmp_cb = h->bipred_scratchpad;
979 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
980 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
981 int refn0 = h->ref_cache[0][scan8[n]];
982 int refn1 = h->ref_cache[1][scan8[n]];
984 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
985 dest_y, dest_cb, dest_cr,
986 x_offset, y_offset, qpix_put, chroma_put,
987 pixel_shift, chroma_idc);
988 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
989 tmp_y, tmp_cb, tmp_cr,
990 x_offset, y_offset, qpix_put, chroma_put,
991 pixel_shift, chroma_idc);
993 if (h->use_weight == 2) {
994 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
995 int weight1 = 64 - weight0;
996 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
997 height, 5, weight0, weight1, 0);
998 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
999 chroma_height, 5, weight0, weight1, 0);
1000 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1001 chroma_height, 5, weight0, weight1, 0);
1003 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1004 h->luma_log2_weight_denom,
1005 h->luma_weight[refn0][0][0],
1006 h->luma_weight[refn1][1][0],
1007 h->luma_weight[refn0][0][1] +
1008 h->luma_weight[refn1][1][1]);
1009 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1010 h->chroma_log2_weight_denom,
1011 h->chroma_weight[refn0][0][0][0],
1012 h->chroma_weight[refn1][1][0][0],
1013 h->chroma_weight[refn0][0][0][1] +
1014 h->chroma_weight[refn1][1][0][1]);
1015 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1016 h->chroma_log2_weight_denom,
1017 h->chroma_weight[refn0][0][1][0],
1018 h->chroma_weight[refn1][1][1][0],
1019 h->chroma_weight[refn0][0][1][1] +
1020 h->chroma_weight[refn1][1][1][1]);
1023 int list = list1 ? 1 : 0;
1024 int refn = h->ref_cache[list][scan8[n]];
1025 Picture *ref = &h->ref_list[list][refn];
1026 mc_dir_part(h, ref, n, square, height, delta, list,
1027 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1028 qpix_put, chroma_put, pixel_shift, chroma_idc);
1030 luma_weight_op(dest_y, h->mb_linesize, height,
1031 h->luma_log2_weight_denom,
1032 h->luma_weight[refn][list][0],
1033 h->luma_weight[refn][list][1]);
1034 if (h->use_weight_chroma) {
1035 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1036 h->chroma_log2_weight_denom,
1037 h->chroma_weight[refn][list][0][0],
1038 h->chroma_weight[refn][list][0][1]);
1039 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1040 h->chroma_log2_weight_denom,
1041 h->chroma_weight[refn][list][1][0],
1042 h->chroma_weight[refn][list][1][1]);
1047 static av_always_inline void prefetch_motion(H264Context *h, int list,
1048 int pixel_shift, int chroma_idc)
1050 /* fetch pixels for estimated mv 4 macroblocks ahead
1051 * optimized for 64byte cache lines */
1052 const int refn = h->ref_cache[list][scan8[0]];
1054 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1055 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1056 uint8_t **src = h->ref_list[list][refn].f.data;
1057 int off = (mx << pixel_shift) +
1058 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1059 (64 << pixel_shift);
1060 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1061 if (chroma_idc == 3 /* yuv444 */) {
1062 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1063 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1065 off = ((mx >> 1) << pixel_shift) +
1066 ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
1067 (64 << pixel_shift);
1068 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1073 static void free_tables(H264Context *h, int free_rbsp)
1078 av_freep(&h->intra4x4_pred_mode);
1079 av_freep(&h->chroma_pred_mode_table);
1080 av_freep(&h->cbp_table);
1081 av_freep(&h->mvd_table[0]);
1082 av_freep(&h->mvd_table[1]);
1083 av_freep(&h->direct_table);
1084 av_freep(&h->non_zero_count);
1085 av_freep(&h->slice_table_base);
1086 h->slice_table = NULL;
1087 av_freep(&h->list_counts);
1089 av_freep(&h->mb2b_xy);
1090 av_freep(&h->mb2br_xy);
1092 av_buffer_pool_uninit(&h->qscale_table_pool);
1093 av_buffer_pool_uninit(&h->mb_type_pool);
1094 av_buffer_pool_uninit(&h->motion_val_pool);
1095 av_buffer_pool_uninit(&h->ref_index_pool);
1097 if (free_rbsp && h->DPB) {
1098 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1099 unref_picture(h, &h->DPB[i]);
1101 } else if (h->DPB) {
1102 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1103 h->DPB[i].needs_realloc = 1;
1106 h->cur_pic_ptr = NULL;
1108 for (i = 0; i < MAX_THREADS; i++) {
1109 hx = h->thread_context[i];
1112 av_freep(&hx->top_borders[1]);
1113 av_freep(&hx->top_borders[0]);
1114 av_freep(&hx->bipred_scratchpad);
1115 av_freep(&hx->edge_emu_buffer);
1116 av_freep(&hx->dc_val_base);
1117 av_freep(&hx->me.scratchpad);
1118 av_freep(&hx->er.mb_index2xy);
1119 av_freep(&hx->er.error_status_table);
1120 av_freep(&hx->er.er_temp_buffer);
1121 av_freep(&hx->er.mbintra_table);
1122 av_freep(&hx->er.mbskip_table);
1125 av_freep(&hx->rbsp_buffer[1]);
1126 av_freep(&hx->rbsp_buffer[0]);
1127 hx->rbsp_buffer_size[0] = 0;
1128 hx->rbsp_buffer_size[1] = 0;
1131 av_freep(&h->thread_context[i]);
1135 static void init_dequant8_coeff_table(H264Context *h)
1138 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1140 for (i = 0; i < 6; i++) {
1141 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1142 for (j = 0; j < i; j++)
1143 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1144 64 * sizeof(uint8_t))) {
1145 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1151 for (q = 0; q < max_qp + 1; q++) {
1152 int shift = div6[q];
1154 for (x = 0; x < 64; x++)
1155 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1156 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1157 h->pps.scaling_matrix8[i][x]) << shift;
1162 static void init_dequant4_coeff_table(H264Context *h)
1165 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1166 for (i = 0; i < 6; i++) {
1167 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1168 for (j = 0; j < i; j++)
1169 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1170 16 * sizeof(uint8_t))) {
1171 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1177 for (q = 0; q < max_qp + 1; q++) {
1178 int shift = div6[q] + 2;
1180 for (x = 0; x < 16; x++)
1181 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1182 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1183 h->pps.scaling_matrix4[i][x]) << shift;
1188 static void init_dequant_tables(H264Context *h)
1191 init_dequant4_coeff_table(h);
1192 if (h->pps.transform_8x8_mode)
1193 init_dequant8_coeff_table(h);
1194 if (h->sps.transform_bypass) {
1195 for (i = 0; i < 6; i++)
1196 for (x = 0; x < 16; x++)
1197 h->dequant4_coeff[i][0][x] = 1 << 6;
1198 if (h->pps.transform_8x8_mode)
1199 for (i = 0; i < 6; i++)
1200 for (x = 0; x < 64; x++)
1201 h->dequant8_coeff[i][0][x] = 1 << 6;
1205 int ff_h264_alloc_tables(H264Context *h)
1207 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1208 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
1211 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1212 row_mb_num * 8 * sizeof(uint8_t), fail)
1213 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1214 big_mb_num * 48 * sizeof(uint8_t), fail)
1215 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1216 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1217 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1218 big_mb_num * sizeof(uint16_t), fail)
1219 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1220 big_mb_num * sizeof(uint8_t), fail)
1221 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1222 16 * row_mb_num * sizeof(uint8_t), fail);
1223 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1224 16 * row_mb_num * sizeof(uint8_t), fail);
1225 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1226 4 * big_mb_num * sizeof(uint8_t), fail);
1227 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1228 big_mb_num * sizeof(uint8_t), fail)
1230 memset(h->slice_table_base, -1,
1231 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1232 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1234 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1235 big_mb_num * sizeof(uint32_t), fail);
1236 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1237 big_mb_num * sizeof(uint32_t), fail);
1238 for (y = 0; y < h->mb_height; y++)
1239 for (x = 0; x < h->mb_width; x++) {
1240 const int mb_xy = x + y * h->mb_stride;
1241 const int b_xy = 4 * x + 4 * y * h->b_stride;
1243 h->mb2b_xy[mb_xy] = b_xy;
1244 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1247 if (!h->dequant4_coeff[0])
1248 init_dequant_tables(h);
1251 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1253 return AVERROR(ENOMEM);
1254 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1255 avcodec_get_frame_defaults(&h->DPB[i].f);
1256 avcodec_get_frame_defaults(&h->cur_pic.f);
1267 * Mimic alloc_tables(), but for every context thread.
1269 static void clone_tables(H264Context *dst, H264Context *src, int i)
1271 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1272 dst->non_zero_count = src->non_zero_count;
1273 dst->slice_table = src->slice_table;
1274 dst->cbp_table = src->cbp_table;
1275 dst->mb2b_xy = src->mb2b_xy;
1276 dst->mb2br_xy = src->mb2br_xy;
1277 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1278 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1279 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1280 dst->direct_table = src->direct_table;
1281 dst->list_counts = src->list_counts;
1282 dst->DPB = src->DPB;
1283 dst->cur_pic_ptr = src->cur_pic_ptr;
1284 dst->cur_pic = src->cur_pic;
1285 dst->bipred_scratchpad = NULL;
1286 dst->edge_emu_buffer = NULL;
1287 dst->me.scratchpad = NULL;
1288 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1289 src->sps.chroma_format_idc);
1294 * Allocate buffers which are not shared amongst multiple threads.
1296 static int context_init(H264Context *h)
1298 ERContext *er = &h->er;
1299 int mb_array_size = h->mb_height * h->mb_stride;
1300 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1301 int c_size = h->mb_stride * (h->mb_height + 1);
1302 int yc_size = y_size + 2 * c_size;
1305 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1306 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1307 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1308 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1310 h->ref_cache[0][scan8[5] + 1] =
1311 h->ref_cache[0][scan8[7] + 1] =
1312 h->ref_cache[0][scan8[13] + 1] =
1313 h->ref_cache[1][scan8[5] + 1] =
1314 h->ref_cache[1][scan8[7] + 1] =
1315 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1318 er->avctx = h->avctx;
1320 er->decode_mb = h264_er_decode_mb;
1322 er->quarter_sample = 1;
1324 er->mb_num = h->mb_num;
1325 er->mb_width = h->mb_width;
1326 er->mb_height = h->mb_height;
1327 er->mb_stride = h->mb_stride;
1328 er->b8_stride = h->mb_width * 2 + 1;
1330 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1331 fail); // error ressilience code looks cleaner with this
1332 for (y = 0; y < h->mb_height; y++)
1333 for (x = 0; x < h->mb_width; x++)
1334 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1336 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1337 h->mb_stride + h->mb_width;
1339 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1340 mb_array_size * sizeof(uint8_t), fail);
1342 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1343 memset(er->mbintra_table, 1, mb_array_size);
1345 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1347 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1350 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1351 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1352 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1353 er->dc_val[2] = er->dc_val[1] + c_size;
1354 for (i = 0; i < yc_size; i++)
1355 h->dc_val_base[i] = 1024;
1360 return -1; // free_tables will clean up for us
1363 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1364 int parse_extradata);
1366 static av_cold void common_init(H264Context *h)
1369 h->width = h->avctx->width;
1370 h->height = h->avctx->height;
1372 h->bit_depth_luma = 8;
1373 h->chroma_format_idc = 1;
1375 ff_h264dsp_init(&h->h264dsp, 8, 1);
1376 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1377 ff_h264qpel_init(&h->h264qpel, 8);
1378 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1380 h->dequant_coeff_pps = -1;
1382 /* needed so that IDCT permutation is known early */
1383 ff_dsputil_init(&h->dsp, h->avctx);
1384 ff_videodsp_init(&h->vdsp, 8);
1386 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1387 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1390 int ff_h264_decode_extradata(H264Context *h)
1392 AVCodecContext *avctx = h->avctx;
1394 if (avctx->extradata[0] == 1) {
1395 int i, cnt, nalsize;
1396 unsigned char *p = avctx->extradata;
1400 if (avctx->extradata_size < 7) {
1401 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1404 /* sps and pps in the avcC always have length coded with 2 bytes,
1405 * so put a fake nal_length_size = 2 while parsing them */
1406 h->nal_length_size = 2;
1407 // Decode sps from avcC
1408 cnt = *(p + 5) & 0x1f; // Number of sps
1410 for (i = 0; i < cnt; i++) {
1411 nalsize = AV_RB16(p) + 2;
1412 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1414 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1415 av_log(avctx, AV_LOG_ERROR,
1416 "Decoding sps %d from avcC failed\n", i);
1421 // Decode pps from avcC
1422 cnt = *(p++); // Number of pps
1423 for (i = 0; i < cnt; i++) {
1424 nalsize = AV_RB16(p) + 2;
1425 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1427 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1428 av_log(avctx, AV_LOG_ERROR,
1429 "Decoding pps %d from avcC failed\n", i);
1434 // Now store right nal length size, that will be used to parse all other nals
1435 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1438 if (decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1) < 0)
1444 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1446 H264Context *h = avctx->priv_data;
1452 h->picture_structure = PICT_FRAME;
1453 h->slice_context_count = 1;
1454 h->workaround_bugs = avctx->workaround_bugs;
1455 h->flags = avctx->flags;
1458 // s->decode_mb = ff_h263_decode_mb;
1459 if (!avctx->has_b_frames)
1462 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1464 ff_h264_decode_init_vlc();
1467 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1469 h->thread_context[0] = h;
1470 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1471 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1472 h->last_pocs[i] = INT_MIN;
1473 h->prev_poc_msb = 1 << 16;
1475 ff_h264_reset_sei(h);
1476 if (avctx->codec_id == AV_CODEC_ID_H264) {
1477 if (avctx->ticks_per_frame == 1)
1478 h->avctx->time_base.den *= 2;
1479 avctx->ticks_per_frame = 2;
1482 if (avctx->extradata_size > 0 && avctx->extradata &&
1483 ff_h264_decode_extradata(h))
1486 if (h->sps.bitstream_restriction_flag &&
1487 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1488 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1492 avctx->internal->allocate_progress = 1;
1497 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1498 #undef REBASE_PICTURE
1499 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1500 ((pic && pic >= old_ctx->DPB && \
1501 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1502 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1504 static void copy_picture_range(Picture **to, Picture **from, int count,
1505 H264Context *new_base,
1506 H264Context *old_base)
1510 for (i = 0; i < count; i++) {
1511 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1512 IN_RANGE(from[i], old_base->DPB,
1513 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1515 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1519 static void copy_parameter_set(void **to, void **from, int count, int size)
1523 for (i = 0; i < count; i++) {
1524 if (to[i] && !from[i])
1526 else if (from[i] && !to[i])
1527 to[i] = av_malloc(size);
1530 memcpy(to[i], from[i], size);
1534 static int decode_init_thread_copy(AVCodecContext *avctx)
1536 H264Context *h = avctx->priv_data;
1538 if (!avctx->internal->is_copy)
1540 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1541 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1543 h->context_initialized = 0;
1548 #define copy_fields(to, from, start_field, end_field) \
1549 memcpy(&to->start_field, &from->start_field, \
1550 (char *)&to->end_field - (char *)&to->start_field)
1552 static int h264_slice_header_init(H264Context *, int);
1554 static int h264_set_parameter_from_sps(H264Context *h);
1556 static int decode_update_thread_context(AVCodecContext *dst,
1557 const AVCodecContext *src)
1559 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1560 int inited = h->context_initialized, err = 0;
1561 int context_reinitialized = 0;
1564 if (dst == src || !h1->context_initialized)
1568 (h->width != h1->width ||
1569 h->height != h1->height ||
1570 h->mb_width != h1->mb_width ||
1571 h->mb_height != h1->mb_height ||
1572 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1573 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1574 h->sps.colorspace != h1->sps.colorspace)) {
1576 av_freep(&h->bipred_scratchpad);
1578 h->width = h1->width;
1579 h->height = h1->height;
1580 h->mb_height = h1->mb_height;
1581 h->mb_width = h1->mb_width;
1582 h->mb_num = h1->mb_num;
1583 h->mb_stride = h1->mb_stride;
1584 h->b_stride = h1->b_stride;
1586 if ((err = h264_slice_header_init(h, 1)) < 0) {
1587 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1590 context_reinitialized = 1;
1592 /* update linesize on resize. The decoder doesn't
1593 * necessarily call ff_h264_frame_start in the new thread */
1594 h->linesize = h1->linesize;
1595 h->uvlinesize = h1->uvlinesize;
1597 /* copy block_offset since frame_start may not be called */
1598 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1602 for (i = 0; i < MAX_SPS_COUNT; i++)
1603 av_freep(h->sps_buffers + i);
1605 for (i = 0; i < MAX_PPS_COUNT; i++)
1606 av_freep(h->pps_buffers + i);
1608 memcpy(h, h1, sizeof(*h1));
1609 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1610 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1611 memset(&h->er, 0, sizeof(h->er));
1612 memset(&h->me, 0, sizeof(h->me));
1613 h->context_initialized = 0;
1615 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1616 avcodec_get_frame_defaults(&h->cur_pic.f);
1617 h->cur_pic.tf.f = &h->cur_pic.f;
1621 h->qscale_table_pool = NULL;
1622 h->mb_type_pool = NULL;
1623 h->ref_index_pool = NULL;
1624 h->motion_val_pool = NULL;
1626 if (ff_h264_alloc_tables(h) < 0) {
1627 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1628 return AVERROR(ENOMEM);
1632 for (i = 0; i < 2; i++) {
1633 h->rbsp_buffer[i] = NULL;
1634 h->rbsp_buffer_size[i] = 0;
1636 h->bipred_scratchpad = NULL;
1637 h->edge_emu_buffer = NULL;
1639 h->thread_context[0] = h;
1641 h->dsp.clear_blocks(h->mb);
1642 h->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1643 h->context_initialized = 1;
1646 h->avctx->coded_height = h1->avctx->coded_height;
1647 h->avctx->coded_width = h1->avctx->coded_width;
1648 h->avctx->width = h1->avctx->width;
1649 h->avctx->height = h1->avctx->height;
1650 h->coded_picture_number = h1->coded_picture_number;
1651 h->first_field = h1->first_field;
1652 h->picture_structure = h1->picture_structure;
1653 h->qscale = h1->qscale;
1654 h->droppable = h1->droppable;
1655 h->data_partitioning = h1->data_partitioning;
1656 h->low_delay = h1->low_delay;
1658 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1659 unref_picture(h, &h->DPB[i]);
1660 if (h1->DPB[i].f.data[0] &&
1661 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1665 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1666 unref_picture(h, &h->cur_pic);
1667 if ((ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1670 h->workaround_bugs = h1->workaround_bugs;
1671 h->low_delay = h1->low_delay;
1672 h->droppable = h1->droppable;
1674 /* frame_start may not be called for the next thread (if it's decoding
1675 * a bottom field) so this has to be allocated here */
1676 err = alloc_scratch_buffers(h, h1->linesize);
1680 // extradata/NAL handling
1681 h->is_avc = h1->is_avc;
1684 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1685 MAX_SPS_COUNT, sizeof(SPS));
1687 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1688 MAX_PPS_COUNT, sizeof(PPS));
1691 // Dequantization matrices
1692 // FIXME these are big - can they be only copied when PPS changes?
1693 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1695 for (i = 0; i < 6; i++)
1696 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1697 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1699 for (i = 0; i < 6; i++)
1700 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1701 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1703 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1706 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1709 copy_fields(h, h1, short_ref, cabac_init_idc);
1711 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1712 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1713 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1714 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1716 h->last_slice_type = h1->last_slice_type;
1718 if (context_reinitialized)
1719 h264_set_parameter_from_sps(h);
1721 if (!h->cur_pic_ptr)
1724 if (!h->droppable) {
1725 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1726 h->prev_poc_msb = h->poc_msb;
1727 h->prev_poc_lsb = h->poc_lsb;
1729 h->prev_frame_num_offset = h->frame_num_offset;
1730 h->prev_frame_num = h->frame_num;
1731 h->outputed_poc = h->next_outputed_poc;
1736 int ff_h264_frame_start(H264Context *h)
1740 const int pixel_shift = h->pixel_shift;
1742 release_unused_pictures(h, 1);
1743 h->cur_pic_ptr = NULL;
1745 i = find_unused_picture(h);
1747 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1752 pic->reference = h->droppable ? 0 : h->picture_structure;
1753 pic->f.coded_picture_number = h->coded_picture_number++;
1754 pic->field_picture = h->picture_structure != PICT_FRAME;
1756 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1758 * See decode_nal_units().
1760 pic->f.key_frame = 0;
1761 pic->mmco_reset = 0;
1763 if ((ret = alloc_picture(h, pic)) < 0)
1766 h->cur_pic_ptr = pic;
1767 unref_picture(h, &h->cur_pic);
1768 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1771 ff_er_frame_start(&h->er);
1773 assert(h->linesize && h->uvlinesize);
1775 for (i = 0; i < 16; i++) {
1776 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1777 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1779 for (i = 0; i < 16; i++) {
1780 h->block_offset[16 + i] =
1781 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1782 h->block_offset[48 + 16 + i] =
1783 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1786 /* can't be in alloc_tables because linesize isn't known there.
1787 * FIXME: redo bipred weight to not require extra buffer? */
1788 for (i = 0; i < h->slice_context_count; i++)
1789 if (h->thread_context[i]) {
1790 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1795 /* Some macroblocks can be accessed before they're available in case
1796 * of lost slices, MBAFF or threading. */
1797 memset(h->slice_table, -1,
1798 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1800 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1801 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1803 /* We mark the current picture as non-reference after allocating it, so
1804 * that if we break out due to an error it can be released automatically
1805 * in the next ff_MPV_frame_start().
1806 * SVQ3 as well as most other codecs have only last/next/current and thus
1807 * get released even with set reference, besides SVQ3 and others do not
1808 * mark frames as reference later "naturally". */
1809 if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
1810 h->cur_pic_ptr->reference = 0;
1812 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1814 h->next_output_pic = NULL;
1816 assert(h->cur_pic_ptr->long_ref == 0);
1822 * Run setup operations that must be run after slice header decoding.
1823 * This includes finding the next displayed frame.
1825 * @param h h264 master context
1826 * @param setup_finished enough NALs have been read that we can call
1827 * ff_thread_finish_setup()
1829 static void decode_postinit(H264Context *h, int setup_finished)
1831 Picture *out = h->cur_pic_ptr;
1832 Picture *cur = h->cur_pic_ptr;
1833 int i, pics, out_of_order, out_idx;
1834 int invalid = 0, cnt = 0;
1836 h->cur_pic_ptr->f.pict_type = h->pict_type;
1838 if (h->next_output_pic)
1841 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1842 /* FIXME: if we have two PAFF fields in one packet, we can't start
1843 * the next thread here. If we have one field per packet, we can.
1844 * The check in decode_nal_units() is not good enough to find this
1845 * yet, so we assume the worst for now. */
1846 // if (setup_finished)
1847 // ff_thread_finish_setup(h->avctx);
1851 cur->f.interlaced_frame = 0;
1852 cur->f.repeat_pict = 0;
1854 /* Signal interlacing information externally. */
1855 /* Prioritize picture timing SEI information over used
1856 * decoding process if it exists. */
1858 if (h->sps.pic_struct_present_flag) {
1859 switch (h->sei_pic_struct) {
1860 case SEI_PIC_STRUCT_FRAME:
1862 case SEI_PIC_STRUCT_TOP_FIELD:
1863 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1864 cur->f.interlaced_frame = 1;
1866 case SEI_PIC_STRUCT_TOP_BOTTOM:
1867 case SEI_PIC_STRUCT_BOTTOM_TOP:
1868 if (FIELD_OR_MBAFF_PICTURE)
1869 cur->f.interlaced_frame = 1;
1871 // try to flag soft telecine progressive
1872 cur->f.interlaced_frame = h->prev_interlaced_frame;
1874 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1875 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1876 /* Signal the possibility of telecined film externally
1877 * (pic_struct 5,6). From these hints, let the applications
1878 * decide if they apply deinterlacing. */
1879 cur->f.repeat_pict = 1;
1881 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1882 cur->f.repeat_pict = 2;
1884 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1885 cur->f.repeat_pict = 4;
1889 if ((h->sei_ct_type & 3) &&
1890 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1891 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1893 /* Derive interlacing flag from used decoding process. */
1894 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1896 h->prev_interlaced_frame = cur->f.interlaced_frame;
1898 if (cur->field_poc[0] != cur->field_poc[1]) {
1899 /* Derive top_field_first from field pocs. */
1900 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1902 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1903 /* Use picture timing SEI information. Even if it is a
1904 * information of a past frame, better than nothing. */
1905 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1906 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1907 cur->f.top_field_first = 1;
1909 cur->f.top_field_first = 0;
1911 /* Most likely progressive */
1912 cur->f.top_field_first = 0;
1916 // FIXME do something with unavailable reference frames
1918 /* Sort B-frames into display order */
1920 if (h->sps.bitstream_restriction_flag &&
1921 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1922 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1926 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1927 !h->sps.bitstream_restriction_flag) {
1928 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1933 while (h->delayed_pic[pics])
1936 assert(pics <= MAX_DELAYED_PIC_COUNT);
1938 h->delayed_pic[pics++] = cur;
1939 if (cur->reference == 0)
1940 cur->reference = DELAYED_PIC_REF;
1942 /* Frame reordering. This code takes pictures from coding order and sorts
1943 * them by their incremental POC value into display order. It supports POC
1944 * gaps, MMCO reset codes and random resets.
1945 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1946 * and/or can be closed down with a MMCO reset code. In sequences where
1947 * there is no delay, we can't detect that (since the frame was already
1948 * output to the user), so we also set h->mmco_reset to detect the MMCO
1950 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
1951 * we increase the delay between input and output. All frames affected by
1952 * the lag (e.g. those that should have been output before another frame
1953 * that we already returned to the user) will be dropped. This is a bug
1954 * that we will fix later. */
1955 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1956 cnt += out->poc < h->last_pocs[i];
1957 invalid += out->poc == INT_MIN;
1959 if (!h->mmco_reset && !cur->f.key_frame &&
1960 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1963 h->delayed_pic[pics - 2]->mmco_reset = 2;
1965 if (h->mmco_reset || cur->f.key_frame) {
1966 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1967 h->last_pocs[i] = INT_MIN;
1969 invalid = MAX_DELAYED_PIC_COUNT;
1971 out = h->delayed_pic[0];
1973 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1974 h->delayed_pic[i] &&
1975 !h->delayed_pic[i - 1]->mmco_reset &&
1976 !h->delayed_pic[i]->f.key_frame;
1978 if (h->delayed_pic[i]->poc < out->poc) {
1979 out = h->delayed_pic[i];
1982 if (h->avctx->has_b_frames == 0 &&
1983 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
1984 h->next_outputed_poc = INT_MIN;
1985 out_of_order = !out->f.key_frame && !h->mmco_reset &&
1986 (out->poc < h->next_outputed_poc);
1988 if (h->sps.bitstream_restriction_flag &&
1989 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
1990 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1991 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1992 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1993 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
1996 } else if (h->low_delay &&
1997 ((h->next_outputed_poc != INT_MIN &&
1998 out->poc > h->next_outputed_poc + 2) ||
1999 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
2001 h->avctx->has_b_frames++;
2004 if (pics > h->avctx->has_b_frames) {
2005 out->reference &= ~DELAYED_PIC_REF;
2006 // for frame threading, the owner must be the second field's thread or
2007 // else the first thread can release the picture and reuse it unsafely
2008 for (i = out_idx; h->delayed_pic[i]; i++)
2009 h->delayed_pic[i] = h->delayed_pic[i + 1];
2011 memmove(h->last_pocs, &h->last_pocs[1],
2012 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
2013 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
2014 if (!out_of_order && pics > h->avctx->has_b_frames) {
2015 h->next_output_pic = out;
2016 if (out->mmco_reset) {
2018 h->next_outputed_poc = out->poc;
2019 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
2021 h->next_outputed_poc = INT_MIN;
2024 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
2025 h->next_outputed_poc = INT_MIN;
2027 h->next_outputed_poc = out->poc;
2032 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
2036 ff_thread_finish_setup(h->avctx);
2039 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2040 uint8_t *src_cb, uint8_t *src_cr,
2041 int linesize, int uvlinesize,
2044 uint8_t *top_border;
2046 const int pixel_shift = h->pixel_shift;
2047 int chroma444 = CHROMA444;
2048 int chroma422 = CHROMA422;
2051 src_cb -= uvlinesize;
2052 src_cr -= uvlinesize;
2054 if (!simple && FRAME_MBAFF) {
2057 top_border = h->top_borders[0][h->mb_x];
2058 AV_COPY128(top_border, src_y + 15 * linesize);
2060 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2061 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2064 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2065 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2066 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2067 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2069 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2070 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2072 } else if (chroma422) {
2074 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2075 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2077 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2078 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2082 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2083 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2085 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2086 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2091 } else if (MB_MBAFF) {
2097 top_border = h->top_borders[top_idx][h->mb_x];
2098 /* There are two lines saved, the line above the top macroblock
2099 * of a pair, and the line above the bottom macroblock. */
2100 AV_COPY128(top_border, src_y + 16 * linesize);
2102 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2104 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2107 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2108 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2109 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2110 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2112 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2113 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2115 } else if (chroma422) {
2117 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2118 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2120 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2121 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2125 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2126 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2128 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2129 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2135 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2136 uint8_t *src_cb, uint8_t *src_cr,
2137 int linesize, int uvlinesize,
2138 int xchg, int chroma444,
2139 int simple, int pixel_shift)
2141 int deblock_topleft;
2144 uint8_t *top_border_m1;
2145 uint8_t *top_border;
2147 if (!simple && FRAME_MBAFF) {
2152 top_idx = MB_MBAFF ? 0 : 1;
2156 if (h->deblocking_filter == 2) {
2157 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2158 deblock_top = h->top_type;
2160 deblock_topleft = (h->mb_x > 0);
2161 deblock_top = (h->mb_y > !!MB_FIELD);
2164 src_y -= linesize + 1 + pixel_shift;
2165 src_cb -= uvlinesize + 1 + pixel_shift;
2166 src_cr -= uvlinesize + 1 + pixel_shift;
2168 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2169 top_border = h->top_borders[top_idx][h->mb_x];
2171 #define XCHG(a, b, xchg) \
2172 if (pixel_shift) { \
2174 AV_SWAP64(b + 0, a + 0); \
2175 AV_SWAP64(b + 8, a + 8); \
2185 if (deblock_topleft) {
2186 XCHG(top_border_m1 + (8 << pixel_shift),
2187 src_y - (7 << pixel_shift), 1);
2189 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2190 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2191 if (h->mb_x + 1 < h->mb_width) {
2192 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2193 src_y + (17 << pixel_shift), 1);
2196 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2198 if (deblock_topleft) {
2199 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2200 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2202 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2203 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2204 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2205 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2206 if (h->mb_x + 1 < h->mb_width) {
2207 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2208 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2212 if (deblock_topleft) {
2213 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2214 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2216 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2217 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2223 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2226 if (high_bit_depth) {
2227 return AV_RN32A(((int32_t *)mb) + index);
2229 return AV_RN16A(mb + index);
2232 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2233 int index, int value)
2235 if (high_bit_depth) {
2236 AV_WN32A(((int32_t *)mb) + index, value);
2238 AV_WN16A(mb + index, value);
2241 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2242 int mb_type, int is_h264,
2244 int transform_bypass,
2248 uint8_t *dest_y, int p)
2250 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2251 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2253 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2254 block_offset += 16 * p;
2255 if (IS_INTRA4x4(mb_type)) {
2256 if (IS_8x8DCT(mb_type)) {
2257 if (transform_bypass) {
2259 idct_add = h->h264dsp.h264_add_pixels8;
2261 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2262 idct_add = h->h264dsp.h264_idct8_add;
2264 for (i = 0; i < 16; i += 4) {
2265 uint8_t *const ptr = dest_y + block_offset[i];
2266 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2267 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2268 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2270 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2271 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2272 (h->topright_samples_available << i) & 0x4000, linesize);
2274 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2275 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2277 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2282 if (transform_bypass) {
2284 idct_add = h->h264dsp.h264_add_pixels4;
2286 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2287 idct_add = h->h264dsp.h264_idct_add;
2289 for (i = 0; i < 16; i++) {
2290 uint8_t *const ptr = dest_y + block_offset[i];
2291 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2293 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2294 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2299 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2300 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2301 assert(h->mb_y || linesize <= block_offset[i]);
2302 if (!topright_avail) {
2304 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2305 topright = (uint8_t *)&tr_high;
2307 tr = ptr[3 - linesize] * 0x01010101u;
2308 topright = (uint8_t *)&tr;
2311 topright = ptr + (4 << pixel_shift) - linesize;
2315 h->hpc.pred4x4[dir](ptr, topright, linesize);
2316 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2319 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2320 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2322 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2323 } else if (CONFIG_SVQ3_DECODER)
2324 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2330 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2332 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2333 if (!transform_bypass)
2334 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2336 h->dequant4_coeff[p][qscale][0]);
2338 static const uint8_t dc_mapping[16] = {
2339 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2340 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2341 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2342 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
2343 for (i = 0; i < 16; i++)
2344 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2345 pixel_shift, dc_mapping[i],
2346 dctcoef_get(h->mb_luma_dc[p],
2350 } else if (CONFIG_SVQ3_DECODER)
2351 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2352 h->mb_luma_dc[p], qscale);
2356 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2357 int is_h264, int simple,
2358 int transform_bypass,
2362 uint8_t *dest_y, int p)
2364 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2366 block_offset += 16 * p;
2367 if (!IS_INTRA4x4(mb_type)) {
2369 if (IS_INTRA16x16(mb_type)) {
2370 if (transform_bypass) {
2371 if (h->sps.profile_idc == 244 &&
2372 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2373 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2374 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2375 h->mb + (p * 256 << pixel_shift),
2378 for (i = 0; i < 16; i++)
2379 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2380 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2381 h->h264dsp.h264_add_pixels4(dest_y + block_offset[i],
2382 h->mb + (i * 16 + p * 256 << pixel_shift),
2386 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2387 h->mb + (p * 256 << pixel_shift),
2389 h->non_zero_count_cache + p * 5 * 8);
2391 } else if (h->cbp & 15) {
2392 if (transform_bypass) {
2393 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2394 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8
2395 : h->h264dsp.h264_add_pixels4;
2396 for (i = 0; i < 16; i += di)
2397 if (h->non_zero_count_cache[scan8[i + p * 16]])
2398 idct_add(dest_y + block_offset[i],
2399 h->mb + (i * 16 + p * 256 << pixel_shift),
2402 if (IS_8x8DCT(mb_type))
2403 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2404 h->mb + (p * 256 << pixel_shift),
2406 h->non_zero_count_cache + p * 5 * 8);
2408 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2409 h->mb + (p * 256 << pixel_shift),
2411 h->non_zero_count_cache + p * 5 * 8);
2414 } else if (CONFIG_SVQ3_DECODER) {
2415 for (i = 0; i < 16; i++)
2416 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2417 // FIXME benchmark weird rule, & below
2418 uint8_t *const ptr = dest_y + block_offset[i];
2419 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2420 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2428 #include "h264_mb_template.c"
2432 #include "h264_mb_template.c"
2436 #include "h264_mb_template.c"
2438 void ff_h264_hl_decode_mb(H264Context *h)
2440 const int mb_xy = h->mb_xy;
2441 const int mb_type = h->cur_pic.mb_type[mb_xy];
2442 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
2445 if (is_complex || h->pixel_shift)
2446 hl_decode_mb_444_complex(h);
2448 hl_decode_mb_444_simple_8(h);
2449 } else if (is_complex) {
2450 hl_decode_mb_complex(h);
2451 } else if (h->pixel_shift) {
2452 hl_decode_mb_simple_16(h);
2454 hl_decode_mb_simple_8(h);
2457 static int pred_weight_table(H264Context *h)
2460 int luma_def, chroma_def;
2463 h->use_weight_chroma = 0;
2464 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2465 if (h->sps.chroma_format_idc)
2466 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2467 luma_def = 1 << h->luma_log2_weight_denom;
2468 chroma_def = 1 << h->chroma_log2_weight_denom;
2470 for (list = 0; list < 2; list++) {
2471 h->luma_weight_flag[list] = 0;
2472 h->chroma_weight_flag[list] = 0;
2473 for (i = 0; i < h->ref_count[list]; i++) {
2474 int luma_weight_flag, chroma_weight_flag;
2476 luma_weight_flag = get_bits1(&h->gb);
2477 if (luma_weight_flag) {
2478 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2479 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2480 if (h->luma_weight[i][list][0] != luma_def ||
2481 h->luma_weight[i][list][1] != 0) {
2483 h->luma_weight_flag[list] = 1;
2486 h->luma_weight[i][list][0] = luma_def;
2487 h->luma_weight[i][list][1] = 0;
2490 if (h->sps.chroma_format_idc) {
2491 chroma_weight_flag = get_bits1(&h->gb);
2492 if (chroma_weight_flag) {
2494 for (j = 0; j < 2; j++) {
2495 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2496 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2497 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2498 h->chroma_weight[i][list][j][1] != 0) {
2499 h->use_weight_chroma = 1;
2500 h->chroma_weight_flag[list] = 1;
2505 for (j = 0; j < 2; j++) {
2506 h->chroma_weight[i][list][j][0] = chroma_def;
2507 h->chroma_weight[i][list][j][1] = 0;
2512 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2515 h->use_weight = h->use_weight || h->use_weight_chroma;
2520 * Initialize implicit_weight table.
2521 * @param field 0/1 initialize the weight for interlaced MBAFF
2522 * -1 initializes the rest
2524 static void implicit_weight_table(H264Context *h, int field)
2526 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2528 for (i = 0; i < 2; i++) {
2529 h->luma_weight_flag[i] = 0;
2530 h->chroma_weight_flag[i] = 0;
2534 if (h->picture_structure == PICT_FRAME) {
2535 cur_poc = h->cur_pic_ptr->poc;
2537 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2539 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2540 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2542 h->use_weight_chroma = 0;
2546 ref_count0 = h->ref_count[0];
2547 ref_count1 = h->ref_count[1];
2549 cur_poc = h->cur_pic_ptr->field_poc[field];
2551 ref_count0 = 16 + 2 * h->ref_count[0];
2552 ref_count1 = 16 + 2 * h->ref_count[1];
2556 h->use_weight_chroma = 2;
2557 h->luma_log2_weight_denom = 5;
2558 h->chroma_log2_weight_denom = 5;
2560 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2561 int poc0 = h->ref_list[0][ref0].poc;
2562 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2564 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2565 int poc1 = h->ref_list[1][ref1].poc;
2566 int td = av_clip(poc1 - poc0, -128, 127);
2568 int tb = av_clip(cur_poc - poc0, -128, 127);
2569 int tx = (16384 + (FFABS(td) >> 1)) / td;
2570 int dist_scale_factor = (tb * tx + 32) >> 8;
2571 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2572 w = 64 - dist_scale_factor;
2576 h->implicit_weight[ref0][ref1][0] =
2577 h->implicit_weight[ref0][ref1][1] = w;
2579 h->implicit_weight[ref0][ref1][field] = w;
2586 * instantaneous decoder refresh.
2588 static void idr(H264Context *h)
2590 ff_h264_remove_all_refs(h);
2591 h->prev_frame_num = 0;
2592 h->prev_frame_num_offset = 0;
2594 h->prev_poc_lsb = 0;
2597 /* forget old pics after a seek */
2598 static void flush_change(H264Context *h)
2601 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2602 h->last_pocs[i] = INT_MIN;
2603 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2604 h->prev_interlaced_frame = 1;
2607 h->cur_pic_ptr->reference = 0;
2609 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2610 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2611 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2612 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2613 ff_h264_reset_sei(h);
2616 /* forget old pics after a seek */
2617 static void flush_dpb(AVCodecContext *avctx)
2619 H264Context *h = avctx->priv_data;
2622 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2623 if (h->delayed_pic[i])
2624 h->delayed_pic[i]->reference = 0;
2625 h->delayed_pic[i] = NULL;
2630 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2631 unref_picture(h, &h->DPB[i]);
2632 h->cur_pic_ptr = NULL;
2633 unref_picture(h, &h->cur_pic);
2635 h->mb_x = h->mb_y = 0;
2637 h->parse_context.state = -1;
2638 h->parse_context.frame_start_found = 0;
2639 h->parse_context.overread = 0;
2640 h->parse_context.overread_index = 0;
2641 h->parse_context.index = 0;
2642 h->parse_context.last_index = 0;
2645 static int init_poc(H264Context *h)
2647 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2649 Picture *cur = h->cur_pic_ptr;
2651 h->frame_num_offset = h->prev_frame_num_offset;
2652 if (h->frame_num < h->prev_frame_num)
2653 h->frame_num_offset += max_frame_num;
2655 if (h->sps.poc_type == 0) {
2656 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2658 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2659 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2660 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2661 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2663 h->poc_msb = h->prev_poc_msb;
2665 field_poc[1] = h->poc_msb + h->poc_lsb;
2666 if (h->picture_structure == PICT_FRAME)
2667 field_poc[1] += h->delta_poc_bottom;
2668 } else if (h->sps.poc_type == 1) {
2669 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2672 if (h->sps.poc_cycle_length != 0)
2673 abs_frame_num = h->frame_num_offset + h->frame_num;
2677 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2680 expected_delta_per_poc_cycle = 0;
2681 for (i = 0; i < h->sps.poc_cycle_length; i++)
2682 // FIXME integrate during sps parse
2683 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2685 if (abs_frame_num > 0) {
2686 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2687 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2689 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2690 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2691 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2695 if (h->nal_ref_idc == 0)
2696 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2698 field_poc[0] = expectedpoc + h->delta_poc[0];
2699 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2701 if (h->picture_structure == PICT_FRAME)
2702 field_poc[1] += h->delta_poc[1];
2704 int poc = 2 * (h->frame_num_offset + h->frame_num);
2706 if (!h->nal_ref_idc)
2713 if (h->picture_structure != PICT_BOTTOM_FIELD)
2714 h->cur_pic_ptr->field_poc[0] = field_poc[0];
2715 if (h->picture_structure != PICT_TOP_FIELD)
2716 h->cur_pic_ptr->field_poc[1] = field_poc[1];
2717 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2723 * initialize scan tables
2725 static void init_scan_tables(H264Context *h)
2728 for (i = 0; i < 16; i++) {
2729 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2730 h->zigzag_scan[i] = T(zigzag_scan[i]);
2731 h->field_scan[i] = T(field_scan[i]);
2734 for (i = 0; i < 64; i++) {
2735 #define T(x) (x >> 3) | ((x & 7) << 3)
2736 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2737 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2738 h->field_scan8x8[i] = T(field_scan8x8[i]);
2739 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2742 if (h->sps.transform_bypass) { // FIXME same ugly
2743 h->zigzag_scan_q0 = zigzag_scan;
2744 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2745 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2746 h->field_scan_q0 = field_scan;
2747 h->field_scan8x8_q0 = field_scan8x8;
2748 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2750 h->zigzag_scan_q0 = h->zigzag_scan;
2751 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2752 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2753 h->field_scan_q0 = h->field_scan;
2754 h->field_scan8x8_q0 = h->field_scan8x8;
2755 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2759 static int field_end(H264Context *h, int in_setup)
2761 AVCodecContext *const avctx = h->avctx;
2765 if (!in_setup && !h->droppable)
2766 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2767 h->picture_structure == PICT_BOTTOM_FIELD);
2769 if (CONFIG_H264_VDPAU_DECODER &&
2770 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2771 ff_vdpau_h264_set_reference_frames(h);
2773 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2774 if (!h->droppable) {
2775 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2776 h->prev_poc_msb = h->poc_msb;
2777 h->prev_poc_lsb = h->poc_lsb;
2779 h->prev_frame_num_offset = h->frame_num_offset;
2780 h->prev_frame_num = h->frame_num;
2781 h->outputed_poc = h->next_outputed_poc;
2784 if (avctx->hwaccel) {
2785 if (avctx->hwaccel->end_frame(avctx) < 0)
2786 av_log(avctx, AV_LOG_ERROR,
2787 "hardware accelerator failed to decode picture\n");
2790 if (CONFIG_H264_VDPAU_DECODER &&
2791 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2792 ff_vdpau_h264_picture_complete(h);
2795 * FIXME: Error handling code does not seem to support interlaced
2796 * when slices span multiple rows
2797 * The ff_er_add_slice calls don't work right for bottom
2798 * fields; they cause massive erroneous error concealing
2799 * Error marking covers both fields (top and bottom).
2800 * This causes a mismatched s->error_count
2801 * and a bad error table. Further, the error count goes to
2802 * INT_MAX when called for bottom field, because mb_y is
2803 * past end by one (callers fault) and resync_mb_y != 0
2804 * causes problems for the first MB line, too.
2806 if (!FIELD_PICTURE) {
2807 h->er.cur_pic = h->cur_pic_ptr;
2808 h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
2809 h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
2810 ff_er_frame_end(&h->er);
2814 h->current_slice = 0;
2820 * Replicate H264 "master" context to thread contexts.
2822 static int clone_slice(H264Context *dst, H264Context *src)
2824 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2825 dst->cur_pic_ptr = src->cur_pic_ptr;
2826 dst->cur_pic = src->cur_pic;
2827 dst->linesize = src->linesize;
2828 dst->uvlinesize = src->uvlinesize;
2829 dst->first_field = src->first_field;
2831 dst->prev_poc_msb = src->prev_poc_msb;
2832 dst->prev_poc_lsb = src->prev_poc_lsb;
2833 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2834 dst->prev_frame_num = src->prev_frame_num;
2835 dst->short_ref_count = src->short_ref_count;
2837 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2838 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2839 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2841 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2842 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2848 * Compute profile from profile_idc and constraint_set?_flags.
2852 * @return profile as defined by FF_PROFILE_H264_*
2854 int ff_h264_get_profile(SPS *sps)
2856 int profile = sps->profile_idc;
2858 switch (sps->profile_idc) {
2859 case FF_PROFILE_H264_BASELINE:
2860 // constraint_set1_flag set to 1
2861 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2863 case FF_PROFILE_H264_HIGH_10:
2864 case FF_PROFILE_H264_HIGH_422:
2865 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2866 // constraint_set3_flag set to 1
2867 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2874 static int h264_set_parameter_from_sps(H264Context *h)
2876 if (h->flags & CODEC_FLAG_LOW_DELAY ||
2877 (h->sps.bitstream_restriction_flag &&
2878 !h->sps.num_reorder_frames)) {
2879 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2880 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
2881 "Reenabling low delay requires a codec flush.\n");
2886 if (h->avctx->has_b_frames < 2)
2887 h->avctx->has_b_frames = !h->low_delay;
2889 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
2890 av_log_missing_feature(h->avctx,
2891 "Different bit depth between chroma and luma", 1);
2892 return AVERROR_PATCHWELCOME;
2895 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2896 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2897 if (h->avctx->codec &&
2898 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2899 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2900 av_log(h->avctx, AV_LOG_ERROR,
2901 "VDPAU decoding does not support video colorspace.\n");
2902 return AVERROR_INVALIDDATA;
2904 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
2905 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2906 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2907 h->pixel_shift = h->sps.bit_depth_luma > 8;
2909 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2910 h->sps.chroma_format_idc);
2911 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2912 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2913 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
2914 h->sps.chroma_format_idc);
2915 h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2916 ff_dsputil_init(&h->dsp, h->avctx);
2917 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
2919 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2920 h->sps.bit_depth_luma);
2921 return AVERROR_INVALIDDATA;
2927 static enum PixelFormat get_pixel_format(H264Context *h)
2929 switch (h->sps.bit_depth_luma) {
2932 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2933 return AV_PIX_FMT_GBRP9;
2935 return AV_PIX_FMT_YUV444P9;
2936 } else if (CHROMA422)
2937 return AV_PIX_FMT_YUV422P9;
2939 return AV_PIX_FMT_YUV420P9;
2943 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2944 return AV_PIX_FMT_GBRP10;
2946 return AV_PIX_FMT_YUV444P10;
2947 } else if (CHROMA422)
2948 return AV_PIX_FMT_YUV422P10;
2950 return AV_PIX_FMT_YUV420P10;
2954 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2955 return AV_PIX_FMT_GBRP;
2957 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2958 : AV_PIX_FMT_YUV444P;
2959 } else if (CHROMA422) {
2960 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2961 : AV_PIX_FMT_YUV422P;
2963 return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
2964 h->avctx->codec->pix_fmts :
2965 h->avctx->color_range == AVCOL_RANGE_JPEG ?
2966 h264_hwaccel_pixfmt_list_jpeg_420 :
2967 h264_hwaccel_pixfmt_list_420);
2971 av_log(h->avctx, AV_LOG_ERROR,
2972 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2973 return AVERROR_INVALIDDATA;
2977 static int h264_slice_header_init(H264Context *h, int reinit)
2979 int nb_slices = (HAVE_THREADS &&
2980 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
2981 h->avctx->thread_count : 1;
2984 avcodec_set_dimensions(h->avctx, h->width, h->height);
2985 h->avctx->sample_aspect_ratio = h->sps.sar;
2986 av_assert0(h->avctx->sample_aspect_ratio.den);
2987 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
2988 &h->chroma_x_shift, &h->chroma_y_shift);
2990 if (h->sps.timing_info_present_flag) {
2991 int64_t den = h->sps.time_scale;
2992 if (h->x264_build < 44U)
2994 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
2995 h->sps.num_units_in_tick, den, 1 << 30);
2998 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
3003 h->prev_interlaced_frame = 1;
3005 init_scan_tables(h);
3006 if (ff_h264_alloc_tables(h) < 0) {
3007 av_log(h->avctx, AV_LOG_ERROR,
3008 "Could not allocate memory for h264\n");
3009 return AVERROR(ENOMEM);
3012 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3015 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3017 max_slices = MAX_THREADS;
3018 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3019 " reducing to %d\n", nb_slices, max_slices);
3020 nb_slices = max_slices;
3022 h->slice_context_count = nb_slices;
3024 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3025 if (context_init(h) < 0) {
3026 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3030 for (i = 1; i < h->slice_context_count; i++) {
3032 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3033 c->avctx = h->avctx;
3036 c->h264dsp = h->h264dsp;
3037 c->h264qpel = h->h264qpel;
3038 c->h264chroma = h->h264chroma;
3041 c->pixel_shift = h->pixel_shift;
3042 c->width = h->width;
3043 c->height = h->height;
3044 c->linesize = h->linesize;
3045 c->uvlinesize = h->uvlinesize;
3046 c->chroma_x_shift = h->chroma_x_shift;
3047 c->chroma_y_shift = h->chroma_y_shift;
3048 c->qscale = h->qscale;
3049 c->droppable = h->droppable;
3050 c->data_partitioning = h->data_partitioning;
3051 c->low_delay = h->low_delay;
3052 c->mb_width = h->mb_width;
3053 c->mb_height = h->mb_height;
3054 c->mb_stride = h->mb_stride;
3055 c->mb_num = h->mb_num;
3056 c->flags = h->flags;
3057 c->workaround_bugs = h->workaround_bugs;
3058 c->pict_type = h->pict_type;
3060 init_scan_tables(c);
3061 clone_tables(c, h, i);
3062 c->context_initialized = 1;
3065 for (i = 0; i < h->slice_context_count; i++)
3066 if (context_init(h->thread_context[i]) < 0) {
3067 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3072 h->context_initialized = 1;
3078 * Decode a slice header.
3079 * This will also call ff_MPV_common_init() and frame_start() as needed.
3081 * @param h h264context
3082 * @param h0 h264 master context (differs from 'h' when doing sliced based
3083 * parallel decoding)
3085 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3087 static int decode_slice_header(H264Context *h, H264Context *h0)
3089 unsigned int first_mb_in_slice;
3090 unsigned int pps_id;
3091 int num_ref_idx_active_override_flag, max_refs, ret;
3092 unsigned int slice_type, tmp, i, j;
3093 int default_ref_list_done = 0;
3094 int last_pic_structure, last_pic_droppable;
3095 int needs_reinit = 0;
3097 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3098 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3100 first_mb_in_slice = get_ue_golomb(&h->gb);
3102 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3103 if (h0->current_slice && FIELD_PICTURE) {
3107 h0->current_slice = 0;
3108 if (!h0->first_field) {
3109 if (h->cur_pic_ptr && !h->droppable) {
3110 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3111 h->picture_structure == PICT_BOTTOM_FIELD);
3113 h->cur_pic_ptr = NULL;
3117 slice_type = get_ue_golomb_31(&h->gb);
3118 if (slice_type > 9) {
3119 av_log(h->avctx, AV_LOG_ERROR,
3120 "slice type too large (%d) at %d %d\n",
3121 h->slice_type, h->mb_x, h->mb_y);
3124 if (slice_type > 4) {
3126 h->slice_type_fixed = 1;
3128 h->slice_type_fixed = 0;
3130 slice_type = golomb_to_pict_type[slice_type];
3131 if (slice_type == AV_PICTURE_TYPE_I ||
3132 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3133 default_ref_list_done = 1;
3135 h->slice_type = slice_type;
3136 h->slice_type_nos = slice_type & 3;
3138 // to make a few old functions happy, it's wrong though
3139 h->pict_type = h->slice_type;
3141 pps_id = get_ue_golomb(&h->gb);
3142 if (pps_id >= MAX_PPS_COUNT) {
3143 av_log(h->avctx, AV_LOG_ERROR, "pps_id out of range\n");
3146 if (!h0->pps_buffers[pps_id]) {
3147 av_log(h->avctx, AV_LOG_ERROR,
3148 "non-existing PPS %u referenced\n",
3152 h->pps = *h0->pps_buffers[pps_id];
3154 if (!h0->sps_buffers[h->pps.sps_id]) {
3155 av_log(h->avctx, AV_LOG_ERROR,
3156 "non-existing SPS %u referenced\n",
3161 if (h->pps.sps_id != h->current_sps_id ||
3162 h0->sps_buffers[h->pps.sps_id]->new) {
3163 h0->sps_buffers[h->pps.sps_id]->new = 0;
3165 h->current_sps_id = h->pps.sps_id;
3166 h->sps = *h0->sps_buffers[h->pps.sps_id];
3168 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3169 h->chroma_format_idc != h->sps.chroma_format_idc) {
3170 h->bit_depth_luma = h->sps.bit_depth_luma;
3171 h->chroma_format_idc = h->sps.chroma_format_idc;
3174 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3178 h->avctx->profile = ff_h264_get_profile(&h->sps);
3179 h->avctx->level = h->sps.level_idc;
3180 h->avctx->refs = h->sps.ref_frame_count;
3182 if (h->mb_width != h->sps.mb_width ||
3183 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
3186 h->mb_width = h->sps.mb_width;
3187 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3188 h->mb_num = h->mb_width * h->mb_height;
3189 h->mb_stride = h->mb_width + 1;
3191 h->b_stride = h->mb_width * 4;
3193 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3195 h->width = 16 * h->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
3196 if (h->sps.frame_mbs_only_flag)
3197 h->height = 16 * h->mb_height - (1 << h->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> h->chroma_y_shift) - 1);
3199 h->height = 16 * h->mb_height - (2 << h->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> h->chroma_y_shift) - 1);
3201 if (FFALIGN(h->avctx->width, 16) == h->width &&
3202 FFALIGN(h->avctx->height, 16) == h->height) {
3203 h->width = h->avctx->width;
3204 h->height = h->avctx->height;
3207 if (h->sps.video_signal_type_present_flag) {
3208 h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
3210 if (h->sps.colour_description_present_flag) {
3211 if (h->avctx->colorspace != h->sps.colorspace)
3213 h->avctx->color_primaries = h->sps.color_primaries;
3214 h->avctx->color_trc = h->sps.color_trc;
3215 h->avctx->colorspace = h->sps.colorspace;
3219 if (h->context_initialized &&
3220 (h->width != h->avctx->width ||
3221 h->height != h->avctx->height ||
3225 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3226 "slice %d\n", h0->current_slice + 1);
3227 return AVERROR_INVALIDDATA;
3232 if ((ret = get_pixel_format(h)) < 0)
3234 h->avctx->pix_fmt = ret;
3236 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3237 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3239 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3240 av_log(h->avctx, AV_LOG_ERROR,
3241 "h264_slice_header_init() failed\n");
3245 if (!h->context_initialized) {
3247 av_log(h->avctx, AV_LOG_ERROR,
3248 "Cannot (re-)initialize context during parallel decoding.\n");
3252 if ((ret = get_pixel_format(h)) < 0)
3254 h->avctx->pix_fmt = ret;
3256 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3257 av_log(h->avctx, AV_LOG_ERROR,
3258 "h264_slice_header_init() failed\n");
3263 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3264 h->dequant_coeff_pps = pps_id;
3265 init_dequant_tables(h);
3268 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3271 h->mb_aff_frame = 0;
3272 last_pic_structure = h0->picture_structure;
3273 last_pic_droppable = h0->droppable;
3274 h->droppable = h->nal_ref_idc == 0;
3275 if (h->sps.frame_mbs_only_flag) {
3276 h->picture_structure = PICT_FRAME;
3278 if (get_bits1(&h->gb)) { // field_pic_flag
3279 h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
3281 h->picture_structure = PICT_FRAME;
3282 h->mb_aff_frame = h->sps.mb_aff;
3285 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3287 if (h0->current_slice != 0) {
3288 if (last_pic_structure != h->picture_structure ||
3289 last_pic_droppable != h->droppable) {
3290 av_log(h->avctx, AV_LOG_ERROR,
3291 "Changing field mode (%d -> %d) between slices is not allowed\n",
3292 last_pic_structure, h->picture_structure);
3293 h->picture_structure = last_pic_structure;
3294 h->droppable = last_pic_droppable;
3295 return AVERROR_INVALIDDATA;
3296 } else if (!h0->cur_pic_ptr) {
3297 av_log(h->avctx, AV_LOG_ERROR,
3298 "unset cur_pic_ptr on %d. slice\n",
3299 h0->current_slice + 1);
3300 return AVERROR_INVALIDDATA;
3303 /* Shorten frame num gaps so we don't have to allocate reference
3304 * frames just to throw them away */
3305 if (h->frame_num != h->prev_frame_num) {
3306 int unwrap_prev_frame_num = h->prev_frame_num;
3307 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3309 if (unwrap_prev_frame_num > h->frame_num)
3310 unwrap_prev_frame_num -= max_frame_num;
3312 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3313 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3314 if (unwrap_prev_frame_num < 0)
3315 unwrap_prev_frame_num += max_frame_num;
3317 h->prev_frame_num = unwrap_prev_frame_num;
3321 /* See if we have a decoded first field looking for a pair...
3322 * Here, we're using that to see if we should mark previously
3323 * decode frames as "finished".
3324 * We have to do that before the "dummy" in-between frame allocation,
3325 * since that can modify s->current_picture_ptr. */
3326 if (h0->first_field) {
3327 assert(h0->cur_pic_ptr);
3328 assert(h0->cur_pic_ptr->f.data[0]);
3329 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3331 /* figure out if we have a complementary field pair */
3332 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3333 /* Previous field is unmatched. Don't display it, but let it
3334 * remain for reference if marked as such. */
3335 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3336 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3337 last_pic_structure == PICT_TOP_FIELD);
3340 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3341 /* This and previous field were reference, but had
3342 * different frame_nums. Consider this field first in
3343 * pair. Throw away previous field except for reference
3345 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3346 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3347 last_pic_structure == PICT_TOP_FIELD);
3350 /* Second field in complementary pair */
3351 if (!((last_pic_structure == PICT_TOP_FIELD &&
3352 h->picture_structure == PICT_BOTTOM_FIELD) ||
3353 (last_pic_structure == PICT_BOTTOM_FIELD &&
3354 h->picture_structure == PICT_TOP_FIELD))) {
3355 av_log(h->avctx, AV_LOG_ERROR,
3356 "Invalid field mode combination %d/%d\n",
3357 last_pic_structure, h->picture_structure);
3358 h->picture_structure = last_pic_structure;
3359 h->droppable = last_pic_droppable;
3360 return AVERROR_INVALIDDATA;
3361 } else if (last_pic_droppable != h->droppable) {
3362 av_log(h->avctx, AV_LOG_ERROR,
3363 "Cannot combine reference and non-reference fields in the same frame\n");
3364 av_log_ask_for_sample(h->avctx, NULL);
3365 h->picture_structure = last_pic_structure;
3366 h->droppable = last_pic_droppable;
3367 return AVERROR_PATCHWELCOME;
3373 while (h->frame_num != h->prev_frame_num &&
3374 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3375 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3376 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3377 h->frame_num, h->prev_frame_num);
3378 if (ff_h264_frame_start(h) < 0)
3380 h->prev_frame_num++;
3381 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3382 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3383 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3384 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3385 if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
3386 h->avctx->err_recognition & AV_EF_EXPLODE)
3388 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3389 (h->avctx->err_recognition & AV_EF_EXPLODE))
3390 return AVERROR_INVALIDDATA;
3391 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3392 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3393 * about there being no actual duplicates.
3394 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3395 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3397 if (h->short_ref_count) {
3399 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3400 (const uint8_t **)prev->f.data, prev->f.linesize,
3401 h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
3402 h->short_ref[0]->poc = prev->poc + 2;
3404 h->short_ref[0]->frame_num = h->prev_frame_num;
3408 /* See if we have a decoded first field looking for a pair...
3409 * We're using that to see whether to continue decoding in that
3410 * frame, or to allocate a new one. */
3411 if (h0->first_field) {
3412 assert(h0->cur_pic_ptr);
3413 assert(h0->cur_pic_ptr->f.data[0]);
3414 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3416 /* figure out if we have a complementary field pair */
3417 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3418 /* Previous field is unmatched. Don't display it, but let it
3419 * remain for reference if marked as such. */
3420 h0->cur_pic_ptr = NULL;
3421 h0->first_field = FIELD_PICTURE;