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"
37 #include "mpegvideo.h"
40 #include "h264chroma.h"
41 #include "h264_mvpred.h"
44 #include "rectangle.h"
47 #include "vdpau_internal.h"
48 #include "libavutil/avassert.h"
53 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
55 static const uint8_t rem6[QP_MAX_NUM + 1] = {
56 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
57 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
58 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
59 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
63 static const uint8_t div6[QP_MAX_NUM + 1] = {
64 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
65 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
66 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
67 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
71 static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
72 #if CONFIG_H264_DXVA2_HWACCEL
75 #if CONFIG_H264_VAAPI_HWACCEL
78 #if CONFIG_H264_VDA_HWACCEL
81 #if CONFIG_H264_VDPAU_HWACCEL
88 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
90 H264Context *h = avctx->priv_data;
91 return h ? h->sps.num_reorder_frames : 0;
94 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
96 int mb_x, int mb_y, int mb_intra, int mb_skipped)
98 H264Context *h = opaque;
102 h->mb_xy = mb_x + mb_y * h->mb_stride;
103 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
104 av_assert1(ref >= 0);
105 /* FIXME: It is possible albeit uncommon that slice references
106 * differ between slices. We take the easy approach and ignore
107 * it for now. If this turns out to have any relevance in
108 * practice then correct remapping should be added. */
109 if (ref >= h->ref_count[0])
111 if (!h->ref_list[0][ref].f.data[0]) {
112 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
115 if ((h->ref_list[0][ref].f.reference&3) != 3) {
116 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
119 fill_rectangle(&h->cur_pic.f.ref_index[0][4 * h->mb_xy],
121 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
122 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
123 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
125 h->mb_field_decoding_flag = 0;
126 ff_h264_hl_decode_mb(h);
129 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
131 ff_draw_horiz_band(h->avctx, NULL, &h->cur_pic,
132 h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL,
133 y, height, h->picture_structure, h->first_field, 0,
134 h->low_delay, h->mb_height * 16, h->mb_width * 16);
137 static void free_frame_buffer(H264Context *h, Picture *pic)
139 pic->period_since_free = 0;
140 ff_thread_release_buffer(h->avctx, &pic->f);
141 av_freep(&pic->f.hwaccel_picture_private);
144 static void free_picture(H264Context *h, Picture *pic)
149 free_frame_buffer(h, pic);
151 av_freep(&pic->qscale_table_base);
152 pic->f.qscale_table = NULL;
153 av_freep(&pic->mb_type_base);
154 pic->f.mb_type = NULL;
155 for (i = 0; i < 2; i++) {
156 av_freep(&pic->motion_val_base[i]);
157 av_freep(&pic->f.ref_index[i]);
158 pic->f.motion_val[i] = NULL;
162 static void release_unused_pictures(H264Context *h, int remove_current)
166 /* release non reference frames */
167 for (i = 0; i < h->picture_count; i++) {
168 if (h->DPB[i].f.data[0] && !h->DPB[i].f.reference &&
169 (!h->DPB[i].owner2 || h->DPB[i].owner2 == h) &&
170 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
171 free_frame_buffer(h, &h->DPB[i]);
176 static int alloc_scratch_buffers(H264Context *h, int linesize)
178 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
180 if (h->bipred_scratchpad)
183 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
184 // edge emu needs blocksize + filter length - 1
185 // (= 21x21 for h264)
186 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
187 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
189 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
190 av_freep(&h->bipred_scratchpad);
191 av_freep(&h->edge_emu_buffer);
192 av_freep(&h->me.scratchpad);
193 return AVERROR(ENOMEM);
196 h->me.temp = h->me.scratchpad;
201 static int alloc_picture(H264Context *h, Picture *pic)
203 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
204 const int mb_array_size = h->mb_stride * h->mb_height;
205 const int b4_stride = h->mb_width * 4 + 1;
206 const int b4_array_size = b4_stride * h->mb_height * 4;
209 av_assert0(!pic->f.data[0]);
211 if (h->avctx->hwaccel) {
212 const AVHWAccel *hwaccel = h->avctx->hwaccel;
213 av_assert0(!pic->f.hwaccel_picture_private);
214 if (hwaccel->priv_data_size) {
215 pic->f.hwaccel_picture_private = av_mallocz(hwaccel->priv_data_size);
216 if (!pic->f.hwaccel_picture_private)
217 return AVERROR(ENOMEM);
220 ret = ff_thread_get_buffer(h->avctx, &pic->f);
224 h->linesize = pic->f.linesize[0];
225 h->uvlinesize = pic->f.linesize[1];
227 if (pic->f.qscale_table == NULL) {
228 FF_ALLOCZ_OR_GOTO(h->avctx, pic->qscale_table_base,
229 (big_mb_num + h->mb_stride) * sizeof(uint8_t),
231 FF_ALLOCZ_OR_GOTO(h->avctx, pic->mb_type_base,
232 (big_mb_num + h->mb_stride) * sizeof(uint32_t),
234 pic->f.mb_type = pic->mb_type_base + 2 * h->mb_stride + 1;
235 pic->f.qscale_table = pic->qscale_table_base + 2 * h->mb_stride + 1;
237 for (i = 0; i < 2; i++) {
238 FF_ALLOCZ_OR_GOTO(h->avctx, pic->motion_val_base[i],
239 2 * (b4_array_size + 4) * sizeof(int16_t),
241 pic->f.motion_val[i] = pic->motion_val_base[i] + 4;
242 FF_ALLOCZ_OR_GOTO(h->avctx, pic->f.ref_index[i],
243 4 * mb_array_size * sizeof(uint8_t), fail)
245 pic->f.motion_subsample_log2 = 2;
247 pic->f.qstride = h->mb_stride;
254 free_frame_buffer(h, pic);
255 return (ret < 0) ? ret : AVERROR(ENOMEM);
258 static inline int pic_is_unused(H264Context *h, Picture *pic)
260 if ( (h->avctx->active_thread_type & FF_THREAD_FRAME)
261 && pic->f.qscale_table //check if the frame has anything allocated
262 && pic->period_since_free < h->avctx->thread_count)
264 if (pic->f.data[0] == NULL)
266 if (pic->needs_realloc && !(pic->f.reference & DELAYED_PIC_REF))
267 if (!pic->owner2 || pic->owner2 == h)
272 static int find_unused_picture(H264Context *h)
276 for (i = h->picture_range_start; i < h->picture_range_end; i++) {
277 if (pic_is_unused(h, &h->DPB[i]))
280 if (i == h->picture_range_end)
281 return AVERROR_INVALIDDATA;
283 if (h->DPB[i].needs_realloc) {
284 h->DPB[i].needs_realloc = 0;
285 free_picture(h, &h->DPB[i]);
286 avcodec_get_frame_defaults(&h->DPB[i].f);
293 * Check if the top & left blocks are available if needed and
294 * change the dc mode so it only uses the available blocks.
296 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
298 static const int8_t top[12] = {
299 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
301 static const int8_t left[12] = {
302 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
306 if (!(h->top_samples_available & 0x8000)) {
307 for (i = 0; i < 4; i++) {
308 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
310 av_log(h->avctx, AV_LOG_ERROR,
311 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
312 status, h->mb_x, h->mb_y);
315 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
320 if ((h->left_samples_available & 0x8888) != 0x8888) {
321 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
322 for (i = 0; i < 4; i++)
323 if (!(h->left_samples_available & mask[i])) {
324 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
326 av_log(h->avctx, AV_LOG_ERROR,
327 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
328 status, h->mb_x, h->mb_y);
331 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
337 } // FIXME cleanup like ff_h264_check_intra_pred_mode
340 * Check if the top & left blocks are available if needed and
341 * change the dc mode so it only uses the available blocks.
343 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
345 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
346 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
349 av_log(h->avctx, AV_LOG_ERROR,
350 "out of range intra chroma pred mode at %d %d\n",
355 if (!(h->top_samples_available & 0x8000)) {
358 av_log(h->avctx, AV_LOG_ERROR,
359 "top block unavailable for requested intra mode at %d %d\n",
365 if ((h->left_samples_available & 0x8080) != 0x8080) {
367 if (is_chroma && (h->left_samples_available & 0x8080)) {
368 // mad cow disease mode, aka MBAFF + constrained_intra_pred
369 mode = ALZHEIMER_DC_L0T_PRED8x8 +
370 (!(h->left_samples_available & 0x8000)) +
371 2 * (mode == DC_128_PRED8x8);
374 av_log(h->avctx, AV_LOG_ERROR,
375 "left block unavailable for requested intra mode at %d %d\n",
384 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
385 int *dst_length, int *consumed, int length)
391 // src[0]&0x80; // forbidden bit
392 h->nal_ref_idc = src[0] >> 5;
393 h->nal_unit_type = src[0] & 0x1F;
398 #define STARTCODE_TEST \
399 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
400 if (src[i + 2] != 3) { \
401 /* startcode, so we must be past the end */ \
406 #if HAVE_FAST_UNALIGNED
407 #define FIND_FIRST_ZERO \
408 if (i > 0 && !src[i]) \
413 for (i = 0; i + 1 < length; i += 9) {
414 if (!((~AV_RN64A(src + i) &
415 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
416 0x8000800080008080ULL))
423 for (i = 0; i + 1 < length; i += 5) {
424 if (!((~AV_RN32A(src + i) &
425 (AV_RN32A(src + i) - 0x01000101U)) &
434 for (i = 0; i + 1 < length; i += 2) {
437 if (i > 0 && src[i - 1] == 0)
443 // use second escape buffer for inter data
444 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
446 si = h->rbsp_buffer_size[bufidx];
447 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
448 dst = h->rbsp_buffer[bufidx];
453 if(i>=length-1){ //no escaped 0
455 *consumed= length+1; //+1 for the header
456 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
459 memcpy(dst, src, length);
466 while (si + 2 < length) {
467 // remove escapes (very rare 1:2^22)
468 if (src[si + 2] > 3) {
469 dst[di++] = src[si++];
470 dst[di++] = src[si++];
471 } else if (src[si] == 0 && src[si + 1] == 0) {
472 if (src[si + 2] == 3) { // escape
477 } else // next start code
481 dst[di++] = src[si++];
484 dst[di++] = src[si++];
487 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
490 *consumed = si + 1; // +1 for the header
491 /* FIXME store exact number of bits in the getbitcontext
492 * (it is needed for decoding) */
497 * Identify the exact end of the bitstream
498 * @return the length of the trailing, or 0 if damaged
500 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
505 tprintf(h->avctx, "rbsp trailing %X\n", v);
507 for (r = 1; r < 9; r++) {
515 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
516 int height, int y_offset, int list)
518 int raw_my = h->mv_cache[list][scan8[n]][1];
519 int filter_height_down = (raw_my & 3) ? 3 : 0;
520 int full_my = (raw_my >> 2) + y_offset;
521 int bottom = full_my + filter_height_down + height;
523 av_assert2(height >= 0);
525 return FFMAX(0, bottom);
528 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
529 int height, int y_offset, int list0,
530 int list1, int *nrefs)
534 y_offset += 16 * (h->mb_y >> MB_FIELD);
537 int ref_n = h->ref_cache[0][scan8[n]];
538 Picture *ref = &h->ref_list[0][ref_n];
540 // Error resilience puts the current picture in the ref list.
541 // Don't try to wait on these as it will cause a deadlock.
542 // Fields can wait on each other, though.
543 if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
544 (ref->f.reference & 3) != h->picture_structure) {
545 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
546 if (refs[0][ref_n] < 0)
548 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
553 int ref_n = h->ref_cache[1][scan8[n]];
554 Picture *ref = &h->ref_list[1][ref_n];
556 if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
557 (ref->f.reference & 3) != h->picture_structure) {
558 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
559 if (refs[1][ref_n] < 0)
561 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
567 * Wait until all reference frames are available for MC operations.
569 * @param h the H264 context
571 static void await_references(H264Context *h)
573 const int mb_xy = h->mb_xy;
574 const int mb_type = h->cur_pic.f.mb_type[mb_xy];
576 int nrefs[2] = { 0 };
579 memset(refs, -1, sizeof(refs));
581 if (IS_16X16(mb_type)) {
582 get_lowest_part_y(h, refs, 0, 16, 0,
583 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
584 } else if (IS_16X8(mb_type)) {
585 get_lowest_part_y(h, refs, 0, 8, 0,
586 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
587 get_lowest_part_y(h, refs, 8, 8, 8,
588 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
589 } else if (IS_8X16(mb_type)) {
590 get_lowest_part_y(h, refs, 0, 16, 0,
591 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
592 get_lowest_part_y(h, refs, 4, 16, 0,
593 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
597 av_assert2(IS_8X8(mb_type));
599 for (i = 0; i < 4; i++) {
600 const int sub_mb_type = h->sub_mb_type[i];
602 int y_offset = (i & 2) << 2;
604 if (IS_SUB_8X8(sub_mb_type)) {
605 get_lowest_part_y(h, refs, n, 8, y_offset,
606 IS_DIR(sub_mb_type, 0, 0),
607 IS_DIR(sub_mb_type, 0, 1),
609 } else if (IS_SUB_8X4(sub_mb_type)) {
610 get_lowest_part_y(h, refs, n, 4, y_offset,
611 IS_DIR(sub_mb_type, 0, 0),
612 IS_DIR(sub_mb_type, 0, 1),
614 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
615 IS_DIR(sub_mb_type, 0, 0),
616 IS_DIR(sub_mb_type, 0, 1),
618 } else if (IS_SUB_4X8(sub_mb_type)) {
619 get_lowest_part_y(h, refs, n, 8, y_offset,
620 IS_DIR(sub_mb_type, 0, 0),
621 IS_DIR(sub_mb_type, 0, 1),
623 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
624 IS_DIR(sub_mb_type, 0, 0),
625 IS_DIR(sub_mb_type, 0, 1),
629 av_assert2(IS_SUB_4X4(sub_mb_type));
630 for (j = 0; j < 4; j++) {
631 int sub_y_offset = y_offset + 2 * (j & 2);
632 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
633 IS_DIR(sub_mb_type, 0, 0),
634 IS_DIR(sub_mb_type, 0, 1),
641 for (list = h->list_count - 1; list >= 0; list--)
642 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
643 int row = refs[list][ref];
645 Picture *ref_pic = &h->ref_list[list][ref];
646 int ref_field = ref_pic->f.reference - 1;
647 int ref_field_picture = ref_pic->field_picture;
648 int pic_height = 16 * h->mb_height >> ref_field_picture;
653 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
654 ff_thread_await_progress(&ref_pic->f,
655 FFMIN((row >> 1) - !(row & 1),
658 ff_thread_await_progress(&ref_pic->f,
659 FFMIN((row >> 1), pic_height - 1),
661 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
662 ff_thread_await_progress(&ref_pic->f,
663 FFMIN(row * 2 + ref_field,
666 } else if (FIELD_PICTURE) {
667 ff_thread_await_progress(&ref_pic->f,
668 FFMIN(row, pic_height - 1),
671 ff_thread_await_progress(&ref_pic->f,
672 FFMIN(row, pic_height - 1),
679 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
680 int n, int square, int height,
682 uint8_t *dest_y, uint8_t *dest_cb,
684 int src_x_offset, int src_y_offset,
685 qpel_mc_func *qpix_op,
686 h264_chroma_mc_func chroma_op,
687 int pixel_shift, int chroma_idc)
689 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
690 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
691 const int luma_xy = (mx & 3) + ((my & 3) << 2);
692 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
693 uint8_t *src_y = pic->f.data[0] + offset;
694 uint8_t *src_cb, *src_cr;
696 int extra_height = 0;
698 const int full_mx = mx >> 2;
699 const int full_my = my >> 2;
700 const int pic_width = 16 * h->mb_width;
701 const int pic_height = 16 * h->mb_height >> MB_FIELD;
709 if (full_mx < 0 - extra_width ||
710 full_my < 0 - extra_height ||
711 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
712 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
713 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
714 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
716 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
717 full_my - 2, pic_width, pic_height);
718 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
722 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
724 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
726 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
729 if (chroma_idc == 3 /* yuv444 */) {
730 src_cb = pic->f.data[1] + offset;
732 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
733 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
735 16 + 5, 16 + 5 /*FIXME*/,
736 full_mx - 2, full_my - 2,
737 pic_width, pic_height);
738 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
740 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
742 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
744 src_cr = pic->f.data[2] + offset;
746 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
747 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
749 16 + 5, 16 + 5 /*FIXME*/,
750 full_mx - 2, full_my - 2,
751 pic_width, pic_height);
752 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
754 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
756 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
760 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
761 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
762 // chroma offset when predicting from a field of opposite parity
763 my += 2 * ((h->mb_y & 1) - (pic->f.reference - 1));
764 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
767 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
768 (my >> ysh) * h->mb_uvlinesize;
769 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
770 (my >> ysh) * h->mb_uvlinesize;
773 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
774 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
775 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
776 src_cb = h->edge_emu_buffer;
778 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
779 height >> (chroma_idc == 1 /* yuv420 */),
780 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
783 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
784 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
785 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
786 src_cr = h->edge_emu_buffer;
788 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
789 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
792 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
793 int height, int delta,
794 uint8_t *dest_y, uint8_t *dest_cb,
796 int x_offset, int y_offset,
797 qpel_mc_func *qpix_put,
798 h264_chroma_mc_func chroma_put,
799 qpel_mc_func *qpix_avg,
800 h264_chroma_mc_func chroma_avg,
801 int list0, int list1,
802 int pixel_shift, int chroma_idc)
804 qpel_mc_func *qpix_op = qpix_put;
805 h264_chroma_mc_func chroma_op = chroma_put;
807 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
808 if (chroma_idc == 3 /* yuv444 */) {
809 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
810 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
811 } else if (chroma_idc == 2 /* yuv422 */) {
812 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
813 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
814 } else { /* yuv420 */
815 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
816 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
818 x_offset += 8 * h->mb_x;
819 y_offset += 8 * (h->mb_y >> MB_FIELD);
822 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
823 mc_dir_part(h, ref, n, square, height, delta, 0,
824 dest_y, dest_cb, dest_cr, x_offset, y_offset,
825 qpix_op, chroma_op, pixel_shift, chroma_idc);
828 chroma_op = chroma_avg;
832 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
833 mc_dir_part(h, ref, n, square, height, delta, 1,
834 dest_y, dest_cb, dest_cr, x_offset, y_offset,
835 qpix_op, chroma_op, pixel_shift, chroma_idc);
839 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
840 int height, int delta,
841 uint8_t *dest_y, uint8_t *dest_cb,
843 int x_offset, int y_offset,
844 qpel_mc_func *qpix_put,
845 h264_chroma_mc_func chroma_put,
846 h264_weight_func luma_weight_op,
847 h264_weight_func chroma_weight_op,
848 h264_biweight_func luma_weight_avg,
849 h264_biweight_func chroma_weight_avg,
850 int list0, int list1,
851 int pixel_shift, int chroma_idc)
855 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
856 if (chroma_idc == 3 /* yuv444 */) {
857 chroma_height = height;
858 chroma_weight_avg = luma_weight_avg;
859 chroma_weight_op = luma_weight_op;
860 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
861 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
862 } else if (chroma_idc == 2 /* yuv422 */) {
863 chroma_height = height;
864 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
865 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
866 } else { /* yuv420 */
867 chroma_height = height >> 1;
868 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
869 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
871 x_offset += 8 * h->mb_x;
872 y_offset += 8 * (h->mb_y >> MB_FIELD);
874 if (list0 && list1) {
875 /* don't optimize for luma-only case, since B-frames usually
876 * use implicit weights => chroma too. */
877 uint8_t *tmp_cb = h->bipred_scratchpad;
878 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
879 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
880 int refn0 = h->ref_cache[0][scan8[n]];
881 int refn1 = h->ref_cache[1][scan8[n]];
883 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
884 dest_y, dest_cb, dest_cr,
885 x_offset, y_offset, qpix_put, chroma_put,
886 pixel_shift, chroma_idc);
887 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
888 tmp_y, tmp_cb, tmp_cr,
889 x_offset, y_offset, qpix_put, chroma_put,
890 pixel_shift, chroma_idc);
892 if (h->use_weight == 2) {
893 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
894 int weight1 = 64 - weight0;
895 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
896 height, 5, weight0, weight1, 0);
897 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
898 chroma_height, 5, weight0, weight1, 0);
899 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
900 chroma_height, 5, weight0, weight1, 0);
902 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
903 h->luma_log2_weight_denom,
904 h->luma_weight[refn0][0][0],
905 h->luma_weight[refn1][1][0],
906 h->luma_weight[refn0][0][1] +
907 h->luma_weight[refn1][1][1]);
908 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
909 h->chroma_log2_weight_denom,
910 h->chroma_weight[refn0][0][0][0],
911 h->chroma_weight[refn1][1][0][0],
912 h->chroma_weight[refn0][0][0][1] +
913 h->chroma_weight[refn1][1][0][1]);
914 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
915 h->chroma_log2_weight_denom,
916 h->chroma_weight[refn0][0][1][0],
917 h->chroma_weight[refn1][1][1][0],
918 h->chroma_weight[refn0][0][1][1] +
919 h->chroma_weight[refn1][1][1][1]);
922 int list = list1 ? 1 : 0;
923 int refn = h->ref_cache[list][scan8[n]];
924 Picture *ref = &h->ref_list[list][refn];
925 mc_dir_part(h, ref, n, square, height, delta, list,
926 dest_y, dest_cb, dest_cr, x_offset, y_offset,
927 qpix_put, chroma_put, pixel_shift, chroma_idc);
929 luma_weight_op(dest_y, h->mb_linesize, height,
930 h->luma_log2_weight_denom,
931 h->luma_weight[refn][list][0],
932 h->luma_weight[refn][list][1]);
933 if (h->use_weight_chroma) {
934 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
935 h->chroma_log2_weight_denom,
936 h->chroma_weight[refn][list][0][0],
937 h->chroma_weight[refn][list][0][1]);
938 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
939 h->chroma_log2_weight_denom,
940 h->chroma_weight[refn][list][1][0],
941 h->chroma_weight[refn][list][1][1]);
946 static av_always_inline void prefetch_motion(H264Context *h, int list,
947 int pixel_shift, int chroma_idc)
949 /* fetch pixels for estimated mv 4 macroblocks ahead
950 * optimized for 64byte cache lines */
951 const int refn = h->ref_cache[list][scan8[0]];
953 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
954 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
955 uint8_t **src = h->ref_list[list][refn].f.data;
956 int off = (mx << pixel_shift) +
957 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
959 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
960 if (chroma_idc == 3 /* yuv444 */) {
961 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
962 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
964 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
965 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
970 static void free_tables(H264Context *h, int free_rbsp)
975 av_freep(&h->intra4x4_pred_mode);
976 av_freep(&h->chroma_pred_mode_table);
977 av_freep(&h->cbp_table);
978 av_freep(&h->mvd_table[0]);
979 av_freep(&h->mvd_table[1]);
980 av_freep(&h->direct_table);
981 av_freep(&h->non_zero_count);
982 av_freep(&h->slice_table_base);
983 h->slice_table = NULL;
984 av_freep(&h->list_counts);
986 av_freep(&h->mb2b_xy);
987 av_freep(&h->mb2br_xy);
990 for (i = 0; i < h->picture_count && !h->avctx->internal->is_copy; i++)
991 free_picture(h, &h->DPB[i]);
993 h->picture_count = 0;
995 for (i = 0; i < h->picture_count; i++)
996 h->DPB[i].needs_realloc = 1;
999 h->cur_pic_ptr = NULL;
1001 for (i = 0; i < MAX_THREADS; i++) {
1002 hx = h->thread_context[i];
1005 av_freep(&hx->top_borders[1]);
1006 av_freep(&hx->top_borders[0]);
1007 av_freep(&hx->bipred_scratchpad);
1008 av_freep(&hx->edge_emu_buffer);
1009 av_freep(&hx->dc_val_base);
1010 av_freep(&hx->me.scratchpad);
1011 av_freep(&hx->er.mb_index2xy);
1012 av_freep(&hx->er.error_status_table);
1013 av_freep(&hx->er.er_temp_buffer);
1014 av_freep(&hx->er.mbintra_table);
1015 av_freep(&hx->er.mbskip_table);
1018 av_freep(&hx->rbsp_buffer[1]);
1019 av_freep(&hx->rbsp_buffer[0]);
1020 hx->rbsp_buffer_size[0] = 0;
1021 hx->rbsp_buffer_size[1] = 0;
1024 av_freep(&h->thread_context[i]);
1028 static void init_dequant8_coeff_table(H264Context *h)
1031 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1033 for (i = 0; i < 6; i++) {
1034 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1035 for (j = 0; j < i; j++)
1036 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1037 64 * sizeof(uint8_t))) {
1038 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1044 for (q = 0; q < max_qp + 1; q++) {
1045 int shift = div6[q];
1047 for (x = 0; x < 64; x++)
1048 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1049 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1050 h->pps.scaling_matrix8[i][x]) << shift;
1055 static void init_dequant4_coeff_table(H264Context *h)
1058 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1059 for (i = 0; i < 6; i++) {
1060 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1061 for (j = 0; j < i; j++)
1062 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1063 16 * sizeof(uint8_t))) {
1064 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1070 for (q = 0; q < max_qp + 1; q++) {
1071 int shift = div6[q] + 2;
1073 for (x = 0; x < 16; x++)
1074 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1075 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1076 h->pps.scaling_matrix4[i][x]) << shift;
1081 static void init_dequant_tables(H264Context *h)
1084 init_dequant4_coeff_table(h);
1085 if (h->pps.transform_8x8_mode)
1086 init_dequant8_coeff_table(h);
1087 if (h->sps.transform_bypass) {
1088 for (i = 0; i < 6; i++)
1089 for (x = 0; x < 16; x++)
1090 h->dequant4_coeff[i][0][x] = 1 << 6;
1091 if (h->pps.transform_8x8_mode)
1092 for (i = 0; i < 6; i++)
1093 for (x = 0; x < 64; x++)
1094 h->dequant8_coeff[i][0][x] = 1 << 6;
1098 int ff_h264_alloc_tables(H264Context *h)
1100 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1101 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1104 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1105 row_mb_num * 8 * sizeof(uint8_t), fail)
1106 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1107 big_mb_num * 48 * sizeof(uint8_t), fail)
1108 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1109 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1110 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1111 big_mb_num * sizeof(uint16_t), fail)
1112 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1113 big_mb_num * sizeof(uint8_t), fail)
1114 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1115 16 * row_mb_num * sizeof(uint8_t), fail);
1116 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1117 16 * row_mb_num * sizeof(uint8_t), fail);
1118 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1119 4 * big_mb_num * sizeof(uint8_t), fail);
1120 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1121 big_mb_num * sizeof(uint8_t), fail)
1123 memset(h->slice_table_base, -1,
1124 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1125 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1127 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1128 big_mb_num * sizeof(uint32_t), fail);
1129 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1130 big_mb_num * sizeof(uint32_t), fail);
1131 for (y = 0; y < h->mb_height; y++)
1132 for (x = 0; x < h->mb_width; x++) {
1133 const int mb_xy = x + y * h->mb_stride;
1134 const int b_xy = 4 * x + 4 * y * h->b_stride;
1136 h->mb2b_xy[mb_xy] = b_xy;
1137 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1140 if (!h->dequant4_coeff[0])
1141 init_dequant_tables(h);
1144 h->picture_count = MAX_PICTURE_COUNT * FFMAX(1, h->avctx->thread_count);
1145 h->DPB = av_mallocz_array(h->picture_count, sizeof(*h->DPB));
1147 return AVERROR(ENOMEM);
1148 for (i = 0; i < h->picture_count; i++)
1149 avcodec_get_frame_defaults(&h->DPB[i].f);
1150 avcodec_get_frame_defaults(&h->cur_pic.f);
1161 * Mimic alloc_tables(), but for every context thread.
1163 static void clone_tables(H264Context *dst, H264Context *src, int i)
1165 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1166 dst->non_zero_count = src->non_zero_count;
1167 dst->slice_table = src->slice_table;
1168 dst->cbp_table = src->cbp_table;
1169 dst->mb2b_xy = src->mb2b_xy;
1170 dst->mb2br_xy = src->mb2br_xy;
1171 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1172 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1173 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1174 dst->direct_table = src->direct_table;
1175 dst->list_counts = src->list_counts;
1176 dst->DPB = src->DPB;
1177 dst->cur_pic_ptr = src->cur_pic_ptr;
1178 dst->cur_pic = src->cur_pic;
1179 dst->bipred_scratchpad = NULL;
1180 dst->edge_emu_buffer = NULL;
1181 dst->me.scratchpad = NULL;
1182 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1183 src->sps.chroma_format_idc);
1188 * Allocate buffers which are not shared amongst multiple threads.
1190 static int context_init(H264Context *h)
1192 ERContext *er = &h->er;
1193 int mb_array_size = h->mb_height * h->mb_stride;
1194 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1195 int c_size = h->mb_stride * (h->mb_height + 1);
1196 int yc_size = y_size + 2 * c_size;
1199 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1200 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1201 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1202 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1204 h->ref_cache[0][scan8[5] + 1] =
1205 h->ref_cache[0][scan8[7] + 1] =
1206 h->ref_cache[0][scan8[13] + 1] =
1207 h->ref_cache[1][scan8[5] + 1] =
1208 h->ref_cache[1][scan8[7] + 1] =
1209 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1212 er->avctx = h->avctx;
1214 er->decode_mb = h264_er_decode_mb;
1216 er->quarter_sample = 1;
1218 er->mb_num = h->mb_num;
1219 er->mb_width = h->mb_width;
1220 er->mb_height = h->mb_height;
1221 er->mb_stride = h->mb_stride;
1222 er->b8_stride = h->mb_width * 2 + 1;
1224 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1225 fail); // error ressilience code looks cleaner with this
1226 for (y = 0; y < h->mb_height; y++)
1227 for (x = 0; x < h->mb_width; x++)
1228 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1230 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1231 h->mb_stride + h->mb_width;
1233 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1234 mb_array_size * sizeof(uint8_t), fail);
1236 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1237 memset(er->mbintra_table, 1, mb_array_size);
1239 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1241 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1244 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1245 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1246 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1247 er->dc_val[2] = er->dc_val[1] + c_size;
1248 for (i = 0; i < yc_size; i++)
1249 h->dc_val_base[i] = 1024;
1254 return -1; // free_tables will clean up for us
1257 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1258 int parse_extradata);
1260 static av_cold void common_init(H264Context *h)
1263 h->width = h->avctx->width;
1264 h->height = h->avctx->height;
1266 h->bit_depth_luma = 8;
1267 h->chroma_format_idc = 1;
1269 h->avctx->bits_per_raw_sample = 8;
1270 h->cur_chroma_format_idc = 1;
1272 ff_h264dsp_init(&h->h264dsp, 8, 1);
1273 av_assert0(h->sps.bit_depth_chroma == 0);
1274 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1275 ff_h264qpel_init(&h->h264qpel, 8);
1276 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1278 h->dequant_coeff_pps = -1;
1280 h->dsp.dct_bits = 16;
1281 /* needed so that IDCT permutation is known early */
1282 ff_dsputil_init(&h->dsp, h->avctx);
1283 ff_videodsp_init(&h->vdsp, 8);
1285 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1286 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1289 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1291 AVCodecContext *avctx = h->avctx;
1293 if (!buf || size <= 0)
1297 int i, cnt, nalsize;
1298 const unsigned char *p = buf;
1303 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1306 /* sps and pps in the avcC always have length coded with 2 bytes,
1307 * so put a fake nal_length_size = 2 while parsing them */
1308 h->nal_length_size = 2;
1309 // Decode sps from avcC
1310 cnt = *(p + 5) & 0x1f; // Number of sps
1312 for (i = 0; i < cnt; i++) {
1313 nalsize = AV_RB16(p) + 2;
1314 if(nalsize > size - (p-buf))
1316 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1317 av_log(avctx, AV_LOG_ERROR,
1318 "Decoding sps %d from avcC failed\n", i);
1323 // Decode pps from avcC
1324 cnt = *(p++); // Number of pps
1325 for (i = 0; i < cnt; i++) {
1326 nalsize = AV_RB16(p) + 2;
1327 if(nalsize > size - (p-buf))
1329 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1330 av_log(avctx, AV_LOG_ERROR,
1331 "Decoding pps %d from avcC failed\n", i);
1336 // Now store right nal length size, that will be used to parse all other nals
1337 h->nal_length_size = (buf[4] & 0x03) + 1;
1340 if (decode_nal_units(h, buf, size, 1) < 0)
1346 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1348 H264Context *h = avctx->priv_data;
1354 h->picture_structure = PICT_FRAME;
1355 h->picture_range_start = 0;
1356 h->picture_range_end = MAX_PICTURE_COUNT;
1357 h->slice_context_count = 1;
1358 h->workaround_bugs = avctx->workaround_bugs;
1359 h->flags = avctx->flags;
1362 // s->decode_mb = ff_h263_decode_mb;
1363 if (!avctx->has_b_frames)
1366 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1368 ff_h264_decode_init_vlc();
1371 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1373 h->thread_context[0] = h;
1374 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1375 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1376 h->last_pocs[i] = INT_MIN;
1377 h->prev_poc_msb = 1 << 16;
1378 h->prev_frame_num = -1;
1380 ff_h264_reset_sei(h);
1381 if (avctx->codec_id == AV_CODEC_ID_H264) {
1382 if (avctx->ticks_per_frame == 1) {
1383 if(h->avctx->time_base.den < INT_MAX/2) {
1384 h->avctx->time_base.den *= 2;
1386 h->avctx->time_base.num /= 2;
1388 avctx->ticks_per_frame = 2;
1391 if (avctx->extradata_size > 0 && avctx->extradata &&
1392 ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
1393 ff_h264_free_context(h);
1397 if (h->sps.bitstream_restriction_flag &&
1398 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1399 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1403 ff_init_cabac_states();
1408 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1409 #undef REBASE_PICTURE
1410 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1411 ((pic && pic >= old_ctx->DPB && \
1412 pic < old_ctx->DPB + old_ctx->picture_count) ? \
1413 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1415 static void copy_picture_range(Picture **to, Picture **from, int count,
1416 H264Context *new_base,
1417 H264Context *old_base)
1421 for (i = 0; i < count; i++) {
1422 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1423 IN_RANGE(from[i], old_base->DPB,
1424 sizeof(Picture) * old_base->picture_count) ||
1426 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1430 static void copy_parameter_set(void **to, void **from, int count, int size)
1434 for (i = 0; i < count; i++) {
1435 if (to[i] && !from[i])
1437 else if (from[i] && !to[i])
1438 to[i] = av_malloc(size);
1441 memcpy(to[i], from[i], size);
1445 static int decode_init_thread_copy(AVCodecContext *avctx)
1447 H264Context *h = avctx->priv_data;
1449 if (!avctx->internal->is_copy)
1451 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1452 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1454 h->context_initialized = 0;
1459 #define copy_fields(to, from, start_field, end_field) \
1460 memcpy(&to->start_field, &from->start_field, \
1461 (char *)&to->end_field - (char *)&to->start_field)
1463 static int h264_slice_header_init(H264Context *, int);
1465 static int h264_set_parameter_from_sps(H264Context *h);
1467 static int decode_update_thread_context(AVCodecContext *dst,
1468 const AVCodecContext *src)
1470 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1471 int inited = h->context_initialized, err = 0;
1472 int context_reinitialized = 0;
1479 (h->width != h1->width ||
1480 h->height != h1->height ||
1481 h->mb_width != h1->mb_width ||
1482 h->mb_height != h1->mb_height ||
1483 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1484 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1485 h->sps.colorspace != h1->sps.colorspace)) {
1487 av_freep(&h->bipred_scratchpad);
1489 h->width = h1->width;
1490 h->height = h1->height;
1491 h->mb_height = h1->mb_height;
1492 h->mb_width = h1->mb_width;
1493 h->mb_num = h1->mb_num;
1494 h->mb_stride = h1->mb_stride;
1495 h->b_stride = h1->b_stride;
1497 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1498 MAX_SPS_COUNT, sizeof(SPS));
1500 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1501 MAX_PPS_COUNT, sizeof(PPS));
1504 if ((err = h264_slice_header_init(h, 1)) < 0) {
1505 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1508 context_reinitialized = 1;
1511 h264_set_parameter_from_sps(h);
1512 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1513 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1516 /* update linesize on resize for h264. The h264 decoder doesn't
1517 * necessarily call ff_MPV_frame_start in the new thread */
1518 h->linesize = h1->linesize;
1519 h->uvlinesize = h1->uvlinesize;
1521 /* copy block_offset since frame_start may not be called */
1522 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1525 for (i = 0; i < MAX_SPS_COUNT; i++)
1526 av_freep(h->sps_buffers + i);
1528 for (i = 0; i < MAX_PPS_COUNT; i++)
1529 av_freep(h->pps_buffers + i);
1531 memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1532 memcpy(&h->cabac, &h1->cabac,
1533 sizeof(H264Context) - offsetof(H264Context, cabac));
1534 av_assert0(&h->cabac == &h->mb_padding + 1);
1536 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1537 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1539 memset(&h->er, 0, sizeof(h->er));
1540 memset(&h->me, 0, sizeof(h->me));
1544 if (h1->context_initialized) {
1545 h->context_initialized = 0;
1547 h->picture_range_start += MAX_PICTURE_COUNT;
1548 h->picture_range_end += MAX_PICTURE_COUNT;
1550 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1552 if (ff_h264_alloc_tables(h) < 0) {
1553 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1554 return AVERROR(ENOMEM);
1559 for (i = 0; i < 2; i++) {
1560 h->rbsp_buffer[i] = NULL;
1561 h->rbsp_buffer_size[i] = 0;
1563 h->bipred_scratchpad = NULL;
1564 h->edge_emu_buffer = NULL;
1566 h->thread_context[0] = h;
1567 h->context_initialized = h1->context_initialized;
1570 h->avctx->coded_height = h1->avctx->coded_height;
1571 h->avctx->coded_width = h1->avctx->coded_width;
1572 h->avctx->width = h1->avctx->width;
1573 h->avctx->height = h1->avctx->height;
1574 h->coded_picture_number = h1->coded_picture_number;
1575 h->first_field = h1->first_field;
1576 h->picture_structure = h1->picture_structure;
1577 h->qscale = h1->qscale;
1578 h->droppable = h1->droppable;
1579 h->data_partitioning = h1->data_partitioning;
1580 h->low_delay = h1->low_delay;
1582 memcpy(h->DPB, h1->DPB, h1->picture_count * sizeof(*h1->DPB));
1584 // reset s->picture[].f.extended_data to s->picture[].f.data
1585 for (i = 0; i < h->picture_count; i++) {
1586 h->DPB[i].f.extended_data = h->DPB[i].f.data;
1587 h->DPB[i].period_since_free ++;
1590 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1591 h->cur_pic = h1->cur_pic;
1592 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1594 h->workaround_bugs = h1->workaround_bugs;
1595 h->low_delay = h1->low_delay;
1596 h->droppable = h1->droppable;
1598 /* frame_start may not be called for the next thread (if it's decoding
1599 * a bottom field) so this has to be allocated here */
1601 err = alloc_scratch_buffers(h, h1->linesize);
1606 // extradata/NAL handling
1607 h->is_avc = h1->is_avc;
1610 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1611 MAX_SPS_COUNT, sizeof(SPS));
1613 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1614 MAX_PPS_COUNT, sizeof(PPS));
1617 // Dequantization matrices
1618 // FIXME these are big - can they be only copied when PPS changes?
1619 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1621 for (i = 0; i < 6; i++)
1622 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1623 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1625 for (i = 0; i < 6; i++)
1626 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1627 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1629 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1632 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1635 copy_fields(h, h1, ref_count, list_count);
1636 copy_fields(h, h1, ref2frm, intra_gb);
1637 copy_fields(h, h1, short_ref, cabac_init_idc);
1639 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1640 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1641 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1642 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1644 h->last_slice_type = h1->last_slice_type;
1647 if (context_reinitialized)
1648 h264_set_parameter_from_sps(h);
1650 if (!h->cur_pic_ptr)
1653 if (!h->droppable) {
1654 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1655 h->prev_poc_msb = h->poc_msb;
1656 h->prev_poc_lsb = h->poc_lsb;
1658 h->prev_frame_num_offset = h->frame_num_offset;
1659 h->prev_frame_num = h->frame_num;
1660 h->outputed_poc = h->next_outputed_poc;
1665 int ff_h264_frame_start(H264Context *h)
1669 const int pixel_shift = h->pixel_shift;
1671 1<<(h->sps.bit_depth_luma-1),
1672 1<<(h->sps.bit_depth_chroma-1),
1673 1<<(h->sps.bit_depth_chroma-1),
1677 if (!ff_thread_can_start_frame(h->avctx)) {
1678 av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1682 release_unused_pictures(h, 1);
1683 h->cur_pic_ptr = NULL;
1685 i = find_unused_picture(h);
1687 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1692 pic->f.reference = h->droppable ? 0 : h->picture_structure;
1693 pic->f.coded_picture_number = h->coded_picture_number++;
1694 pic->field_picture = h->picture_structure != PICT_FRAME;
1697 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1699 * See decode_nal_units().
1701 pic->f.key_frame = 0;
1703 pic->mmco_reset = 0;
1705 if ((ret = alloc_picture(h, pic)) < 0)
1707 if(!h->sync && !h->avctx->hwaccel &&
1708 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1709 avpriv_color_frame(&pic->f, c);
1711 h->cur_pic_ptr = pic;
1712 h->cur_pic = *h->cur_pic_ptr;
1713 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1715 ff_er_frame_start(&h->er);
1717 assert(h->linesize && h->uvlinesize);
1719 for (i = 0; i < 16; i++) {
1720 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1721 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1723 for (i = 0; i < 16; i++) {
1724 h->block_offset[16 + i] =
1725 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1726 h->block_offset[48 + 16 + i] =
1727 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1730 /* can't be in alloc_tables because linesize isn't known there.
1731 * FIXME: redo bipred weight to not require extra buffer? */
1732 for (i = 0; i < h->slice_context_count; i++)
1733 if (h->thread_context[i]) {
1734 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1739 /* Some macroblocks can be accessed before they're available in case
1740 * of lost slices, MBAFF or threading. */
1741 memset(h->slice_table, -1,
1742 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1744 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1745 // h->cur_pic.f.reference /* || h->contains_intra */ || 1;
1747 /* We mark the current picture as non-reference after allocating it, so
1748 * that if we break out due to an error it can be released automatically
1749 * in the next ff_MPV_frame_start().
1750 * SVQ3 as well as most other codecs have only last/next/current and thus
1751 * get released even with set reference, besides SVQ3 and others do not
1752 * mark frames as reference later "naturally". */
1753 if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
1754 h->cur_pic_ptr->f.reference = 0;
1756 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1758 h->next_output_pic = NULL;
1760 assert(h->cur_pic_ptr->long_ref == 0);
1766 * Run setup operations that must be run after slice header decoding.
1767 * This includes finding the next displayed frame.
1769 * @param h h264 master context
1770 * @param setup_finished enough NALs have been read that we can call
1771 * ff_thread_finish_setup()
1773 static void decode_postinit(H264Context *h, int setup_finished)
1775 Picture *out = h->cur_pic_ptr;
1776 Picture *cur = h->cur_pic_ptr;
1777 int i, pics, out_of_order, out_idx;
1779 h->cur_pic_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1780 h->cur_pic_ptr->f.pict_type = h->pict_type;
1782 if (h->next_output_pic)
1785 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1786 /* FIXME: if we have two PAFF fields in one packet, we can't start
1787 * the next thread here. If we have one field per packet, we can.
1788 * The check in decode_nal_units() is not good enough to find this
1789 * yet, so we assume the worst for now. */
1790 // if (setup_finished)
1791 // ff_thread_finish_setup(h->avctx);
1795 cur->f.interlaced_frame = 0;
1796 cur->f.repeat_pict = 0;
1798 /* Signal interlacing information externally. */
1799 /* Prioritize picture timing SEI information over used
1800 * decoding process if it exists. */
1802 if (h->sps.pic_struct_present_flag) {
1803 switch (h->sei_pic_struct) {
1804 case SEI_PIC_STRUCT_FRAME:
1806 case SEI_PIC_STRUCT_TOP_FIELD:
1807 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1808 cur->f.interlaced_frame = 1;
1810 case SEI_PIC_STRUCT_TOP_BOTTOM:
1811 case SEI_PIC_STRUCT_BOTTOM_TOP:
1812 if (FIELD_OR_MBAFF_PICTURE)
1813 cur->f.interlaced_frame = 1;
1815 // try to flag soft telecine progressive
1816 cur->f.interlaced_frame = h->prev_interlaced_frame;
1818 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1819 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1820 /* Signal the possibility of telecined film externally
1821 * (pic_struct 5,6). From these hints, let the applications
1822 * decide if they apply deinterlacing. */
1823 cur->f.repeat_pict = 1;
1825 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1826 cur->f.repeat_pict = 2;
1828 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1829 cur->f.repeat_pict = 4;
1833 if ((h->sei_ct_type & 3) &&
1834 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1835 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1837 /* Derive interlacing flag from used decoding process. */
1838 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1840 h->prev_interlaced_frame = cur->f.interlaced_frame;
1842 if (cur->field_poc[0] != cur->field_poc[1]) {
1843 /* Derive top_field_first from field pocs. */
1844 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1846 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1847 /* Use picture timing SEI information. Even if it is a
1848 * information of a past frame, better than nothing. */
1849 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1850 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1851 cur->f.top_field_first = 1;
1853 cur->f.top_field_first = 0;
1855 /* Most likely progressive */
1856 cur->f.top_field_first = 0;
1860 cur->mmco_reset = h->mmco_reset;
1862 // FIXME do something with unavailable reference frames
1864 /* Sort B-frames into display order */
1866 if (h->sps.bitstream_restriction_flag &&
1867 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1868 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1872 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1873 !h->sps.bitstream_restriction_flag) {
1874 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1878 for (i = 0; 1; i++) {
1879 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
1881 h->last_pocs[i-1] = cur->poc;
1884 h->last_pocs[i-1]= h->last_pocs[i];
1887 out_of_order = MAX_DELAYED_PIC_COUNT - i;
1888 if( cur->f.pict_type == AV_PICTURE_TYPE_B
1889 || (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))
1890 out_of_order = FFMAX(out_of_order, 1);
1891 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
1892 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
1893 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
1894 h->last_pocs[i] = INT_MIN;
1895 h->last_pocs[0] = cur->poc;
1896 cur->mmco_reset = 1;
1897 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
1898 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
1899 h->avctx->has_b_frames = out_of_order;
1904 while (h->delayed_pic[pics])
1907 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1909 h->delayed_pic[pics++] = cur;
1910 if (cur->f.reference == 0)
1911 cur->f.reference = DELAYED_PIC_REF;
1913 out = h->delayed_pic[0];
1915 for (i = 1; h->delayed_pic[i] &&
1916 !h->delayed_pic[i]->f.key_frame &&
1917 !h->delayed_pic[i]->mmco_reset;
1919 if (h->delayed_pic[i]->poc < out->poc) {
1920 out = h->delayed_pic[i];
1923 if (h->avctx->has_b_frames == 0 &&
1924 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
1925 h->next_outputed_poc = INT_MIN;
1926 out_of_order = out->poc < h->next_outputed_poc;
1928 if (out_of_order || pics > h->avctx->has_b_frames) {
1929 out->f.reference &= ~DELAYED_PIC_REF;
1930 // for frame threading, the owner must be the second field's thread or
1931 // else the first thread can release the picture and reuse it unsafely
1933 for (i = out_idx; h->delayed_pic[i]; i++)
1934 h->delayed_pic[i] = h->delayed_pic[i + 1];
1936 if (!out_of_order && pics > h->avctx->has_b_frames) {
1937 h->next_output_pic = out;
1938 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
1939 h->next_outputed_poc = INT_MIN;
1941 h->next_outputed_poc = out->poc;
1943 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1946 if (h->next_output_pic && h->next_output_pic->sync) {
1951 ff_thread_finish_setup(h->avctx);
1954 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1955 uint8_t *src_cb, uint8_t *src_cr,
1956 int linesize, int uvlinesize,
1959 uint8_t *top_border;
1961 const int pixel_shift = h->pixel_shift;
1962 int chroma444 = CHROMA444;
1963 int chroma422 = CHROMA422;
1966 src_cb -= uvlinesize;
1967 src_cr -= uvlinesize;
1969 if (!simple && FRAME_MBAFF) {
1972 top_border = h->top_borders[0][h->mb_x];
1973 AV_COPY128(top_border, src_y + 15 * linesize);
1975 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1976 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
1979 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1980 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1981 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1982 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1984 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1985 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1987 } else if (chroma422) {
1989 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1990 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1992 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1993 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1997 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1998 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2000 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2001 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2006 } else if (MB_MBAFF) {
2012 top_border = h->top_borders[top_idx][h->mb_x];
2013 /* There are two lines saved, the line above the top macroblock
2014 * of a pair, and the line above the bottom macroblock. */
2015 AV_COPY128(top_border, src_y + 16 * linesize);
2017 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2019 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2022 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2023 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2024 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2025 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2027 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2028 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2030 } else if (chroma422) {
2032 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2033 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2035 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2036 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2040 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2041 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2043 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2044 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2050 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2051 uint8_t *src_cb, uint8_t *src_cr,
2052 int linesize, int uvlinesize,
2053 int xchg, int chroma444,
2054 int simple, int pixel_shift)
2056 int deblock_topleft;
2059 uint8_t *top_border_m1;
2060 uint8_t *top_border;
2062 if (!simple && FRAME_MBAFF) {
2067 top_idx = MB_MBAFF ? 0 : 1;
2071 if (h->deblocking_filter == 2) {
2072 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2073 deblock_top = h->top_type;
2075 deblock_topleft = (h->mb_x > 0);
2076 deblock_top = (h->mb_y > !!MB_FIELD);
2079 src_y -= linesize + 1 + pixel_shift;
2080 src_cb -= uvlinesize + 1 + pixel_shift;
2081 src_cr -= uvlinesize + 1 + pixel_shift;
2083 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2084 top_border = h->top_borders[top_idx][h->mb_x];
2086 #define XCHG(a, b, xchg) \
2087 if (pixel_shift) { \
2089 AV_SWAP64(b + 0, a + 0); \
2090 AV_SWAP64(b + 8, a + 8); \
2100 if (deblock_topleft) {
2101 XCHG(top_border_m1 + (8 << pixel_shift),
2102 src_y - (7 << pixel_shift), 1);
2104 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2105 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2106 if (h->mb_x + 1 < h->mb_width) {
2107 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2108 src_y + (17 << pixel_shift), 1);
2111 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2113 if (deblock_topleft) {
2114 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2115 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2117 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2118 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2119 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2120 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2121 if (h->mb_x + 1 < h->mb_width) {
2122 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2123 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2127 if (deblock_topleft) {
2128 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2129 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2131 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2132 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2138 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2141 if (high_bit_depth) {
2142 return AV_RN32A(((int32_t *)mb) + index);
2144 return AV_RN16A(mb + index);
2147 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2148 int index, int value)
2150 if (high_bit_depth) {
2151 AV_WN32A(((int32_t *)mb) + index, value);
2153 AV_WN16A(mb + index, value);
2156 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2157 int mb_type, int is_h264,
2159 int transform_bypass,
2163 uint8_t *dest_y, int p)
2165 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2166 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2168 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2169 block_offset += 16 * p;
2170 if (IS_INTRA4x4(mb_type)) {
2171 if (IS_8x8DCT(mb_type)) {
2172 if (transform_bypass) {
2174 idct_add = h->h264dsp.h264_add_pixels8;
2176 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2177 idct_add = h->h264dsp.h264_idct8_add;
2179 for (i = 0; i < 16; i += 4) {
2180 uint8_t *const ptr = dest_y + block_offset[i];
2181 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2182 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2183 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2185 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2186 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2187 (h->topright_samples_available << i) & 0x4000, linesize);
2189 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2190 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2192 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2197 if (transform_bypass) {
2199 idct_add = h->h264dsp.h264_add_pixels4;
2201 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2202 idct_add = h->h264dsp.h264_idct_add;
2204 for (i = 0; i < 16; i++) {
2205 uint8_t *const ptr = dest_y + block_offset[i];
2206 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2208 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2209 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2214 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2215 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2216 av_assert2(h->mb_y || linesize <= block_offset[i]);
2217 if (!topright_avail) {
2219 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2220 topright = (uint8_t *)&tr_high;
2222 tr = ptr[3 - linesize] * 0x01010101u;
2223 topright = (uint8_t *)&tr;
2226 topright = ptr + (4 << pixel_shift) - linesize;
2230 h->hpc.pred4x4[dir](ptr, topright, linesize);
2231 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2234 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2235 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2237 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2238 } else if (CONFIG_SVQ3_DECODER)
2239 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2245 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2247 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2248 if (!transform_bypass)
2249 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2251 h->dequant4_coeff[p][qscale][0]);
2253 static const uint8_t dc_mapping[16] = {
2254 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2255 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2256 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2257 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
2258 for (i = 0; i < 16; i++)
2259 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2260 pixel_shift, dc_mapping[i],
2261 dctcoef_get(h->mb_luma_dc[p],
2265 } else if (CONFIG_SVQ3_DECODER)
2266 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2267 h->mb_luma_dc[p], qscale);
2271 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2272 int is_h264, int simple,
2273 int transform_bypass,
2277 uint8_t *dest_y, int p)
2279 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2281 block_offset += 16 * p;
2282 if (!IS_INTRA4x4(mb_type)) {
2284 if (IS_INTRA16x16(mb_type)) {
2285 if (transform_bypass) {
2286 if (h->sps.profile_idc == 244 &&
2287 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2288 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2289 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2290 h->mb + (p * 256 << pixel_shift),
2293 for (i = 0; i < 16; i++)
2294 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2295 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2296 h->h264dsp.h264_add_pixels4(dest_y + block_offset[i],
2297 h->mb + (i * 16 + p * 256 << pixel_shift),
2301 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2302 h->mb + (p * 256 << pixel_shift),
2304 h->non_zero_count_cache + p * 5 * 8);
2306 } else if (h->cbp & 15) {
2307 if (transform_bypass) {
2308 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2309 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8
2310 : h->h264dsp.h264_add_pixels4;
2311 for (i = 0; i < 16; i += di)
2312 if (h->non_zero_count_cache[scan8[i + p * 16]])
2313 idct_add(dest_y + block_offset[i],
2314 h->mb + (i * 16 + p * 256 << pixel_shift),
2317 if (IS_8x8DCT(mb_type))
2318 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2319 h->mb + (p * 256 << pixel_shift),
2321 h->non_zero_count_cache + p * 5 * 8);
2323 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2324 h->mb + (p * 256 << pixel_shift),
2326 h->non_zero_count_cache + p * 5 * 8);
2329 } else if (CONFIG_SVQ3_DECODER) {
2330 for (i = 0; i < 16; i++)
2331 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2332 // FIXME benchmark weird rule, & below
2333 uint8_t *const ptr = dest_y + block_offset[i];
2334 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2335 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2343 #include "h264_mb_template.c"
2347 #include "h264_mb_template.c"
2351 #include "h264_mb_template.c"
2353 void ff_h264_hl_decode_mb(H264Context *h)
2355 const int mb_xy = h->mb_xy;
2356 const int mb_type = h->cur_pic.f.mb_type[mb_xy];
2357 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
2360 if (is_complex || h->pixel_shift)
2361 hl_decode_mb_444_complex(h);
2363 hl_decode_mb_444_simple_8(h);
2364 } else if (is_complex) {
2365 hl_decode_mb_complex(h);
2366 } else if (h->pixel_shift) {
2367 hl_decode_mb_simple_16(h);
2369 hl_decode_mb_simple_8(h);
2372 static int pred_weight_table(H264Context *h)
2375 int luma_def, chroma_def;
2378 h->use_weight_chroma = 0;
2379 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2380 if (h->sps.chroma_format_idc)
2381 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2382 luma_def = 1 << h->luma_log2_weight_denom;
2383 chroma_def = 1 << h->chroma_log2_weight_denom;
2385 for (list = 0; list < 2; list++) {
2386 h->luma_weight_flag[list] = 0;
2387 h->chroma_weight_flag[list] = 0;
2388 for (i = 0; i < h->ref_count[list]; i++) {
2389 int luma_weight_flag, chroma_weight_flag;
2391 luma_weight_flag = get_bits1(&h->gb);
2392 if (luma_weight_flag) {
2393 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2394 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2395 if (h->luma_weight[i][list][0] != luma_def ||
2396 h->luma_weight[i][list][1] != 0) {
2398 h->luma_weight_flag[list] = 1;
2401 h->luma_weight[i][list][0] = luma_def;
2402 h->luma_weight[i][list][1] = 0;
2405 if (h->sps.chroma_format_idc) {
2406 chroma_weight_flag = get_bits1(&h->gb);
2407 if (chroma_weight_flag) {
2409 for (j = 0; j < 2; j++) {
2410 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2411 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2412 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2413 h->chroma_weight[i][list][j][1] != 0) {
2414 h->use_weight_chroma = 1;
2415 h->chroma_weight_flag[list] = 1;
2420 for (j = 0; j < 2; j++) {
2421 h->chroma_weight[i][list][j][0] = chroma_def;
2422 h->chroma_weight[i][list][j][1] = 0;
2427 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2430 h->use_weight = h->use_weight || h->use_weight_chroma;
2435 * Initialize implicit_weight table.
2436 * @param field 0/1 initialize the weight for interlaced MBAFF
2437 * -1 initializes the rest
2439 static void implicit_weight_table(H264Context *h, int field)
2441 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2443 for (i = 0; i < 2; i++) {
2444 h->luma_weight_flag[i] = 0;
2445 h->chroma_weight_flag[i] = 0;
2449 if (h->picture_structure == PICT_FRAME) {
2450 cur_poc = h->cur_pic_ptr->poc;
2452 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2454 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2455 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2457 h->use_weight_chroma = 0;
2461 ref_count0 = h->ref_count[0];
2462 ref_count1 = h->ref_count[1];
2464 cur_poc = h->cur_pic_ptr->field_poc[field];
2466 ref_count0 = 16 + 2 * h->ref_count[0];
2467 ref_count1 = 16 + 2 * h->ref_count[1];
2471 h->use_weight_chroma = 2;
2472 h->luma_log2_weight_denom = 5;
2473 h->chroma_log2_weight_denom = 5;
2475 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2476 int poc0 = h->ref_list[0][ref0].poc;
2477 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2479 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2480 int poc1 = h->ref_list[1][ref1].poc;
2481 int td = av_clip(poc1 - poc0, -128, 127);
2483 int tb = av_clip(cur_poc - poc0, -128, 127);
2484 int tx = (16384 + (FFABS(td) >> 1)) / td;
2485 int dist_scale_factor = (tb * tx + 32) >> 8;
2486 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2487 w = 64 - dist_scale_factor;
2491 h->implicit_weight[ref0][ref1][0] =
2492 h->implicit_weight[ref0][ref1][1] = w;
2494 h->implicit_weight[ref0][ref1][field] = w;
2501 * instantaneous decoder refresh.
2503 static void idr(H264Context *h)
2506 ff_h264_remove_all_refs(h);
2507 h->prev_frame_num = 0;
2508 h->prev_frame_num_offset = 0;
2509 h->prev_poc_msb = 1<<16;
2510 h->prev_poc_lsb = 0;
2511 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2512 h->last_pocs[i] = INT_MIN;
2515 /* forget old pics after a seek */
2516 static void flush_change(H264Context *h)
2520 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2521 h->prev_interlaced_frame = 1;
2523 h->prev_frame_num = -1;
2524 if (h->cur_pic_ptr) {
2525 h->cur_pic_ptr->f.reference = 0;
2526 for (j=i=0; h->delayed_pic[i]; i++)
2527 if (h->delayed_pic[i] != h->cur_pic_ptr)
2528 h->delayed_pic[j++] = h->delayed_pic[i];
2529 h->delayed_pic[j] = NULL;
2532 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2533 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2534 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2535 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2536 ff_h264_reset_sei(h);
2537 h->recovery_frame= -1;
2540 h->current_slice = 0;
2543 /* forget old pics after a seek */
2544 static void flush_dpb(AVCodecContext *avctx)
2546 H264Context *h = avctx->priv_data;
2549 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2550 if (h->delayed_pic[i])
2551 h->delayed_pic[i]->f.reference = 0;
2552 h->delayed_pic[i] = NULL;
2557 for (i = 0; i < h->picture_count; i++) {
2558 if (h->DPB[i].f.data[0])
2559 free_frame_buffer(h, &h->DPB[i]);
2561 h->cur_pic_ptr = NULL;
2563 h->mb_x = h->mb_y = 0;
2565 h->parse_context.state = -1;
2566 h->parse_context.frame_start_found = 0;
2567 h->parse_context.overread = 0;
2568 h->parse_context.overread_index = 0;
2569 h->parse_context.index = 0;
2570 h->parse_context.last_index = 0;
2573 static int init_poc(H264Context *h)
2575 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2577 Picture *cur = h->cur_pic_ptr;
2579 h->frame_num_offset = h->prev_frame_num_offset;
2580 if (h->frame_num < h->prev_frame_num)
2581 h->frame_num_offset += max_frame_num;
2583 if (h->sps.poc_type == 0) {
2584 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2586 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2587 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2588 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2589 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2591 h->poc_msb = h->prev_poc_msb;
2593 field_poc[1] = h->poc_msb + h->poc_lsb;
2594 if (h->picture_structure == PICT_FRAME)
2595 field_poc[1] += h->delta_poc_bottom;
2596 } else if (h->sps.poc_type == 1) {
2597 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2600 if (h->sps.poc_cycle_length != 0)
2601 abs_frame_num = h->frame_num_offset + h->frame_num;
2605 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2608 expected_delta_per_poc_cycle = 0;
2609 for (i = 0; i < h->sps.poc_cycle_length; i++)
2610 // FIXME integrate during sps parse
2611 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2613 if (abs_frame_num > 0) {
2614 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2615 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2617 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2618 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2619 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2623 if (h->nal_ref_idc == 0)
2624 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2626 field_poc[0] = expectedpoc + h->delta_poc[0];
2627 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2629 if (h->picture_structure == PICT_FRAME)
2630 field_poc[1] += h->delta_poc[1];
2632 int poc = 2 * (h->frame_num_offset + h->frame_num);
2634 if (!h->nal_ref_idc)
2641 if (h->picture_structure != PICT_BOTTOM_FIELD)
2642 h->cur_pic_ptr->field_poc[0] = field_poc[0];
2643 if (h->picture_structure != PICT_TOP_FIELD)
2644 h->cur_pic_ptr->field_poc[1] = field_poc[1];
2645 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2651 * initialize scan tables
2653 static void init_scan_tables(H264Context *h)
2656 for (i = 0; i < 16; i++) {
2657 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2658 h->zigzag_scan[i] = T(zigzag_scan[i]);
2659 h->field_scan[i] = T(field_scan[i]);
2662 for (i = 0; i < 64; i++) {
2663 #define T(x) (x >> 3) | ((x & 7) << 3)
2664 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2665 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2666 h->field_scan8x8[i] = T(field_scan8x8[i]);
2667 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2670 if (h->sps.transform_bypass) { // FIXME same ugly
2671 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2672 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2673 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2674 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2675 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2676 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2678 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2679 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2680 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2681 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2682 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2683 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2687 static int field_end(H264Context *h, int in_setup)
2689 AVCodecContext *const avctx = h->avctx;
2693 if (!in_setup && !h->droppable)
2694 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
2695 h->picture_structure == PICT_BOTTOM_FIELD);
2697 if (CONFIG_H264_VDPAU_DECODER &&
2698 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2699 ff_vdpau_h264_set_reference_frames(h);
2701 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2702 if (!h->droppable) {
2703 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2704 h->prev_poc_msb = h->poc_msb;
2705 h->prev_poc_lsb = h->poc_lsb;
2707 h->prev_frame_num_offset = h->frame_num_offset;
2708 h->prev_frame_num = h->frame_num;
2709 h->outputed_poc = h->next_outputed_poc;
2712 if (avctx->hwaccel) {
2713 if (avctx->hwaccel->end_frame(avctx) < 0)
2714 av_log(avctx, AV_LOG_ERROR,
2715 "hardware accelerator failed to decode picture\n");
2718 if (CONFIG_H264_VDPAU_DECODER &&
2719 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2720 ff_vdpau_h264_picture_complete(h);
2723 * FIXME: Error handling code does not seem to support interlaced
2724 * when slices span multiple rows
2725 * The ff_er_add_slice calls don't work right for bottom
2726 * fields; they cause massive erroneous error concealing
2727 * Error marking covers both fields (top and bottom).
2728 * This causes a mismatched s->error_count
2729 * and a bad error table. Further, the error count goes to
2730 * INT_MAX when called for bottom field, because mb_y is
2731 * past end by one (callers fault) and resync_mb_y != 0
2732 * causes problems for the first MB line, too.
2734 if (!FIELD_PICTURE && h->current_slice && !h->sps.new) {
2735 h->er.cur_pic = h->cur_pic_ptr;
2736 h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
2737 h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
2738 ff_er_frame_end(&h->er);
2742 h->current_slice = 0;
2748 * Replicate H264 "master" context to thread contexts.
2750 static int clone_slice(H264Context *dst, H264Context *src)
2752 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2753 dst->cur_pic_ptr = src->cur_pic_ptr;
2754 dst->cur_pic = src->cur_pic;
2755 dst->linesize = src->linesize;
2756 dst->uvlinesize = src->uvlinesize;
2757 dst->first_field = src->first_field;
2759 dst->prev_poc_msb = src->prev_poc_msb;
2760 dst->prev_poc_lsb = src->prev_poc_lsb;
2761 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2762 dst->prev_frame_num = src->prev_frame_num;
2763 dst->short_ref_count = src->short_ref_count;
2765 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2766 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2767 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2769 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2770 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2776 * Compute profile from profile_idc and constraint_set?_flags.
2780 * @return profile as defined by FF_PROFILE_H264_*
2782 int ff_h264_get_profile(SPS *sps)
2784 int profile = sps->profile_idc;
2786 switch (sps->profile_idc) {
2787 case FF_PROFILE_H264_BASELINE:
2788 // constraint_set1_flag set to 1
2789 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2791 case FF_PROFILE_H264_HIGH_10:
2792 case FF_PROFILE_H264_HIGH_422:
2793 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2794 // constraint_set3_flag set to 1
2795 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2802 static int h264_set_parameter_from_sps(H264Context *h)
2804 if (h->flags & CODEC_FLAG_LOW_DELAY ||
2805 (h->sps.bitstream_restriction_flag &&
2806 !h->sps.num_reorder_frames)) {
2807 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2808 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
2809 "Reenabling low delay requires a codec flush.\n");
2814 if (h->avctx->has_b_frames < 2)
2815 h->avctx->has_b_frames = !h->low_delay;
2817 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2818 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2819 if (h->avctx->codec &&
2820 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2821 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2822 av_log(h->avctx, AV_LOG_ERROR,
2823 "VDPAU decoding does not support video colorspace.\n");
2824 return AVERROR_INVALIDDATA;
2826 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
2827 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
2828 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2829 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2830 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2831 h->pixel_shift = h->sps.bit_depth_luma > 8;
2833 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2834 h->sps.chroma_format_idc);
2835 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2836 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2837 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
2838 h->sps.chroma_format_idc);
2839 h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2840 ff_dsputil_init(&h->dsp, h->avctx);
2841 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
2843 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2844 h->sps.bit_depth_luma);
2845 return AVERROR_INVALIDDATA;
2851 static enum PixelFormat get_pixel_format(H264Context *h)
2853 switch (h->sps.bit_depth_luma) {
2856 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2857 return AV_PIX_FMT_GBRP9;
2859 return AV_PIX_FMT_YUV444P9;
2860 } else if (CHROMA422)
2861 return AV_PIX_FMT_YUV422P9;
2863 return AV_PIX_FMT_YUV420P9;
2867 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2868 return AV_PIX_FMT_GBRP10;
2870 return AV_PIX_FMT_YUV444P10;
2871 } else if (CHROMA422)
2872 return AV_PIX_FMT_YUV422P10;
2874 return AV_PIX_FMT_YUV420P10;
2878 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2879 return AV_PIX_FMT_GBRP12;
2881 return AV_PIX_FMT_YUV444P12;
2882 } else if (CHROMA422)
2883 return AV_PIX_FMT_YUV422P12;
2885 return AV_PIX_FMT_YUV420P12;
2889 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2890 return AV_PIX_FMT_GBRP14;
2892 return AV_PIX_FMT_YUV444P14;
2893 } else if (CHROMA422)
2894 return AV_PIX_FMT_YUV422P14;
2896 return AV_PIX_FMT_YUV420P14;
2900 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2901 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2902 return AV_PIX_FMT_GBR24P;
2903 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
2904 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2906 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2907 : AV_PIX_FMT_YUV444P;
2908 } else if (CHROMA422) {
2909 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2910 : AV_PIX_FMT_YUV422P;
2913 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
2914 h->avctx->codec->pix_fmts :
2915 h->avctx->color_range == AVCOL_RANGE_JPEG ?
2916 hwaccel_pixfmt_list_h264_jpeg_420 :
2917 ff_hwaccel_pixfmt_list_420;
2919 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
2920 if (fmt[i] == h->avctx->pix_fmt)
2922 return h->avctx->get_format(h->avctx, fmt);
2926 av_log(h->avctx, AV_LOG_ERROR,
2927 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2928 return AVERROR_INVALIDDATA;
2932 static int h264_slice_header_init(H264Context *h, int reinit)
2934 int nb_slices = (HAVE_THREADS &&
2935 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
2936 h->avctx->thread_count : 1;
2939 if( FFALIGN(h->avctx->width , 16 ) == h->width
2940 && FFALIGN(h->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == h->height
2941 && !h->sps.crop_right && !h->sps.crop_bottom
2942 && (h->avctx->width != h->width || h->avctx->height && h->height)
2944 av_log(h->avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
2945 h->avctx->coded_width = h->width;
2946 h->avctx->coded_height = h->height;
2948 avcodec_set_dimensions(h->avctx, h->width, h->height);
2949 h->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2950 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);
2953 h->avctx->sample_aspect_ratio = h->sps.sar;
2954 av_assert0(h->avctx->sample_aspect_ratio.den);
2955 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
2956 &h->chroma_x_shift, &h->chroma_y_shift);
2958 if (h->sps.timing_info_present_flag) {
2959 int64_t den = h->sps.time_scale;
2960 if (h->x264_build < 44U)
2962 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
2963 h->sps.num_units_in_tick, den, 1 << 30);
2966 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
2971 h->prev_interlaced_frame = 1;
2973 init_scan_tables(h);
2974 if (ff_h264_alloc_tables(h) < 0) {
2975 av_log(h->avctx, AV_LOG_ERROR,
2976 "Could not allocate memory for h264\n");
2977 return AVERROR(ENOMEM);
2980 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
2983 max_slices = FFMIN(MAX_THREADS, h->mb_height);
2985 max_slices = MAX_THREADS;
2986 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
2987 " reducing to %d\n", nb_slices, max_slices);
2988 nb_slices = max_slices;
2990 h->slice_context_count = nb_slices;
2992 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
2993 if (context_init(h) < 0) {
2994 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
2998 for (i = 1; i < h->slice_context_count; i++) {
3000 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3001 c->avctx = h->avctx;
3004 c->h264dsp = h->h264dsp;
3005 c->h264qpel = h->h264qpel;
3006 c->h264chroma = h->h264chroma;
3009 c->pixel_shift = h->pixel_shift;
3010 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3011 c->width = h->width;
3012 c->height = h->height;
3013 c->linesize = h->linesize;
3014 c->uvlinesize = h->uvlinesize;
3015 c->chroma_x_shift = h->chroma_x_shift;
3016 c->chroma_y_shift = h->chroma_y_shift;
3017 c->qscale = h->qscale;
3018 c->droppable = h->droppable;
3019 c->data_partitioning = h->data_partitioning;
3020 c->low_delay = h->low_delay;
3021 c->mb_width = h->mb_width;
3022 c->mb_height = h->mb_height;
3023 c->mb_stride = h->mb_stride;
3024 c->mb_num = h->mb_num;
3025 c->flags = h->flags;
3026 c->workaround_bugs = h->workaround_bugs;
3027 c->pict_type = h->pict_type;
3029 init_scan_tables(c);
3030 clone_tables(c, h, i);
3031 c->context_initialized = 1;
3034 for (i = 0; i < h->slice_context_count; i++)
3035 if (context_init(h->thread_context[i]) < 0) {
3036 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3041 h->context_initialized = 1;
3047 * Decode a slice header.
3048 * This will also call ff_MPV_common_init() and frame_start() as needed.
3050 * @param h h264context
3051 * @param h0 h264 master context (differs from 'h' when doing sliced based
3052 * parallel decoding)
3054 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3056 static int decode_slice_header(H264Context *h, H264Context *h0)
3058 unsigned int first_mb_in_slice;
3059 unsigned int pps_id;
3060 int num_ref_idx_active_override_flag, ret;
3061 unsigned int slice_type, tmp, i, j;
3062 int default_ref_list_done = 0;
3063 int last_pic_structure, last_pic_droppable;
3065 int needs_reinit = 0;
3067 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3068 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3070 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3072 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3073 if (h0->current_slice && FIELD_PICTURE) {
3077 h0->current_slice = 0;
3078 if (!h0->first_field) {
3079 if (h->cur_pic_ptr && !h->droppable &&
3080 h->cur_pic_ptr->owner2 == h) {
3081 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
3082 h->picture_structure == PICT_BOTTOM_FIELD);
3084 h->cur_pic_ptr = NULL;
3088 slice_type = get_ue_golomb_31(&h->gb);
3089 if (slice_type > 9) {
3090 av_log(h->avctx, AV_LOG_ERROR,
3091 "slice type too large (%d) at %d %d\n",
3092 slice_type, h->mb_x, h->mb_y);
3095 if (slice_type > 4) {
3097 h->slice_type_fixed = 1;
3099 h->slice_type_fixed = 0;
3101 slice_type = golomb_to_pict_type[slice_type];
3102 if (slice_type == AV_PICTURE_TYPE_I ||
3103 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3104 default_ref_list_done = 1;
3106 h->slice_type = slice_type;
3107 h->slice_type_nos = slice_type & 3;
3109 // to make a few old functions happy, it's wrong though
3110 h->pict_type = h->slice_type;
3112 pps_id = get_ue_golomb(&h->gb);
3113 if (pps_id >= MAX_PPS_COUNT) {
3114 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3117 if (!h0->pps_buffers[pps_id]) {
3118 av_log(h->avctx, AV_LOG_ERROR,
3119 "non-existing PPS %u referenced\n",
3123 h->pps = *h0->pps_buffers[pps_id];
3125 if (!h0->sps_buffers[h->pps.sps_id]) {
3126 av_log(h->avctx, AV_LOG_ERROR,
3127 "non-existing SPS %u referenced\n",
3132 if (h->pps.sps_id != h->current_sps_id ||
3133 h0->sps_buffers[h->pps.sps_id]->new) {
3134 h0->sps_buffers[h->pps.sps_id]->new = 0;
3136 h->current_sps_id = h->pps.sps_id;
3137 h->sps = *h0->sps_buffers[h->pps.sps_id];
3139 if (h->mb_width != h->sps.mb_width ||
3140 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3141 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3142 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3146 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3147 h->chroma_format_idc != h->sps.chroma_format_idc) {
3148 h->bit_depth_luma = h->sps.bit_depth_luma;
3149 h->chroma_format_idc = h->sps.chroma_format_idc;
3152 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3156 h->avctx->profile = ff_h264_get_profile(&h->sps);
3157 h->avctx->level = h->sps.level_idc;
3158 h->avctx->refs = h->sps.ref_frame_count;
3160 must_reinit = (h->context_initialized &&
3161 ( 16*h->sps.mb_width != h->avctx->coded_width
3162 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3163 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3164 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3165 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)));
3166 if (h0->avctx->pix_fmt != get_pixel_format(h0))
3169 h->mb_width = h->sps.mb_width;
3170 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3171 h->mb_num = h->mb_width * h->mb_height;
3172 h->mb_stride = h->mb_width + 1;
3174 h->b_stride = h->mb_width * 4;
3176 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3178 h->width = 16 * h->mb_width;
3179 h->height = 16 * h->mb_height;
3181 if (h->sps.video_signal_type_present_flag) {
3182 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3184 if (h->sps.colour_description_present_flag) {
3185 if (h->avctx->colorspace != h->sps.colorspace)
3187 h->avctx->color_primaries = h->sps.color_primaries;
3188 h->avctx->color_trc = h->sps.color_trc;
3189 h->avctx->colorspace = h->sps.colorspace;
3193 if (h->context_initialized &&
3199 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3200 "slice %d\n", h0->current_slice + 1);
3201 return AVERROR_INVALIDDATA;
3206 if ((ret = get_pixel_format(h)) < 0)
3208 h->avctx->pix_fmt = ret;
3210 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3211 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3213 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3214 av_log(h->avctx, AV_LOG_ERROR,
3215 "h264_slice_header_init() failed\n");
3219 if (!h->context_initialized) {
3221 av_log(h->avctx, AV_LOG_ERROR,
3222 "Cannot (re-)initialize context during parallel decoding.\n");
3226 if ((ret = get_pixel_format(h)) < 0)
3228 h->avctx->pix_fmt = ret;
3230 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3231 av_log(h->avctx, AV_LOG_ERROR,
3232 "h264_slice_header_init() failed\n");
3237 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3238 h->dequant_coeff_pps = pps_id;
3239 init_dequant_tables(h);
3242 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3245 h->mb_aff_frame = 0;
3246 last_pic_structure = h0->picture_structure;
3247 last_pic_droppable = h0->droppable;
3248 h->droppable = h->nal_ref_idc == 0;
3249 if (h->sps.frame_mbs_only_flag) {
3250 h->picture_structure = PICT_FRAME;
3252 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3253 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3256 if (get_bits1(&h->gb)) { // field_pic_flag
3257 h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
3259 h->picture_structure = PICT_FRAME;
3260 h->mb_aff_frame = h->sps.mb_aff;
3263 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3265 if (h0->current_slice != 0) {
3266 if (last_pic_structure != h->picture_structure ||
3267 last_pic_droppable != h->droppable) {
3268 av_log(h->avctx, AV_LOG_ERROR,
3269 "Changing field mode (%d -> %d) between slices is not allowed\n",
3270 last_pic_structure, h->picture_structure);
3271 h->picture_structure = last_pic_structure;
3272 h->droppable = last_pic_droppable;
3273 return AVERROR_INVALIDDATA;
3274 } else if (!h0->cur_pic_ptr) {
3275 av_log(h->avctx, AV_LOG_ERROR,
3276 "unset cur_pic_ptr on %d. slice\n",
3277 h0->current_slice + 1);
3278 return AVERROR_INVALIDDATA;
3281 /* Shorten frame num gaps so we don't have to allocate reference
3282 * frames just to throw them away */
3283 if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
3284 int unwrap_prev_frame_num = h->prev_frame_num;
3285 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3287 if (unwrap_prev_frame_num > h->frame_num)
3288 unwrap_prev_frame_num -= max_frame_num;
3290 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3291 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3292 if (unwrap_prev_frame_num < 0)
3293 unwrap_prev_frame_num += max_frame_num;
3295 h->prev_frame_num = unwrap_prev_frame_num;
3299 /* See if we have a decoded first field looking for a pair...
3300 * Here, we're using that to see if we should mark previously
3301 * decode frames as "finished".
3302 * We have to do that before the "dummy" in-between frame allocation,
3303 * since that can modify h->cur_pic_ptr. */
3304 if (h0->first_field) {
3305 assert(h0->cur_pic_ptr);
3306 assert(h0->cur_pic_ptr->f.data[0]);
3307 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3309 /* Mark old field/frame as completed */
3310 if (!last_pic_droppable && h0->cur_pic_ptr->owner2 == h0) {
3311 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3312 last_pic_structure == PICT_BOTTOM_FIELD);
3315 /* figure out if we have a complementary field pair */
3316 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3317 /* Previous field is unmatched. Don't display it, but let it
3318 * remain for reference if marked as such. */
3319 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3320 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3321 last_pic_structure == PICT_TOP_FIELD);
3324 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3325 /* This and previous field were reference, but had
3326 * different frame_nums. Consider this field first in
3327 * pair. Throw away previous field except for reference
3329 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3330 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3331 last_pic_structure == PICT_TOP_FIELD);
3334 /* Second field in complementary pair */
3335 if (!((last_pic_structure == PICT_TOP_FIELD &&
3336 h->picture_structure == PICT_BOTTOM_FIELD) ||
3337 (last_pic_structure == PICT_BOTTOM_FIELD &&
3338 h->picture_structure == PICT_TOP_FIELD))) {
3339 av_log(h->avctx, AV_LOG_ERROR,
3340 "Invalid field mode combination %d/%d\n",
3341 last_pic_structure, h->picture_structure);
3342 h->picture_structure = last_pic_structure;
3343 h->droppable = last_pic_droppable;
3344 return AVERROR_INVALIDDATA;
3345 } else if (last_pic_droppable != h->droppable) {
3346 av_log(h->avctx, AV_LOG_ERROR,
3347 "Cannot combine reference and non-reference fields in the same frame\n");
3348 av_log_ask_for_sample(h->avctx, NULL);
3349 h->picture_structure = last_pic_structure;
3350 h->droppable = last_pic_droppable;
3351 return AVERROR_PATCHWELCOME;
3354 /* Take ownership of this buffer. Note that if another thread owned
3355 * the first field of this buffer, we're not operating on that pointer,
3356 * so the original thread is still responsible for reporting progress
3357 * on that first field (or if that was us, we just did that above).
3358 * By taking ownership, we assign responsibility to ourselves to
3359 * report progress on the second field. */
3360 h0->cur_pic_ptr->owner2 = h0;
3365 while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field &&
3366 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3367 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3368 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3369 h->frame_num, h->prev_frame_num);
3370 if (!h->sps.gaps_in_frame_num_allowed_flag)
3371 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3372 h->last_pocs[i] = INT_MIN;
3373 if (ff_h264_frame_start(h) < 0)
3375 h->prev_frame_num++;
3376 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3377 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3378 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 0);
3379 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 1);
3380 if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
3381 h->avctx->err_recognition & AV_EF_EXPLODE)
3383 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3384 (h->avctx->err_recognition & AV_EF_EXPLODE))
3385 return AVERROR_INVALIDDATA;
3386 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3387 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3388 * about there being no actual duplicates.
3389 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3390 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3392 if (h->short_ref_count) {
3394 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3395 (const uint8_t **)prev->f.data, prev->f.linesize,
3396 h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
3397 h->short_ref[0]->poc = prev->poc + 2;
3399 h->short_ref[0]->frame_num = h->prev_frame_num;
3403 /* See if we have a decoded first field looking for a pair...
3404 * We're using that to see whether to continue decoding in that
3405 * frame, or to allocate a new one. */
3406 if (h0->first_field) {