2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
34 #include "cabac_functions.h"
36 #include "error_resilience.h"
38 #include "mpegvideo.h"
41 #include "h264chroma.h"
42 #include "h264_mvpred.h"
45 #include "rectangle.h"
48 #include "vdpau_internal.h"
49 #include "libavutil/avassert.h"
54 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
56 static const uint8_t rem6[QP_MAX_NUM + 1] = {
57 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
58 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
59 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
60 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
64 static const uint8_t div6[QP_MAX_NUM + 1] = {
65 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
66 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
67 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
68 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
72 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
73 #if CONFIG_H264_DXVA2_HWACCEL
76 #if CONFIG_H264_VAAPI_HWACCEL
79 #if CONFIG_H264_VDA_HWACCEL
82 #if CONFIG_H264_VDPAU_HWACCEL
89 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
90 #if CONFIG_H264_DXVA2_HWACCEL
93 #if CONFIG_H264_VAAPI_HWACCEL
96 #if CONFIG_H264_VDA_HWACCEL
99 #if CONFIG_H264_VDPAU_HWACCEL
106 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
108 H264Context *h = avctx->priv_data;
109 return h ? h->sps.num_reorder_frames : 0;
112 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
114 int mb_x, int mb_y, int mb_intra, int mb_skipped)
116 H264Context *h = opaque;
120 h->mb_xy = mb_x + mb_y * h->mb_stride;
121 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
122 av_assert1(ref >= 0);
123 /* FIXME: It is possible albeit uncommon that slice references
124 * differ between slices. We take the easy approach and ignore
125 * it for now. If this turns out to have any relevance in
126 * practice then correct remapping should be added. */
127 if (ref >= h->ref_count[0])
129 if (!h->ref_list[0][ref].f.data[0]) {
130 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
133 if ((h->ref_list[0][ref].reference&3) != 3) {
134 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
137 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
139 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
140 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
141 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
143 h->mb_field_decoding_flag = 0;
144 ff_h264_hl_decode_mb(h);
147 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
149 AVCodecContext *avctx = h->avctx;
150 Picture *cur = &h->cur_pic;
151 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
152 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
153 int vshift = desc->log2_chroma_h;
154 const int field_pic = h->picture_structure != PICT_FRAME;
160 height = FFMIN(height, avctx->height - y);
162 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
165 if (avctx->draw_horiz_band) {
167 int offset[AV_NUM_DATA_POINTERS];
170 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
171 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
178 offset[0] = y * src->linesize[0];
180 offset[2] = (y >> vshift) * src->linesize[1];
181 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
186 avctx->draw_horiz_band(avctx, src, offset,
187 y, h->picture_structure, height);
191 static void unref_picture(H264Context *h, Picture *pic)
193 int off = offsetof(Picture, tf) + sizeof(pic->tf);
199 pic->period_since_free = 0;
200 ff_thread_release_buffer(h->avctx, &pic->tf);
201 av_buffer_unref(&pic->hwaccel_priv_buf);
203 av_buffer_unref(&pic->qscale_table_buf);
204 av_buffer_unref(&pic->mb_type_buf);
205 for (i = 0; i < 2; i++) {
206 av_buffer_unref(&pic->motion_val_buf[i]);
207 av_buffer_unref(&pic->ref_index_buf[i]);
210 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
213 static void release_unused_pictures(H264Context *h, int remove_current)
217 /* release non reference frames */
218 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
219 if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&
220 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
221 unref_picture(h, &h->DPB[i]);
226 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
230 av_assert0(!dst->f.buf[0]);
231 av_assert0(src->f.buf[0]);
235 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
240 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
241 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
242 if (!dst->qscale_table_buf || !dst->mb_type_buf)
244 dst->qscale_table = src->qscale_table;
245 dst->mb_type = src->mb_type;
247 for (i = 0; i < 2; i ++) {
248 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
249 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
250 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
252 dst->motion_val[i] = src->motion_val[i];
253 dst->ref_index[i] = src->ref_index[i];
256 if (src->hwaccel_picture_private) {
257 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
258 if (!dst->hwaccel_priv_buf)
260 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
263 for (i = 0; i < 2; i++)
264 dst->field_poc[i] = src->field_poc[i];
266 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
267 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
270 dst->frame_num = src->frame_num;
271 dst->mmco_reset = src->mmco_reset;
272 dst->pic_id = src->pic_id;
273 dst->long_ref = src->long_ref;
274 dst->mbaff = src->mbaff;
275 dst->field_picture = src->field_picture;
276 dst->needs_realloc = src->needs_realloc;
277 dst->reference = src->reference;
278 dst->sync = src->sync;
279 dst->period_since_free = src->period_since_free;
283 unref_picture(h, dst);
288 static int alloc_scratch_buffers(H264Context *h, int linesize)
290 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
292 if (h->bipred_scratchpad)
295 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
296 // edge emu needs blocksize + filter length - 1
297 // (= 21x21 for h264)
298 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
299 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
301 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
302 av_freep(&h->bipred_scratchpad);
303 av_freep(&h->edge_emu_buffer);
304 av_freep(&h->me.scratchpad);
305 return AVERROR(ENOMEM);
308 h->me.temp = h->me.scratchpad;
313 static int init_table_pools(H264Context *h)
315 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
316 const int mb_array_size = h->mb_stride * h->mb_height;
317 const int b4_stride = h->mb_width * 4 + 1;
318 const int b4_array_size = b4_stride * h->mb_height * 4;
320 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
322 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
323 sizeof(uint32_t), av_buffer_allocz);
324 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
325 sizeof(int16_t), av_buffer_allocz);
326 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
328 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
329 !h->ref_index_pool) {
330 av_buffer_pool_uninit(&h->qscale_table_pool);
331 av_buffer_pool_uninit(&h->mb_type_pool);
332 av_buffer_pool_uninit(&h->motion_val_pool);
333 av_buffer_pool_uninit(&h->ref_index_pool);
334 return AVERROR(ENOMEM);
340 static int alloc_picture(H264Context *h, Picture *pic)
344 av_assert0(!pic->f.data[0]);
346 if (h->avctx->hwaccel) {
347 const AVHWAccel *hwaccel = h->avctx->hwaccel;
348 av_assert0(!pic->hwaccel_picture_private);
349 if (hwaccel->priv_data_size) {
350 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
351 if (!pic->hwaccel_priv_buf)
352 return AVERROR(ENOMEM);
353 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
357 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
358 AV_GET_BUFFER_FLAG_REF : 0);
362 h->linesize = pic->f.linesize[0];
363 h->uvlinesize = pic->f.linesize[1];
365 if (!h->qscale_table_pool) {
366 ret = init_table_pools(h);
371 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
372 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
373 if (!pic->qscale_table_buf || !pic->mb_type_buf)
376 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
377 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
379 for (i = 0; i < 2; i++) {
380 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
381 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
382 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
385 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
386 pic->ref_index[i] = pic->ref_index_buf[i]->data;
391 unref_picture(h, pic);
392 return (ret < 0) ? ret : AVERROR(ENOMEM);
395 static inline int pic_is_unused(H264Context *h, Picture *pic)
397 if ( (h->avctx->active_thread_type & FF_THREAD_FRAME)
398 && pic->f.qscale_table //check if the frame has anything allocated
399 && pic->period_since_free < h->avctx->thread_count)
401 if (pic->f.data[0] == NULL)
403 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
408 static int find_unused_picture(H264Context *h)
412 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
413 if (pic_is_unused(h, &h->DPB[i]))
416 if (i == MAX_PICTURE_COUNT)
417 return AVERROR_INVALIDDATA;
419 if (h->DPB[i].needs_realloc) {
420 h->DPB[i].needs_realloc = 0;
421 unref_picture(h, &h->DPB[i]);
428 * Check if the top & left blocks are available if needed and
429 * change the dc mode so it only uses the available blocks.
431 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
433 static const int8_t top[12] = {
434 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
436 static const int8_t left[12] = {
437 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
441 if (!(h->top_samples_available & 0x8000)) {
442 for (i = 0; i < 4; i++) {
443 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
445 av_log(h->avctx, AV_LOG_ERROR,
446 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
447 status, h->mb_x, h->mb_y);
450 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
455 if ((h->left_samples_available & 0x8888) != 0x8888) {
456 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
457 for (i = 0; i < 4; i++)
458 if (!(h->left_samples_available & mask[i])) {
459 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
461 av_log(h->avctx, AV_LOG_ERROR,
462 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
463 status, h->mb_x, h->mb_y);
466 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
472 } // FIXME cleanup like ff_h264_check_intra_pred_mode
475 * Check if the top & left blocks are available if needed and
476 * change the dc mode so it only uses the available blocks.
478 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
480 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
481 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
484 av_log(h->avctx, AV_LOG_ERROR,
485 "out of range intra chroma pred mode at %d %d\n",
490 if (!(h->top_samples_available & 0x8000)) {
493 av_log(h->avctx, AV_LOG_ERROR,
494 "top block unavailable for requested intra mode at %d %d\n",
500 if ((h->left_samples_available & 0x8080) != 0x8080) {
502 if (is_chroma && (h->left_samples_available & 0x8080)) {
503 // mad cow disease mode, aka MBAFF + constrained_intra_pred
504 mode = ALZHEIMER_DC_L0T_PRED8x8 +
505 (!(h->left_samples_available & 0x8000)) +
506 2 * (mode == DC_128_PRED8x8);
509 av_log(h->avctx, AV_LOG_ERROR,
510 "left block unavailable for requested intra mode at %d %d\n",
519 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
520 int *dst_length, int *consumed, int length)
526 // src[0]&0x80; // forbidden bit
527 h->nal_ref_idc = src[0] >> 5;
528 h->nal_unit_type = src[0] & 0x1F;
533 #define STARTCODE_TEST \
534 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
535 if (src[i + 2] != 3) { \
536 /* startcode, so we must be past the end */ \
541 #if HAVE_FAST_UNALIGNED
542 #define FIND_FIRST_ZERO \
543 if (i > 0 && !src[i]) \
548 for (i = 0; i + 1 < length; i += 9) {
549 if (!((~AV_RN64A(src + i) &
550 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
551 0x8000800080008080ULL))
558 for (i = 0; i + 1 < length; i += 5) {
559 if (!((~AV_RN32A(src + i) &
560 (AV_RN32A(src + i) - 0x01000101U)) &
569 for (i = 0; i + 1 < length; i += 2) {
572 if (i > 0 && src[i - 1] == 0)
578 // use second escape buffer for inter data
579 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
581 si = h->rbsp_buffer_size[bufidx];
582 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
583 dst = h->rbsp_buffer[bufidx];
588 if(i>=length-1){ //no escaped 0
590 *consumed= length+1; //+1 for the header
591 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
594 memcpy(dst, src, length);
601 while (si + 2 < length) {
602 // remove escapes (very rare 1:2^22)
603 if (src[si + 2] > 3) {
604 dst[di++] = src[si++];
605 dst[di++] = src[si++];
606 } else if (src[si] == 0 && src[si + 1] == 0) {
607 if (src[si + 2] == 3) { // escape
612 } else // next start code
616 dst[di++] = src[si++];
619 dst[di++] = src[si++];
622 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
625 *consumed = si + 1; // +1 for the header
626 /* FIXME store exact number of bits in the getbitcontext
627 * (it is needed for decoding) */
632 * Identify the exact end of the bitstream
633 * @return the length of the trailing, or 0 if damaged
635 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
640 tprintf(h->avctx, "rbsp trailing %X\n", v);
642 for (r = 1; r < 9; r++) {
650 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
651 int height, int y_offset, int list)
653 int raw_my = h->mv_cache[list][scan8[n]][1];
654 int filter_height_down = (raw_my & 3) ? 3 : 0;
655 int full_my = (raw_my >> 2) + y_offset;
656 int bottom = full_my + filter_height_down + height;
658 av_assert2(height >= 0);
660 return FFMAX(0, bottom);
663 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
664 int height, int y_offset, int list0,
665 int list1, int *nrefs)
669 y_offset += 16 * (h->mb_y >> MB_FIELD);
672 int ref_n = h->ref_cache[0][scan8[n]];
673 Picture *ref = &h->ref_list[0][ref_n];
675 // Error resilience puts the current picture in the ref list.
676 // Don't try to wait on these as it will cause a deadlock.
677 // Fields can wait on each other, though.
678 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
679 (ref->reference & 3) != h->picture_structure) {
680 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
681 if (refs[0][ref_n] < 0)
683 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
688 int ref_n = h->ref_cache[1][scan8[n]];
689 Picture *ref = &h->ref_list[1][ref_n];
691 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
692 (ref->reference & 3) != h->picture_structure) {
693 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
694 if (refs[1][ref_n] < 0)
696 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
702 * Wait until all reference frames are available for MC operations.
704 * @param h the H264 context
706 static void await_references(H264Context *h)
708 const int mb_xy = h->mb_xy;
709 const int mb_type = h->cur_pic.mb_type[mb_xy];
711 int nrefs[2] = { 0 };
714 memset(refs, -1, sizeof(refs));
716 if (IS_16X16(mb_type)) {
717 get_lowest_part_y(h, refs, 0, 16, 0,
718 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
719 } else if (IS_16X8(mb_type)) {
720 get_lowest_part_y(h, refs, 0, 8, 0,
721 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
722 get_lowest_part_y(h, refs, 8, 8, 8,
723 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
724 } else if (IS_8X16(mb_type)) {
725 get_lowest_part_y(h, refs, 0, 16, 0,
726 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
727 get_lowest_part_y(h, refs, 4, 16, 0,
728 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
732 av_assert2(IS_8X8(mb_type));
734 for (i = 0; i < 4; i++) {
735 const int sub_mb_type = h->sub_mb_type[i];
737 int y_offset = (i & 2) << 2;
739 if (IS_SUB_8X8(sub_mb_type)) {
740 get_lowest_part_y(h, refs, n, 8, y_offset,
741 IS_DIR(sub_mb_type, 0, 0),
742 IS_DIR(sub_mb_type, 0, 1),
744 } else if (IS_SUB_8X4(sub_mb_type)) {
745 get_lowest_part_y(h, refs, n, 4, y_offset,
746 IS_DIR(sub_mb_type, 0, 0),
747 IS_DIR(sub_mb_type, 0, 1),
749 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
750 IS_DIR(sub_mb_type, 0, 0),
751 IS_DIR(sub_mb_type, 0, 1),
753 } else if (IS_SUB_4X8(sub_mb_type)) {
754 get_lowest_part_y(h, refs, n, 8, y_offset,
755 IS_DIR(sub_mb_type, 0, 0),
756 IS_DIR(sub_mb_type, 0, 1),
758 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
759 IS_DIR(sub_mb_type, 0, 0),
760 IS_DIR(sub_mb_type, 0, 1),
764 av_assert2(IS_SUB_4X4(sub_mb_type));
765 for (j = 0; j < 4; j++) {
766 int sub_y_offset = y_offset + 2 * (j & 2);
767 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
768 IS_DIR(sub_mb_type, 0, 0),
769 IS_DIR(sub_mb_type, 0, 1),
776 for (list = h->list_count - 1; list >= 0; list--)
777 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
778 int row = refs[list][ref];
780 Picture *ref_pic = &h->ref_list[list][ref];
781 int ref_field = ref_pic->reference - 1;
782 int ref_field_picture = ref_pic->field_picture;
783 int pic_height = 16 * h->mb_height >> ref_field_picture;
788 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
789 ff_thread_await_progress(&ref_pic->tf,
790 FFMIN((row >> 1) - !(row & 1),
793 ff_thread_await_progress(&ref_pic->tf,
794 FFMIN((row >> 1), pic_height - 1),
796 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
797 ff_thread_await_progress(&ref_pic->tf,
798 FFMIN(row * 2 + ref_field,
801 } else if (FIELD_PICTURE) {
802 ff_thread_await_progress(&ref_pic->tf,
803 FFMIN(row, pic_height - 1),
806 ff_thread_await_progress(&ref_pic->tf,
807 FFMIN(row, pic_height - 1),
814 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
815 int n, int square, int height,
817 uint8_t *dest_y, uint8_t *dest_cb,
819 int src_x_offset, int src_y_offset,
820 qpel_mc_func *qpix_op,
821 h264_chroma_mc_func chroma_op,
822 int pixel_shift, int chroma_idc)
824 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
825 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
826 const int luma_xy = (mx & 3) + ((my & 3) << 2);
827 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
828 uint8_t *src_y = pic->f.data[0] + offset;
829 uint8_t *src_cb, *src_cr;
831 int extra_height = 0;
833 const int full_mx = mx >> 2;
834 const int full_my = my >> 2;
835 const int pic_width = 16 * h->mb_width;
836 const int pic_height = 16 * h->mb_height >> MB_FIELD;
844 if (full_mx < 0 - extra_width ||
845 full_my < 0 - extra_height ||
846 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
847 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
848 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
849 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
851 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
852 full_my - 2, pic_width, pic_height);
853 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
857 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
859 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
861 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
864 if (chroma_idc == 3 /* yuv444 */) {
865 src_cb = pic->f.data[1] + offset;
867 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
868 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
870 16 + 5, 16 + 5 /*FIXME*/,
871 full_mx - 2, full_my - 2,
872 pic_width, pic_height);
873 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
875 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
877 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
879 src_cr = pic->f.data[2] + offset;
881 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
882 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
884 16 + 5, 16 + 5 /*FIXME*/,
885 full_mx - 2, full_my - 2,
886 pic_width, pic_height);
887 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
889 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
891 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
895 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
896 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
897 // chroma offset when predicting from a field of opposite parity
898 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
899 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
902 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
903 (my >> ysh) * h->mb_uvlinesize;
904 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
905 (my >> ysh) * h->mb_uvlinesize;
908 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
909 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
910 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
911 src_cb = h->edge_emu_buffer;
913 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
914 height >> (chroma_idc == 1 /* yuv420 */),
915 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
918 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
919 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
920 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
921 src_cr = h->edge_emu_buffer;
923 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
924 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
927 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
928 int height, int delta,
929 uint8_t *dest_y, uint8_t *dest_cb,
931 int x_offset, int y_offset,
932 qpel_mc_func *qpix_put,
933 h264_chroma_mc_func chroma_put,
934 qpel_mc_func *qpix_avg,
935 h264_chroma_mc_func chroma_avg,
936 int list0, int list1,
937 int pixel_shift, int chroma_idc)
939 qpel_mc_func *qpix_op = qpix_put;
940 h264_chroma_mc_func chroma_op = chroma_put;
942 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
943 if (chroma_idc == 3 /* yuv444 */) {
944 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
945 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
946 } else if (chroma_idc == 2 /* yuv422 */) {
947 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
948 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
949 } else { /* yuv420 */
950 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
951 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
953 x_offset += 8 * h->mb_x;
954 y_offset += 8 * (h->mb_y >> MB_FIELD);
957 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
958 mc_dir_part(h, ref, n, square, height, delta, 0,
959 dest_y, dest_cb, dest_cr, x_offset, y_offset,
960 qpix_op, chroma_op, pixel_shift, chroma_idc);
963 chroma_op = chroma_avg;
967 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
968 mc_dir_part(h, ref, n, square, height, delta, 1,
969 dest_y, dest_cb, dest_cr, x_offset, y_offset,
970 qpix_op, chroma_op, pixel_shift, chroma_idc);
974 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
975 int height, int delta,
976 uint8_t *dest_y, uint8_t *dest_cb,
978 int x_offset, int y_offset,
979 qpel_mc_func *qpix_put,
980 h264_chroma_mc_func chroma_put,
981 h264_weight_func luma_weight_op,
982 h264_weight_func chroma_weight_op,
983 h264_biweight_func luma_weight_avg,
984 h264_biweight_func chroma_weight_avg,
985 int list0, int list1,
986 int pixel_shift, int chroma_idc)
990 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
991 if (chroma_idc == 3 /* yuv444 */) {
992 chroma_height = height;
993 chroma_weight_avg = luma_weight_avg;
994 chroma_weight_op = luma_weight_op;
995 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
996 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
997 } else if (chroma_idc == 2 /* yuv422 */) {
998 chroma_height = height;
999 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1000 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1001 } else { /* yuv420 */
1002 chroma_height = height >> 1;
1003 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1004 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1006 x_offset += 8 * h->mb_x;
1007 y_offset += 8 * (h->mb_y >> MB_FIELD);
1009 if (list0 && list1) {
1010 /* don't optimize for luma-only case, since B-frames usually
1011 * use implicit weights => chroma too. */
1012 uint8_t *tmp_cb = h->bipred_scratchpad;
1013 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1014 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1015 int refn0 = h->ref_cache[0][scan8[n]];
1016 int refn1 = h->ref_cache[1][scan8[n]];
1018 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1019 dest_y, dest_cb, dest_cr,
1020 x_offset, y_offset, qpix_put, chroma_put,
1021 pixel_shift, chroma_idc);
1022 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1023 tmp_y, tmp_cb, tmp_cr,
1024 x_offset, y_offset, qpix_put, chroma_put,
1025 pixel_shift, chroma_idc);
1027 if (h->use_weight == 2) {
1028 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1029 int weight1 = 64 - weight0;
1030 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1031 height, 5, weight0, weight1, 0);
1032 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1033 chroma_height, 5, weight0, weight1, 0);
1034 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1035 chroma_height, 5, weight0, weight1, 0);
1037 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1038 h->luma_log2_weight_denom,
1039 h->luma_weight[refn0][0][0],
1040 h->luma_weight[refn1][1][0],
1041 h->luma_weight[refn0][0][1] +
1042 h->luma_weight[refn1][1][1]);
1043 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1044 h->chroma_log2_weight_denom,
1045 h->chroma_weight[refn0][0][0][0],
1046 h->chroma_weight[refn1][1][0][0],
1047 h->chroma_weight[refn0][0][0][1] +
1048 h->chroma_weight[refn1][1][0][1]);
1049 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1050 h->chroma_log2_weight_denom,
1051 h->chroma_weight[refn0][0][1][0],
1052 h->chroma_weight[refn1][1][1][0],
1053 h->chroma_weight[refn0][0][1][1] +
1054 h->chroma_weight[refn1][1][1][1]);
1057 int list = list1 ? 1 : 0;
1058 int refn = h->ref_cache[list][scan8[n]];
1059 Picture *ref = &h->ref_list[list][refn];
1060 mc_dir_part(h, ref, n, square, height, delta, list,
1061 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1062 qpix_put, chroma_put, pixel_shift, chroma_idc);
1064 luma_weight_op(dest_y, h->mb_linesize, height,
1065 h->luma_log2_weight_denom,
1066 h->luma_weight[refn][list][0],
1067 h->luma_weight[refn][list][1]);
1068 if (h->use_weight_chroma) {
1069 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1070 h->chroma_log2_weight_denom,
1071 h->chroma_weight[refn][list][0][0],
1072 h->chroma_weight[refn][list][0][1]);
1073 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1074 h->chroma_log2_weight_denom,
1075 h->chroma_weight[refn][list][1][0],
1076 h->chroma_weight[refn][list][1][1]);
1081 static av_always_inline void prefetch_motion(H264Context *h, int list,
1082 int pixel_shift, int chroma_idc)
1084 /* fetch pixels for estimated mv 4 macroblocks ahead
1085 * optimized for 64byte cache lines */
1086 const int refn = h->ref_cache[list][scan8[0]];
1088 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1089 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1090 uint8_t **src = h->ref_list[list][refn].f.data;
1091 int off = (mx << pixel_shift) +
1092 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1093 (64 << pixel_shift);
1094 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1095 if (chroma_idc == 3 /* yuv444 */) {
1096 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1097 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1099 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
1100 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1105 static void free_tables(H264Context *h, int free_rbsp)
1110 av_freep(&h->intra4x4_pred_mode);
1111 av_freep(&h->chroma_pred_mode_table);
1112 av_freep(&h->cbp_table);
1113 av_freep(&h->mvd_table[0]);
1114 av_freep(&h->mvd_table[1]);
1115 av_freep(&h->direct_table);
1116 av_freep(&h->non_zero_count);
1117 av_freep(&h->slice_table_base);
1118 h->slice_table = NULL;
1119 av_freep(&h->list_counts);
1121 av_freep(&h->mb2b_xy);
1122 av_freep(&h->mb2br_xy);
1124 for (i = 0; i < 3; i++)
1125 av_freep(&h->visualization_buffer[i]);
1127 av_buffer_pool_uninit(&h->qscale_table_pool);
1128 av_buffer_pool_uninit(&h->mb_type_pool);
1129 av_buffer_pool_uninit(&h->motion_val_pool);
1130 av_buffer_pool_uninit(&h->ref_index_pool);
1132 if (free_rbsp && h->DPB) {
1133 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1134 unref_picture(h, &h->DPB[i]);
1136 } else if (h->DPB) {
1137 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1138 h->DPB[i].needs_realloc = 1;
1141 h->cur_pic_ptr = NULL;
1143 for (i = 0; i < MAX_THREADS; i++) {
1144 hx = h->thread_context[i];
1147 av_freep(&hx->top_borders[1]);
1148 av_freep(&hx->top_borders[0]);
1149 av_freep(&hx->bipred_scratchpad);
1150 av_freep(&hx->edge_emu_buffer);
1151 av_freep(&hx->dc_val_base);
1152 av_freep(&hx->me.scratchpad);
1153 av_freep(&hx->er.mb_index2xy);
1154 av_freep(&hx->er.error_status_table);
1155 av_freep(&hx->er.er_temp_buffer);
1156 av_freep(&hx->er.mbintra_table);
1157 av_freep(&hx->er.mbskip_table);
1160 av_freep(&hx->rbsp_buffer[1]);
1161 av_freep(&hx->rbsp_buffer[0]);
1162 hx->rbsp_buffer_size[0] = 0;
1163 hx->rbsp_buffer_size[1] = 0;
1166 av_freep(&h->thread_context[i]);
1170 static void init_dequant8_coeff_table(H264Context *h)
1173 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1175 for (i = 0; i < 6; i++) {
1176 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1177 for (j = 0; j < i; j++)
1178 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1179 64 * sizeof(uint8_t))) {
1180 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1186 for (q = 0; q < max_qp + 1; q++) {
1187 int shift = div6[q];
1189 for (x = 0; x < 64; x++)
1190 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1191 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1192 h->pps.scaling_matrix8[i][x]) << shift;
1197 static void init_dequant4_coeff_table(H264Context *h)
1200 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1201 for (i = 0; i < 6; i++) {
1202 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1203 for (j = 0; j < i; j++)
1204 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1205 16 * sizeof(uint8_t))) {
1206 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1212 for (q = 0; q < max_qp + 1; q++) {
1213 int shift = div6[q] + 2;
1215 for (x = 0; x < 16; x++)
1216 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1217 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1218 h->pps.scaling_matrix4[i][x]) << shift;
1223 static void init_dequant_tables(H264Context *h)
1226 init_dequant4_coeff_table(h);
1227 if (h->pps.transform_8x8_mode)
1228 init_dequant8_coeff_table(h);
1229 if (h->sps.transform_bypass) {
1230 for (i = 0; i < 6; i++)
1231 for (x = 0; x < 16; x++)
1232 h->dequant4_coeff[i][0][x] = 1 << 6;
1233 if (h->pps.transform_8x8_mode)
1234 for (i = 0; i < 6; i++)
1235 for (x = 0; x < 64; x++)
1236 h->dequant8_coeff[i][0][x] = 1 << 6;
1240 int ff_h264_alloc_tables(H264Context *h)
1242 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1243 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1246 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1247 row_mb_num * 8 * sizeof(uint8_t), fail)
1248 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1249 big_mb_num * 48 * sizeof(uint8_t), fail)
1250 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1251 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1252 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1253 big_mb_num * sizeof(uint16_t), fail)
1254 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1255 big_mb_num * sizeof(uint8_t), fail)
1256 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1257 16 * row_mb_num * sizeof(uint8_t), fail);
1258 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1259 16 * row_mb_num * sizeof(uint8_t), fail);
1260 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1261 4 * big_mb_num * sizeof(uint8_t), fail);
1262 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1263 big_mb_num * sizeof(uint8_t), fail)
1265 memset(h->slice_table_base, -1,
1266 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1267 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1269 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1270 big_mb_num * sizeof(uint32_t), fail);
1271 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1272 big_mb_num * sizeof(uint32_t), fail);
1273 for (y = 0; y < h->mb_height; y++)
1274 for (x = 0; x < h->mb_width; x++) {
1275 const int mb_xy = x + y * h->mb_stride;
1276 const int b_xy = 4 * x + 4 * y * h->b_stride;
1278 h->mb2b_xy[mb_xy] = b_xy;
1279 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1282 if (!h->dequant4_coeff[0])
1283 init_dequant_tables(h);
1286 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1288 return AVERROR(ENOMEM);
1289 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1290 avcodec_get_frame_defaults(&h->DPB[i].f);
1291 avcodec_get_frame_defaults(&h->cur_pic.f);
1302 * Mimic alloc_tables(), but for every context thread.
1304 static void clone_tables(H264Context *dst, H264Context *src, int i)
1306 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1307 dst->non_zero_count = src->non_zero_count;
1308 dst->slice_table = src->slice_table;
1309 dst->cbp_table = src->cbp_table;
1310 dst->mb2b_xy = src->mb2b_xy;
1311 dst->mb2br_xy = src->mb2br_xy;
1312 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1313 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1314 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1315 dst->direct_table = src->direct_table;
1316 dst->list_counts = src->list_counts;
1317 dst->DPB = src->DPB;
1318 dst->cur_pic_ptr = src->cur_pic_ptr;
1319 dst->cur_pic = src->cur_pic;
1320 dst->bipred_scratchpad = NULL;
1321 dst->edge_emu_buffer = NULL;
1322 dst->me.scratchpad = NULL;
1323 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1324 src->sps.chroma_format_idc);
1329 * Allocate buffers which are not shared amongst multiple threads.
1331 static int context_init(H264Context *h)
1333 ERContext *er = &h->er;
1334 int mb_array_size = h->mb_height * h->mb_stride;
1335 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1336 int c_size = h->mb_stride * (h->mb_height + 1);
1337 int yc_size = y_size + 2 * c_size;
1340 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1341 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1342 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1343 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1345 h->ref_cache[0][scan8[5] + 1] =
1346 h->ref_cache[0][scan8[7] + 1] =
1347 h->ref_cache[0][scan8[13] + 1] =
1348 h->ref_cache[1][scan8[5] + 1] =
1349 h->ref_cache[1][scan8[7] + 1] =
1350 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1352 if (CONFIG_ERROR_RESILIENCE) {
1354 er->avctx = h->avctx;
1356 er->decode_mb = h264_er_decode_mb;
1358 er->quarter_sample = 1;
1360 er->mb_num = h->mb_num;
1361 er->mb_width = h->mb_width;
1362 er->mb_height = h->mb_height;
1363 er->mb_stride = h->mb_stride;
1364 er->b8_stride = h->mb_width * 2 + 1;
1366 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1367 fail); // error ressilience code looks cleaner with this
1368 for (y = 0; y < h->mb_height; y++)
1369 for (x = 0; x < h->mb_width; x++)
1370 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1372 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1373 h->mb_stride + h->mb_width;
1375 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1376 mb_array_size * sizeof(uint8_t), fail);
1378 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1379 memset(er->mbintra_table, 1, mb_array_size);
1381 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1383 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1386 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1387 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1388 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1389 er->dc_val[2] = er->dc_val[1] + c_size;
1390 for (i = 0; i < yc_size; i++)
1391 h->dc_val_base[i] = 1024;
1397 return -1; // free_tables will clean up for us
1400 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1401 int parse_extradata);
1403 static av_cold void common_init(H264Context *h)
1406 h->width = h->avctx->width;
1407 h->height = h->avctx->height;
1409 h->bit_depth_luma = 8;
1410 h->chroma_format_idc = 1;
1412 h->avctx->bits_per_raw_sample = 8;
1413 h->cur_chroma_format_idc = 1;
1415 ff_h264dsp_init(&h->h264dsp, 8, 1);
1416 av_assert0(h->sps.bit_depth_chroma == 0);
1417 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1418 ff_h264qpel_init(&h->h264qpel, 8);
1419 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1421 h->dequant_coeff_pps = -1;
1423 if (CONFIG_ERROR_RESILIENCE) {
1424 h->dsp.dct_bits = 16;
1425 /* needed so that IDCT permutation is known early */
1426 ff_dsputil_init(&h->dsp, h->avctx);
1428 ff_videodsp_init(&h->vdsp, 8);
1430 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1431 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1434 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1436 AVCodecContext *avctx = h->avctx;
1438 if (!buf || size <= 0)
1442 int i, cnt, nalsize;
1443 const unsigned char *p = buf;
1448 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1451 /* sps and pps in the avcC always have length coded with 2 bytes,
1452 * so put a fake nal_length_size = 2 while parsing them */
1453 h->nal_length_size = 2;
1454 // Decode sps from avcC
1455 cnt = *(p + 5) & 0x1f; // Number of sps
1457 for (i = 0; i < cnt; i++) {
1458 nalsize = AV_RB16(p) + 2;
1459 if(nalsize > size - (p-buf))
1461 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1462 av_log(avctx, AV_LOG_ERROR,
1463 "Decoding sps %d from avcC failed\n", i);
1468 // Decode pps from avcC
1469 cnt = *(p++); // Number of pps
1470 for (i = 0; i < cnt; i++) {
1471 nalsize = AV_RB16(p) + 2;
1472 if(nalsize > size - (p-buf))
1474 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1475 av_log(avctx, AV_LOG_ERROR,
1476 "Decoding pps %d from avcC failed\n", i);
1481 // Now store right nal length size, that will be used to parse all other nals
1482 h->nal_length_size = (buf[4] & 0x03) + 1;
1485 if (decode_nal_units(h, buf, size, 1) < 0)
1491 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1493 H264Context *h = avctx->priv_data;
1499 h->picture_structure = PICT_FRAME;
1500 h->slice_context_count = 1;
1501 h->workaround_bugs = avctx->workaround_bugs;
1502 h->flags = avctx->flags;
1505 // s->decode_mb = ff_h263_decode_mb;
1506 if (!avctx->has_b_frames)
1509 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1511 ff_h264_decode_init_vlc();
1514 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1516 h->thread_context[0] = h;
1517 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1518 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1519 h->last_pocs[i] = INT_MIN;
1520 h->prev_poc_msb = 1 << 16;
1521 h->prev_frame_num = -1;
1523 ff_h264_reset_sei(h);
1524 if (avctx->codec_id == AV_CODEC_ID_H264) {
1525 if (avctx->ticks_per_frame == 1) {
1526 if(h->avctx->time_base.den < INT_MAX/2) {
1527 h->avctx->time_base.den *= 2;
1529 h->avctx->time_base.num /= 2;
1531 avctx->ticks_per_frame = 2;
1534 if (avctx->extradata_size > 0 && avctx->extradata &&
1535 ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
1536 ff_h264_free_context(h);
1540 if (h->sps.bitstream_restriction_flag &&
1541 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1542 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1546 ff_init_cabac_states();
1547 avctx->internal->allocate_progress = 1;
1552 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1553 #undef REBASE_PICTURE
1554 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1555 ((pic && pic >= old_ctx->DPB && \
1556 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1557 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1559 static void copy_picture_range(Picture **to, Picture **from, int count,
1560 H264Context *new_base,
1561 H264Context *old_base)
1565 for (i = 0; i < count; i++) {
1566 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1567 IN_RANGE(from[i], old_base->DPB,
1568 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1570 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1574 static void copy_parameter_set(void **to, void **from, int count, int size)
1578 for (i = 0; i < count; i++) {
1579 if (to[i] && !from[i])
1581 else if (from[i] && !to[i])
1582 to[i] = av_malloc(size);
1585 memcpy(to[i], from[i], size);
1589 static int decode_init_thread_copy(AVCodecContext *avctx)
1591 H264Context *h = avctx->priv_data;
1593 if (!avctx->internal->is_copy)
1595 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1596 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1598 h->context_initialized = 0;
1603 #define copy_fields(to, from, start_field, end_field) \
1604 memcpy(&to->start_field, &from->start_field, \
1605 (char *)&to->end_field - (char *)&to->start_field)
1607 static int h264_slice_header_init(H264Context *, int);
1609 static int h264_set_parameter_from_sps(H264Context *h);
1611 static int decode_update_thread_context(AVCodecContext *dst,
1612 const AVCodecContext *src)
1614 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1615 int inited = h->context_initialized, err = 0;
1616 int context_reinitialized = 0;
1623 (h->width != h1->width ||
1624 h->height != h1->height ||
1625 h->mb_width != h1->mb_width ||
1626 h->mb_height != h1->mb_height ||
1627 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1628 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1629 h->sps.colorspace != h1->sps.colorspace)) {
1631 av_freep(&h->bipred_scratchpad);
1633 h->width = h1->width;
1634 h->height = h1->height;
1635 h->mb_height = h1->mb_height;
1636 h->mb_width = h1->mb_width;
1637 h->mb_num = h1->mb_num;
1638 h->mb_stride = h1->mb_stride;
1639 h->b_stride = h1->b_stride;
1641 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1642 MAX_SPS_COUNT, sizeof(SPS));
1644 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1645 MAX_PPS_COUNT, sizeof(PPS));
1648 if ((err = h264_slice_header_init(h, 1)) < 0) {
1649 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1652 context_reinitialized = 1;
1655 h264_set_parameter_from_sps(h);
1656 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1657 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1660 /* update linesize on resize for h264. The h264 decoder doesn't
1661 * necessarily call ff_MPV_frame_start in the new thread */
1662 h->linesize = h1->linesize;
1663 h->uvlinesize = h1->uvlinesize;
1665 /* copy block_offset since frame_start may not be called */
1666 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1669 for (i = 0; i < MAX_SPS_COUNT; i++)
1670 av_freep(h->sps_buffers + i);
1672 for (i = 0; i < MAX_PPS_COUNT; i++)
1673 av_freep(h->pps_buffers + i);
1675 memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1676 memcpy(&h->cabac, &h1->cabac,
1677 sizeof(H264Context) - offsetof(H264Context, cabac));
1678 av_assert0((void*)&h->cabac == &h->mb_padding + 1);
1680 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1681 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1683 memset(&h->er, 0, sizeof(h->er));
1684 memset(&h->me, 0, sizeof(h->me));
1687 h->qscale_table_pool = NULL;
1688 h->mb_type_pool = NULL;
1689 h->ref_index_pool = NULL;
1690 h->motion_val_pool = NULL;
1692 if (h1->context_initialized) {
1693 h->context_initialized = 0;
1695 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1696 avcodec_get_frame_defaults(&h->cur_pic.f);
1697 h->cur_pic.tf.f = &h->cur_pic.f;
1699 if (ff_h264_alloc_tables(h) < 0) {
1700 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1701 return AVERROR(ENOMEM);
1706 for (i = 0; i < 2; i++) {
1707 h->rbsp_buffer[i] = NULL;
1708 h->rbsp_buffer_size[i] = 0;
1710 h->bipred_scratchpad = NULL;
1711 h->edge_emu_buffer = NULL;
1713 h->thread_context[0] = h;
1714 h->context_initialized = h1->context_initialized;
1717 h->avctx->coded_height = h1->avctx->coded_height;
1718 h->avctx->coded_width = h1->avctx->coded_width;
1719 h->avctx->width = h1->avctx->width;
1720 h->avctx->height = h1->avctx->height;
1721 h->coded_picture_number = h1->coded_picture_number;
1722 h->first_field = h1->first_field;
1723 h->picture_structure = h1->picture_structure;
1724 h->qscale = h1->qscale;
1725 h->droppable = h1->droppable;
1726 h->data_partitioning = h1->data_partitioning;
1727 h->low_delay = h1->low_delay;
1729 for (i = 0; h->DPB && i < MAX_PICTURE_COUNT; i++) {
1730 h->DPB[i].period_since_free ++;
1731 unref_picture(h, &h->DPB[i]);
1732 if (h1->DPB[i].f.data[0] &&
1733 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1737 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1738 unref_picture(h, &h->cur_pic);
1739 if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1742 h->workaround_bugs = h1->workaround_bugs;
1743 h->low_delay = h1->low_delay;
1744 h->droppable = h1->droppable;
1746 // extradata/NAL handling
1747 h->is_avc = h1->is_avc;
1750 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1751 MAX_SPS_COUNT, sizeof(SPS));
1753 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1754 MAX_PPS_COUNT, sizeof(PPS));
1757 // Dequantization matrices
1758 // FIXME these are big - can they be only copied when PPS changes?
1759 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1761 for (i = 0; i < 6; i++)
1762 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1763 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1765 for (i = 0; i < 6; i++)
1766 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1767 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1769 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1772 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1775 copy_fields(h, h1, short_ref, cabac_init_idc);
1777 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1778 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1779 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1780 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1782 h->last_slice_type = h1->last_slice_type;
1784 memcpy(h->last_ref_count, h1->last_ref_count, sizeof(h->last_ref_count));
1786 if (context_reinitialized)
1787 h264_set_parameter_from_sps(h);
1789 if (!h->cur_pic_ptr)
1792 if (!h->droppable) {
1793 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1794 h->prev_poc_msb = h->poc_msb;
1795 h->prev_poc_lsb = h->poc_lsb;
1797 h->prev_frame_num_offset = h->frame_num_offset;
1798 h->prev_frame_num = h->frame_num;
1799 h->outputed_poc = h->next_outputed_poc;
1804 int ff_h264_frame_start(H264Context *h)
1808 const int pixel_shift = h->pixel_shift;
1810 1<<(h->sps.bit_depth_luma-1),
1811 1<<(h->sps.bit_depth_chroma-1),
1812 1<<(h->sps.bit_depth_chroma-1),
1816 if (!ff_thread_can_start_frame(h->avctx)) {
1817 av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1821 release_unused_pictures(h, 1);
1822 h->cur_pic_ptr = NULL;
1824 i = find_unused_picture(h);
1826 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1831 pic->reference = h->droppable ? 0 : h->picture_structure;
1832 pic->f.coded_picture_number = h->coded_picture_number++;
1833 pic->field_picture = h->picture_structure != PICT_FRAME;
1836 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1838 * See decode_nal_units().
1840 pic->f.key_frame = 0;
1842 pic->mmco_reset = 0;
1844 if ((ret = alloc_picture(h, pic)) < 0)
1846 if(!h->sync && !h->avctx->hwaccel &&
1847 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1848 avpriv_color_frame(&pic->f, c);
1850 h->cur_pic_ptr = pic;
1851 unref_picture(h, &h->cur_pic);
1852 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1855 if (CONFIG_ERROR_RESILIENCE) {
1856 ff_er_frame_start(&h->er);
1858 h->er.next_pic = NULL;
1861 assert(h->linesize && h->uvlinesize);
1863 for (i = 0; i < 16; i++) {
1864 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1865 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1867 for (i = 0; i < 16; i++) {
1868 h->block_offset[16 + i] =
1869 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1870 h->block_offset[48 + 16 + i] =
1871 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1874 /* Some macroblocks can be accessed before they're available in case
1875 * of lost slices, MBAFF or threading. */
1876 memset(h->slice_table, -1,
1877 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1879 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1880 // h->cur_pic.reference /* || h->contains_intra */ || 1;
1882 /* We mark the current picture as non-reference after allocating it, so
1883 * that if we break out due to an error it can be released automatically
1884 * in the next ff_MPV_frame_start().
1885 * SVQ3 as well as most other codecs have only last/next/current and thus
1886 * get released even with set reference, besides SVQ3 and others do not
1887 * mark frames as reference later "naturally". */
1888 if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
1889 h->cur_pic_ptr->reference = 0;
1891 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1893 h->next_output_pic = NULL;
1895 assert(h->cur_pic_ptr->long_ref == 0);
1901 * Run setup operations that must be run after slice header decoding.
1902 * This includes finding the next displayed frame.
1904 * @param h h264 master context
1905 * @param setup_finished enough NALs have been read that we can call
1906 * ff_thread_finish_setup()
1908 static void decode_postinit(H264Context *h, int setup_finished)
1910 Picture *out = h->cur_pic_ptr;
1911 Picture *cur = h->cur_pic_ptr;
1912 int i, pics, out_of_order, out_idx;
1914 h->cur_pic_ptr->f.pict_type = h->pict_type;
1916 if (h->next_output_pic)
1919 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1920 /* FIXME: if we have two PAFF fields in one packet, we can't start
1921 * the next thread here. If we have one field per packet, we can.
1922 * The check in decode_nal_units() is not good enough to find this
1923 * yet, so we assume the worst for now. */
1924 // if (setup_finished)
1925 // ff_thread_finish_setup(h->avctx);
1929 cur->f.interlaced_frame = 0;
1930 cur->f.repeat_pict = 0;
1932 /* Signal interlacing information externally. */
1933 /* Prioritize picture timing SEI information over used
1934 * decoding process if it exists. */
1936 if (h->sps.pic_struct_present_flag) {
1937 switch (h->sei_pic_struct) {
1938 case SEI_PIC_STRUCT_FRAME:
1940 case SEI_PIC_STRUCT_TOP_FIELD:
1941 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1942 cur->f.interlaced_frame = 1;
1944 case SEI_PIC_STRUCT_TOP_BOTTOM:
1945 case SEI_PIC_STRUCT_BOTTOM_TOP:
1946 if (FIELD_OR_MBAFF_PICTURE)
1947 cur->f.interlaced_frame = 1;
1949 // try to flag soft telecine progressive
1950 cur->f.interlaced_frame = h->prev_interlaced_frame;
1952 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1953 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1954 /* Signal the possibility of telecined film externally
1955 * (pic_struct 5,6). From these hints, let the applications
1956 * decide if they apply deinterlacing. */
1957 cur->f.repeat_pict = 1;
1959 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1960 cur->f.repeat_pict = 2;
1962 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1963 cur->f.repeat_pict = 4;
1967 if ((h->sei_ct_type & 3) &&
1968 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1969 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1971 /* Derive interlacing flag from used decoding process. */
1972 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1974 h->prev_interlaced_frame = cur->f.interlaced_frame;
1976 if (cur->field_poc[0] != cur->field_poc[1]) {
1977 /* Derive top_field_first from field pocs. */
1978 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1980 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1981 /* Use picture timing SEI information. Even if it is a
1982 * information of a past frame, better than nothing. */
1983 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1984 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1985 cur->f.top_field_first = 1;
1987 cur->f.top_field_first = 0;
1989 /* Most likely progressive */
1990 cur->f.top_field_first = 0;
1994 cur->mmco_reset = h->mmco_reset;
1996 // FIXME do something with unavailable reference frames
1998 /* Sort B-frames into display order */
2000 if (h->sps.bitstream_restriction_flag &&
2001 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2002 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2006 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2007 !h->sps.bitstream_restriction_flag) {
2008 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2012 for (i = 0; 1; i++) {
2013 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2015 h->last_pocs[i-1] = cur->poc;
2018 h->last_pocs[i-1]= h->last_pocs[i];
2021 out_of_order = MAX_DELAYED_PIC_COUNT - i;
2022 if( cur->f.pict_type == AV_PICTURE_TYPE_B
2023 || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
2024 out_of_order = FFMAX(out_of_order, 1);
2025 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2026 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2027 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2028 h->last_pocs[i] = INT_MIN;
2029 h->last_pocs[0] = cur->poc;
2030 cur->mmco_reset = 1;
2031 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2032 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2033 h->avctx->has_b_frames = out_of_order;
2038 while (h->delayed_pic[pics])
2041 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
2043 h->delayed_pic[pics++] = cur;
2044 if (cur->reference == 0)
2045 cur->reference = DELAYED_PIC_REF;
2047 out = h->delayed_pic[0];
2049 for (i = 1; h->delayed_pic[i] &&
2050 !h->delayed_pic[i]->f.key_frame &&
2051 !h->delayed_pic[i]->mmco_reset;
2053 if (h->delayed_pic[i]->poc < out->poc) {
2054 out = h->delayed_pic[i];
2057 if (h->avctx->has_b_frames == 0 &&
2058 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2059 h->next_outputed_poc = INT_MIN;
2060 out_of_order = out->poc < h->next_outputed_poc;
2062 if (out_of_order || pics > h->avctx->has_b_frames) {
2063 out->reference &= ~DELAYED_PIC_REF;
2064 // for frame threading, the owner must be the second field's thread or
2065 // else the first thread can release the picture and reuse it unsafely
2066 for (i = out_idx; h->delayed_pic[i]; i++)
2067 h->delayed_pic[i] = h->delayed_pic[i + 1];
2069 if (!out_of_order && pics > h->avctx->has_b_frames) {
2070 h->next_output_pic = out;
2071 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2072 h->next_outputed_poc = INT_MIN;
2074 h->next_outputed_poc = out->poc;
2076 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2079 if (h->next_output_pic && h->next_output_pic->sync) {
2084 ff_thread_finish_setup(h->avctx);
2087 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2088 uint8_t *src_cb, uint8_t *src_cr,
2089 int linesize, int uvlinesize,
2092 uint8_t *top_border;
2094 const int pixel_shift = h->pixel_shift;
2095 int chroma444 = CHROMA444;
2096 int chroma422 = CHROMA422;
2099 src_cb -= uvlinesize;
2100 src_cr -= uvlinesize;
2102 if (!simple && FRAME_MBAFF) {
2105 top_border = h->top_borders[0][h->mb_x];
2106 AV_COPY128(top_border, src_y + 15 * linesize);
2108 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2109 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2112 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2113 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2114 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2115 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2117 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2118 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2120 } else if (chroma422) {
2122 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2123 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2125 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2126 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2130 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2131 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2133 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2134 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2139 } else if (MB_MBAFF) {
2145 top_border = h->top_borders[top_idx][h->mb_x];
2146 /* There are two lines saved, the line above the top macroblock
2147 * of a pair, and the line above the bottom macroblock. */
2148 AV_COPY128(top_border, src_y + 16 * linesize);
2150 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2152 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2155 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2156 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2157 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2158 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2160 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2161 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2163 } else if (chroma422) {
2165 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2166 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2168 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2169 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2173 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2174 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2176 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2177 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2183 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2184 uint8_t *src_cb, uint8_t *src_cr,
2185 int linesize, int uvlinesize,
2186 int xchg, int chroma444,
2187 int simple, int pixel_shift)
2189 int deblock_topleft;
2192 uint8_t *top_border_m1;
2193 uint8_t *top_border;
2195 if (!simple && FRAME_MBAFF) {
2200 top_idx = MB_MBAFF ? 0 : 1;
2204 if (h->deblocking_filter == 2) {
2205 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2206 deblock_top = h->top_type;
2208 deblock_topleft = (h->mb_x > 0);
2209 deblock_top = (h->mb_y > !!MB_FIELD);
2212 src_y -= linesize + 1 + pixel_shift;
2213 src_cb -= uvlinesize + 1 + pixel_shift;
2214 src_cr -= uvlinesize + 1 + pixel_shift;
2216 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2217 top_border = h->top_borders[top_idx][h->mb_x];
2219 #define XCHG(a, b, xchg) \
2220 if (pixel_shift) { \
2222 AV_SWAP64(b + 0, a + 0); \
2223 AV_SWAP64(b + 8, a + 8); \
2233 if (deblock_topleft) {
2234 XCHG(top_border_m1 + (8 << pixel_shift),
2235 src_y - (7 << pixel_shift), 1);
2237 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2238 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2239 if (h->mb_x + 1 < h->mb_width) {
2240 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2241 src_y + (17 << pixel_shift), 1);
2244 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2246 if (deblock_topleft) {
2247 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2248 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2250 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2251 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2252 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2253 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2254 if (h->mb_x + 1 < h->mb_width) {
2255 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2256 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2260 if (deblock_topleft) {
2261 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2262 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2264 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2265 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2271 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2274 if (high_bit_depth) {
2275 return AV_RN32A(((int32_t *)mb) + index);
2277 return AV_RN16A(mb + index);
2280 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2281 int index, int value)
2283 if (high_bit_depth) {
2284 AV_WN32A(((int32_t *)mb) + index, value);
2286 AV_WN16A(mb + index, value);
2289 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2290 int mb_type, int is_h264,
2292 int transform_bypass,
2296 uint8_t *dest_y, int p)
2298 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2299 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2301 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2302 block_offset += 16 * p;
2303 if (IS_INTRA4x4(mb_type)) {
2304 if (IS_8x8DCT(mb_type)) {
2305 if (transform_bypass) {
2307 idct_add = h->h264dsp.h264_add_pixels8_clear;
2309 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2310 idct_add = h->h264dsp.h264_idct8_add;
2312 for (i = 0; i < 16; i += 4) {
2313 uint8_t *const ptr = dest_y + block_offset[i];
2314 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2315 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2316 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2318 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2319 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2320 (h->topright_samples_available << i) & 0x4000, linesize);
2322 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2323 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2325 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2330 if (transform_bypass) {
2332 idct_add = h->h264dsp.h264_add_pixels4_clear;
2334 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2335 idct_add = h->h264dsp.h264_idct_add;
2337 for (i = 0; i < 16; i++) {
2338 uint8_t *const ptr = dest_y + block_offset[i];
2339 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2341 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2342 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2347 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2348 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2349 av_assert2(h->mb_y || linesize <= block_offset[i]);
2350 if (!topright_avail) {
2352 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2353 topright = (uint8_t *)&tr_high;
2355 tr = ptr[3 - linesize] * 0x01010101u;
2356 topright = (uint8_t *)&tr;
2359 topright = ptr + (4 << pixel_shift) - linesize;
2363 h->hpc.pred4x4[dir](ptr, topright, linesize);
2364 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2367 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2368 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2370 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2371 } else if (CONFIG_SVQ3_DECODER)
2372 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2378 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2380 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2381 if (!transform_bypass)
2382 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2384 h->dequant4_coeff[p][qscale][0]);
2386 static const uint8_t dc_mapping[16] = {
2387 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2388 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2389 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2390 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
2391 for (i = 0; i < 16; i++)
2392 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2393 pixel_shift, dc_mapping[i],
2394 dctcoef_get(h->mb_luma_dc[p],
2398 } else if (CONFIG_SVQ3_DECODER)
2399 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2400 h->mb_luma_dc[p], qscale);
2404 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2405 int is_h264, int simple,
2406 int transform_bypass,
2410 uint8_t *dest_y, int p)
2412 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2414 block_offset += 16 * p;
2415 if (!IS_INTRA4x4(mb_type)) {
2417 if (IS_INTRA16x16(mb_type)) {
2418 if (transform_bypass) {
2419 if (h->sps.profile_idc == 244 &&
2420 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2421 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2422 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2423 h->mb + (p * 256 << pixel_shift),
2426 for (i = 0; i < 16; i++)
2427 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2428 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2429 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2430 h->mb + (i * 16 + p * 256 << pixel_shift),
2434 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2435 h->mb + (p * 256 << pixel_shift),
2437 h->non_zero_count_cache + p * 5 * 8);
2439 } else if (h->cbp & 15) {
2440 if (transform_bypass) {
2441 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2442 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2443 : h->h264dsp.h264_add_pixels4_clear;
2444 for (i = 0; i < 16; i += di)
2445 if (h->non_zero_count_cache[scan8[i + p * 16]])
2446 idct_add(dest_y + block_offset[i],
2447 h->mb + (i * 16 + p * 256 << pixel_shift),
2450 if (IS_8x8DCT(mb_type))
2451 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2452 h->mb + (p * 256 << pixel_shift),
2454 h->non_zero_count_cache + p * 5 * 8);
2456 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2457 h->mb + (p * 256 << pixel_shift),
2459 h->non_zero_count_cache + p * 5 * 8);
2462 } else if (CONFIG_SVQ3_DECODER) {
2463 for (i = 0; i < 16; i++)
2464 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2465 // FIXME benchmark weird rule, & below
2466 uint8_t *const ptr = dest_y + block_offset[i];
2467 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2468 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2476 #include "h264_mb_template.c"
2480 #include "h264_mb_template.c"
2484 #include "h264_mb_template.c"
2486 void ff_h264_hl_decode_mb(H264Context *h)
2488 const int mb_xy = h->mb_xy;
2489 const int mb_type = h->cur_pic.mb_type[mb_xy];
2490 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
2493 if (is_complex || h->pixel_shift)
2494 hl_decode_mb_444_complex(h);
2496 hl_decode_mb_444_simple_8(h);
2497 } else if (is_complex) {
2498 hl_decode_mb_complex(h);
2499 } else if (h->pixel_shift) {
2500 hl_decode_mb_simple_16(h);
2502 hl_decode_mb_simple_8(h);
2505 static int pred_weight_table(H264Context *h)
2508 int luma_def, chroma_def;
2511 h->use_weight_chroma = 0;
2512 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2513 if (h->sps.chroma_format_idc)
2514 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2515 luma_def = 1 << h->luma_log2_weight_denom;
2516 chroma_def = 1 << h->chroma_log2_weight_denom;
2518 for (list = 0; list < 2; list++) {
2519 h->luma_weight_flag[list] = 0;
2520 h->chroma_weight_flag[list] = 0;
2521 for (i = 0; i < h->ref_count[list]; i++) {
2522 int luma_weight_flag, chroma_weight_flag;
2524 luma_weight_flag = get_bits1(&h->gb);
2525 if (luma_weight_flag) {
2526 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2527 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2528 if (h->luma_weight[i][list][0] != luma_def ||
2529 h->luma_weight[i][list][1] != 0) {
2531 h->luma_weight_flag[list] = 1;
2534 h->luma_weight[i][list][0] = luma_def;
2535 h->luma_weight[i][list][1] = 0;
2538 if (h->sps.chroma_format_idc) {
2539 chroma_weight_flag = get_bits1(&h->gb);
2540 if (chroma_weight_flag) {
2542 for (j = 0; j < 2; j++) {
2543 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2544 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2545 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2546 h->chroma_weight[i][list][j][1] != 0) {
2547 h->use_weight_chroma = 1;
2548 h->chroma_weight_flag[list] = 1;
2553 for (j = 0; j < 2; j++) {
2554 h->chroma_weight[i][list][j][0] = chroma_def;
2555 h->chroma_weight[i][list][j][1] = 0;
2560 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2563 h->use_weight = h->use_weight || h->use_weight_chroma;
2568 * Initialize implicit_weight table.
2569 * @param field 0/1 initialize the weight for interlaced MBAFF
2570 * -1 initializes the rest
2572 static void implicit_weight_table(H264Context *h, int field)
2574 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2576 for (i = 0; i < 2; i++) {
2577 h->luma_weight_flag[i] = 0;
2578 h->chroma_weight_flag[i] = 0;
2582 if (h->picture_structure == PICT_FRAME) {
2583 cur_poc = h->cur_pic_ptr->poc;
2585 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2587 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2588 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2590 h->use_weight_chroma = 0;
2594 ref_count0 = h->ref_count[0];
2595 ref_count1 = h->ref_count[1];
2597 cur_poc = h->cur_pic_ptr->field_poc[field];
2599 ref_count0 = 16 + 2 * h->ref_count[0];
2600 ref_count1 = 16 + 2 * h->ref_count[1];
2604 h->use_weight_chroma = 2;
2605 h->luma_log2_weight_denom = 5;
2606 h->chroma_log2_weight_denom = 5;
2608 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2609 int poc0 = h->ref_list[0][ref0].poc;
2610 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2612 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2613 int poc1 = h->ref_list[1][ref1].poc;
2614 int td = av_clip(poc1 - poc0, -128, 127);
2616 int tb = av_clip(cur_poc - poc0, -128, 127);
2617 int tx = (16384 + (FFABS(td) >> 1)) / td;
2618 int dist_scale_factor = (tb * tx + 32) >> 8;
2619 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2620 w = 64 - dist_scale_factor;
2624 h->implicit_weight[ref0][ref1][0] =
2625 h->implicit_weight[ref0][ref1][1] = w;
2627 h->implicit_weight[ref0][ref1][field] = w;
2634 * instantaneous decoder refresh.
2636 static void idr(H264Context *h)
2639 ff_h264_remove_all_refs(h);
2640 h->prev_frame_num = 0;
2641 h->prev_frame_num_offset = 0;
2642 h->prev_poc_msb = 1<<16;
2643 h->prev_poc_lsb = 0;
2644 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2645 h->last_pocs[i] = INT_MIN;
2648 /* forget old pics after a seek */
2649 static void flush_change(H264Context *h)
2653 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2654 h->prev_interlaced_frame = 1;
2657 h->prev_frame_num = -1;
2658 if (h->cur_pic_ptr) {
2659 h->cur_pic_ptr->reference = 0;
2660 for (j=i=0; h->delayed_pic[i]; i++)
2661 if (h->delayed_pic[i] != h->cur_pic_ptr)
2662 h->delayed_pic[j++] = h->delayed_pic[i];
2663 h->delayed_pic[j] = NULL;
2666 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2667 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2668 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2669 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2670 ff_h264_reset_sei(h);
2671 h->recovery_frame= -1;
2674 h->current_slice = 0;
2677 /* forget old pics after a seek */
2678 static void flush_dpb(AVCodecContext *avctx)
2680 H264Context *h = avctx->priv_data;
2683 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2684 if (h->delayed_pic[i])
2685 h->delayed_pic[i]->reference = 0;
2686 h->delayed_pic[i] = NULL;
2691 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2692 unref_picture(h, &h->DPB[i]);
2693 h->cur_pic_ptr = NULL;
2694 unref_picture(h, &h->cur_pic);
2696 h->mb_x = h->mb_y = 0;
2698 h->parse_context.state = -1;
2699 h->parse_context.frame_start_found = 0;
2700 h->parse_context.overread = 0;
2701 h->parse_context.overread_index = 0;
2702 h->parse_context.index = 0;
2703 h->parse_context.last_index = 0;
2706 static int init_poc(H264Context *h)
2708 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2710 Picture *cur = h->cur_pic_ptr;
2712 h->frame_num_offset = h->prev_frame_num_offset;
2713 if (h->frame_num < h->prev_frame_num)
2714 h->frame_num_offset += max_frame_num;
2716 if (h->sps.poc_type == 0) {
2717 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2719 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2720 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2721 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2722 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2724 h->poc_msb = h->prev_poc_msb;
2726 field_poc[1] = h->poc_msb + h->poc_lsb;
2727 if (h->picture_structure == PICT_FRAME)
2728 field_poc[1] += h->delta_poc_bottom;
2729 } else if (h->sps.poc_type == 1) {
2730 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2733 if (h->sps.poc_cycle_length != 0)
2734 abs_frame_num = h->frame_num_offset + h->frame_num;
2738 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2741 expected_delta_per_poc_cycle = 0;
2742 for (i = 0; i < h->sps.poc_cycle_length; i++)
2743 // FIXME integrate during sps parse
2744 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2746 if (abs_frame_num > 0) {
2747 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2748 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2750 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2751 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2752 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2756 if (h->nal_ref_idc == 0)
2757 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2759 field_poc[0] = expectedpoc + h->delta_poc[0];
2760 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2762 if (h->picture_structure == PICT_FRAME)
2763 field_poc[1] += h->delta_poc[1];
2765 int poc = 2 * (h->frame_num_offset + h->frame_num);
2767 if (!h->nal_ref_idc)
2774 if (h->picture_structure != PICT_BOTTOM_FIELD)
2775 h->cur_pic_ptr->field_poc[0] = field_poc[0];
2776 if (h->picture_structure != PICT_TOP_FIELD)
2777 h->cur_pic_ptr->field_poc[1] = field_poc[1];
2778 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2784 * initialize scan tables
2786 static void init_scan_tables(H264Context *h)
2789 for (i = 0; i < 16; i++) {
2790 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2791 h->zigzag_scan[i] = T(zigzag_scan[i]);
2792 h->field_scan[i] = T(field_scan[i]);
2795 for (i = 0; i < 64; i++) {
2796 #define T(x) (x >> 3) | ((x & 7) << 3)
2797 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2798 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2799 h->field_scan8x8[i] = T(field_scan8x8[i]);
2800 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2803 if (h->sps.transform_bypass) { // FIXME same ugly
2804 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2805 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2806 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2807 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2808 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2809 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2811 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2812 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2813 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2814 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2815 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2816 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2820 static int field_end(H264Context *h, int in_setup)
2822 AVCodecContext *const avctx = h->avctx;
2826 if (!in_setup && !h->droppable)
2827 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2828 h->picture_structure == PICT_BOTTOM_FIELD);
2830 if (CONFIG_H264_VDPAU_DECODER &&
2831 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2832 ff_vdpau_h264_set_reference_frames(h);
2834 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2835 if (!h->droppable) {
2836 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2837 h->prev_poc_msb = h->poc_msb;
2838 h->prev_poc_lsb = h->poc_lsb;
2840 h->prev_frame_num_offset = h->frame_num_offset;
2841 h->prev_frame_num = h->frame_num;
2842 h->outputed_poc = h->next_outputed_poc;
2845 if (avctx->hwaccel) {
2846 if (avctx->hwaccel->end_frame(avctx) < 0)
2847 av_log(avctx, AV_LOG_ERROR,
2848 "hardware accelerator failed to decode picture\n");
2851 if (CONFIG_H264_VDPAU_DECODER &&
2852 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2853 ff_vdpau_h264_picture_complete(h);
2856 * FIXME: Error handling code does not seem to support interlaced
2857 * when slices span multiple rows
2858 * The ff_er_add_slice calls don't work right for bottom
2859 * fields; they cause massive erroneous error concealing
2860 * Error marking covers both fields (top and bottom).
2861 * This causes a mismatched s->error_count
2862 * and a bad error table. Further, the error count goes to
2863 * INT_MAX when called for bottom field, because mb_y is
2864 * past end by one (callers fault) and resync_mb_y != 0
2865 * causes problems for the first MB line, too.
2867 if (CONFIG_ERROR_RESILIENCE &&
2868 !FIELD_PICTURE && h->current_slice && !h->sps.new) {
2869 h->er.cur_pic = h->cur_pic_ptr;
2870 ff_er_frame_end(&h->er);
2874 h->current_slice = 0;
2880 * Replicate H264 "master" context to thread contexts.
2882 static int clone_slice(H264Context *dst, H264Context *src)
2884 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2885 dst->cur_pic_ptr = src->cur_pic_ptr;
2886 dst->cur_pic = src->cur_pic;
2887 dst->linesize = src->linesize;
2888 dst->uvlinesize = src->uvlinesize;
2889 dst->first_field = src->first_field;
2891 dst->prev_poc_msb = src->prev_poc_msb;
2892 dst->prev_poc_lsb = src->prev_poc_lsb;
2893 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2894 dst->prev_frame_num = src->prev_frame_num;
2895 dst->short_ref_count = src->short_ref_count;
2897 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2898 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2899 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2901 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2902 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2908 * Compute profile from profile_idc and constraint_set?_flags.
2912 * @return profile as defined by FF_PROFILE_H264_*
2914 int ff_h264_get_profile(SPS *sps)
2916 int profile = sps->profile_idc;
2918 switch (sps->profile_idc) {
2919 case FF_PROFILE_H264_BASELINE:
2920 // constraint_set1_flag set to 1
2921 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2923 case FF_PROFILE_H264_HIGH_10:
2924 case FF_PROFILE_H264_HIGH_422:
2925 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2926 // constraint_set3_flag set to 1
2927 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2934 static int h264_set_parameter_from_sps(H264Context *h)
2936 if (h->flags & CODEC_FLAG_LOW_DELAY ||
2937 (h->sps.bitstream_restriction_flag &&
2938 !h->sps.num_reorder_frames)) {
2939 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2940 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
2941 "Reenabling low delay requires a codec flush.\n");
2946 if (h->avctx->has_b_frames < 2)
2947 h->avctx->has_b_frames = !h->low_delay;
2949 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
2950 av_log_missing_feature(h->avctx,
2951 "Different bit depth between chroma and luma", 1);
2952 return AVERROR_PATCHWELCOME;
2955 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2956 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2957 if (h->avctx->codec &&
2958 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2959 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2960 av_log(h->avctx, AV_LOG_ERROR,
2961 "VDPAU decoding does not support video colorspace.\n");
2962 return AVERROR_INVALIDDATA;
2964 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
2965 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
2966 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2967 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2968 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2969 h->pixel_shift = h->sps.bit_depth_luma > 8;
2971 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2972 h->sps.chroma_format_idc);
2973 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2974 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2975 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
2976 h->sps.chroma_format_idc);
2977 if (CONFIG_ERROR_RESILIENCE) {
2978 h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2979 ff_dsputil_init(&h->dsp, h->avctx);
2981 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
2983 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2984 h->sps.bit_depth_luma);
2985 return AVERROR_INVALIDDATA;
2991 static enum PixelFormat get_pixel_format(H264Context *h, int force_callback)
2993 switch (h->sps.bit_depth_luma) {
2996 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2997 return AV_PIX_FMT_GBRP9;
2999 return AV_PIX_FMT_YUV444P9;
3000 } else if (CHROMA422)
3001 return AV_PIX_FMT_YUV422P9;
3003 return AV_PIX_FMT_YUV420P9;
3007 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3008 return AV_PIX_FMT_GBRP10;
3010 return AV_PIX_FMT_YUV444P10;
3011 } else if (CHROMA422)
3012 return AV_PIX_FMT_YUV422P10;
3014 return AV_PIX_FMT_YUV420P10;
3018 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3019 return AV_PIX_FMT_GBRP12;
3021 return AV_PIX_FMT_YUV444P12;
3022 } else if (CHROMA422)
3023 return AV_PIX_FMT_YUV422P12;
3025 return AV_PIX_FMT_YUV420P12;
3029 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3030 return AV_PIX_FMT_GBRP14;
3032 return AV_PIX_FMT_YUV444P14;
3033 } else if (CHROMA422)
3034 return AV_PIX_FMT_YUV422P14;
3036 return AV_PIX_FMT_YUV420P14;
3040 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3041 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
3042 return AV_PIX_FMT_GBR24P;
3043 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
3044 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
3046 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3047 : AV_PIX_FMT_YUV444P;
3048 } else if (CHROMA422) {
3049 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3050 : AV_PIX_FMT_YUV422P;
3053 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
3054 h->avctx->codec->pix_fmts :
3055 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3056 h264_hwaccel_pixfmt_list_jpeg_420 :
3057 h264_hwaccel_pixfmt_list_420;
3059 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
3060 if (fmt[i] == h->avctx->pix_fmt && !force_callback)
3062 return h->avctx->get_format(h->avctx, fmt);
3066 av_log(h->avctx, AV_LOG_ERROR,
3067 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3068 return AVERROR_INVALIDDATA;
3072 static int h264_slice_header_init(H264Context *h, int reinit)
3074 int nb_slices = (HAVE_THREADS &&
3075 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3076 h->avctx->thread_count : 1;
3079 if( FFALIGN(h->avctx->width , 16 ) == h->width
3080 && FFALIGN(h->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == h->height
3081 && !h->sps.crop_right && !h->sps.crop_bottom
3082 && (h->avctx->width != h->width || h->avctx->height && h->height)
3084 av_log(h->avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
3085 h->avctx->coded_width = h->width;
3086 h->avctx->coded_height = h->height;
3088 avcodec_set_dimensions(h->avctx, h->width, h->height);
3089 h->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
3090 h->avctx->height -= (1<<h->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>h->chroma_y_shift)-1) * (2 - h->sps.frame_mbs_only_flag);
3093 h->avctx->sample_aspect_ratio = h->sps.sar;
3094 av_assert0(h->avctx->sample_aspect_ratio.den);
3095 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3096 &h->chroma_x_shift, &h->chroma_y_shift);
3098 if (h->sps.timing_info_present_flag) {
3099 int64_t den = h->sps.time_scale;
3100 if (h->x264_build < 44U)
3102 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3103 h->sps.num_units_in_tick, den, 1 << 30);
3106 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
3111 h->prev_interlaced_frame = 1;
3113 init_scan_tables(h);
3114 if (ff_h264_alloc_tables(h) < 0) {
3115 av_log(h->avctx, AV_LOG_ERROR,
3116 "Could not allocate memory for h264\n");
3117 return AVERROR(ENOMEM);
3120 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3123 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3125 max_slices = MAX_THREADS;
3126 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3127 " reducing to %d\n", nb_slices, max_slices);
3128 nb_slices = max_slices;
3130 h->slice_context_count = nb_slices;
3132 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3133 if (context_init(h) < 0) {
3134 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3138 for (i = 1; i < h->slice_context_count; i++) {
3140 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3141 c->avctx = h->avctx;
3142 if (CONFIG_ERROR_RESILIENCE) {
3146 c->h264dsp = h->h264dsp;
3147 c->h264qpel = h->h264qpel;
3148 c->h264chroma = h->h264chroma;
3151 c->pixel_shift = h->pixel_shift;
3152 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3153 c->width = h->width;
3154 c->height = h->height;
3155 c->linesize = h->linesize;
3156 c->uvlinesize = h->uvlinesize;
3157 c->chroma_x_shift = h->chroma_x_shift;
3158 c->chroma_y_shift = h->chroma_y_shift;
3159 c->qscale = h->qscale;
3160 c->droppable = h->droppable;
3161 c->data_partitioning = h->data_partitioning;
3162 c->low_delay = h->low_delay;
3163 c->mb_width = h->mb_width;
3164 c->mb_height = h->mb_height;
3165 c->mb_stride = h->mb_stride;
3166 c->mb_num = h->mb_num;
3167 c->flags = h->flags;
3168 c->workaround_bugs = h->workaround_bugs;
3169 c->pict_type = h->pict_type;
3171 init_scan_tables(c);
3172 clone_tables(c, h, i);
3173 c->context_initialized = 1;
3176 for (i = 0; i < h->slice_context_count; i++)
3177 if (context_init(h->thread_context[i]) < 0) {
3178 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3183 h->context_initialized = 1;
3189 * Decode a slice header.
3190 * This will also call ff_MPV_common_init() and frame_start() as needed.
3192 * @param h h264context
3193 * @param h0 h264 master context (differs from 'h' when doing sliced based
3194 * parallel decoding)
3196 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3198 static int decode_slice_header(H264Context *h, H264Context *h0)
3200 unsigned int first_mb_in_slice;
3201 unsigned int pps_id;
3202 int num_ref_idx_active_override_flag, ret;
3203 unsigned int slice_type, tmp, i, j;
3204 int default_ref_list_done = 0;
3205 int last_pic_structure, last_pic_droppable;
3207 int needs_reinit = 0;
3209 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3210 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3212 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3214 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3215 if (h0->current_slice && FIELD_PICTURE) {
3219 h0->current_slice = 0;
3220 if (!h0->first_field) {
3221 if (h->cur_pic_ptr && !h->droppable) {
3222 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3223 h->picture_structure == PICT_BOTTOM_FIELD);
3225 h->cur_pic_ptr = NULL;
3229 slice_type = get_ue_golomb_31(&h->gb);
3230 if (slice_type > 9) {
3231 av_log(h->avctx, AV_LOG_ERROR,
3232 "slice type too large (%d) at %d %d\n",
3233 slice_type, h->mb_x, h->mb_y);
3236 if (slice_type > 4) {
3238 h->slice_type_fixed = 1;
3240 h->slice_type_fixed = 0;
3242 slice_type = golomb_to_pict_type[slice_type];
3243 if (slice_type == AV_PICTURE_TYPE_I ||
3244 (h0->current_slice != 0 &&
3245 slice_type == h0->last_slice_type &&
3246 !memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3247 default_ref_list_done = 1;
3249 h->slice_type = slice_type;
3250 h->slice_type_nos = slice_type & 3;
3252 // to make a few old functions happy, it's wrong though
3253 h->pict_type = h->slice_type;
3255 pps_id = get_ue_golomb(&h->gb);
3256 if (pps_id >= MAX_PPS_COUNT) {
3257 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3260 if (!h0->pps_buffers[pps_id]) {
3261 av_log(h->avctx, AV_LOG_ERROR,
3262 "non-existing PPS %u referenced\n",
3266 h->pps = *h0->pps_buffers[pps_id];
3268 if (!h0->sps_buffers[h->pps.sps_id]) {
3269 av_log(h->avctx, AV_LOG_ERROR,
3270 "non-existing SPS %u referenced\n",
3275 if (h->pps.sps_id != h->current_sps_id ||
3276 h0->sps_buffers[h->pps.sps_id]->new) {
3277 h0->sps_buffers[h->pps.sps_id]->new = 0;
3279 h->current_sps_id = h->pps.sps_id;
3280 h->sps = *h0->sps_buffers[h->pps.sps_id];
3282 if (h->mb_width != h->sps.mb_width ||
3283 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3284 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3285 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3289 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3290 h->chroma_format_idc != h->sps.chroma_format_idc) {
3291 h->bit_depth_luma = h->sps.bit_depth_luma;
3292 h->chroma_format_idc = h->sps.chroma_format_idc;
3295 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3299 h->avctx->profile = ff_h264_get_profile(&h->sps);
3300 h->avctx->level = h->sps.level_idc;
3301 h->avctx->refs = h->sps.ref_frame_count;
3303 must_reinit = (h->context_initialized &&
3304 ( 16*h->sps.mb_width != h->avctx->coded_width
3305 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3306 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3307 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3308 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)));
3309 if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3312 h->mb_width = h->sps.mb_width;
3313 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3314 h->mb_num = h->mb_width * h->mb_height;
3315 h->mb_stride = h->mb_width + 1;
3317 h->b_stride = h->mb_width * 4;
3319 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3321 h->width = 16 * h->mb_width;
3322 h->height = 16 * h->mb_height;
3324 if (h->sps.video_signal_type_present_flag) {
3325 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3327 if (h->sps.colour_description_present_flag) {
3328 if (h->avctx->colorspace != h->sps.colorspace)
3330 h->avctx->color_primaries = h->sps.color_primaries;
3331 h->avctx->color_trc = h->sps.color_trc;
3332 h->avctx->colorspace = h->sps.colorspace;
3336 if (h->context_initialized &&
3342 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3343 "slice %d\n", h0->current_slice + 1);
3344 return AVERROR_INVALIDDATA;
3349 if ((ret = get_pixel_format(h, 1)) < 0)
3351 h->avctx->pix_fmt = ret;
3353 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3354 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3356 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3357 av_log(h->avctx, AV_LOG_ERROR,
3358 "h264_slice_header_init() failed\n");
3362 if (!h->context_initialized) {
3364 av_log(h->avctx, AV_LOG_ERROR,
3365 "Cannot (re-)initialize context during parallel decoding.\n");
3369 if ((ret = get_pixel_format(h, 1)) < 0)
3371 h->avctx->pix_fmt = ret;
3373 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3374 av_log(h->avctx, AV_LOG_ERROR,
3375 "h264_slice_header_init() failed\n");
3380 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3381 h->dequant_coeff_pps = pps_id;
3382 init_dequant_tables(h);
3385 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3388 h->mb_aff_frame = 0;
3389 last_pic_structure = h0->picture_structure;
3390 last_pic_droppable = h0->droppable;
3391 h->droppable = h->nal_ref_idc == 0;
3392 if (h->sps.frame_mbs_only_flag) {
3393 h->picture_structure = PICT_FRAME;
3395 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3396 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3399 if (get_bits1(&h->gb)) { // field_pic_flag
3400 h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
3402 h->picture_structure = PICT_FRAME;
3403 h->mb_aff_frame = h->sps.mb_aff;
3406 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3408 if (h0->current_slice != 0) {
3409 if (last_pic_structure != h->picture_structure ||
3410 last_pic_droppable != h->droppable) {
3411 av_log(h->avctx, AV_LOG_ERROR,
3412 "Changing field mode (%d -> %d) between slices is not allowed\n",
3413 last_pic_structure, h->picture_structure);
3414 h->picture_structure = last_pic_structure;
3415 h->droppable = last_pic_droppable;
3416 return AVERROR_INVALIDDATA;
3417 } else if (!h0->cur_pic_ptr) {
3418 av_log(h->avctx, AV_LOG_ERROR,
3419 "unset cur_pic_ptr on %d. slice\n",
3420 h0->current_slice + 1);
3421 return AVERROR_INVALIDDATA;
3424 /* Shorten frame num gaps so we don't have to allocate reference
3425 * frames just to throw them away */
3426 if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
3427 int unwrap_prev_frame_num = h->prev_frame_num;
3428 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3430 if (unwrap_prev_frame_num > h->frame_num)
3431 unwrap_prev_frame_num -= max_frame_num;
3433 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3434 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3435 if (unwrap_prev_frame_num < 0)
3436 unwrap_prev_frame_num += max_frame_num;
3438 h->prev_frame_num = unwrap_prev_frame_num;
3442 /* See if we have a decoded first field looking for a pair...
3443 * Here, we're using that to see if we should mark previously
3444 * decode frames as "finished".
3445 * We have to do that before the "dummy" in-between frame allocation,