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, &h->dsp, &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, 1,
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;
695 int extra_width = h->emu_edge_width;
696 int extra_height = h->emu_edge_height;
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);
2741 /* redraw edges for the frame if decoding didn't complete */
2742 if (h->er.error_count &&
2743 !h->avctx->hwaccel &&
2744 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) &&
2745 h->cur_pic_ptr->f.reference &&
2746 !(h->flags & CODEC_FLAG_EMU_EDGE)) {
2747 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(h->avctx->pix_fmt);
2748 int hshift = desc->log2_chroma_w;
2749 int vshift = desc->log2_chroma_h;
2750 h->dsp.draw_edges(h->cur_pic.f.data[0], h->linesize,
2751 h->mb_width * 16, h->mb_height * 16,
2752 EDGE_WIDTH, EDGE_WIDTH,
2753 EDGE_TOP | EDGE_BOTTOM);
2754 h->dsp.draw_edges(h->cur_pic.f.data[1], h->uvlinesize,
2755 (h->mb_width * 16) >> hshift, (h->mb_height * 16) >> vshift,
2756 EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
2757 EDGE_TOP | EDGE_BOTTOM);
2758 h->dsp.draw_edges(h->cur_pic.f.data[2], h->uvlinesize,
2759 (h->mb_width * 16) >> hshift, (h->mb_height * 16) >> vshift,
2760 EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
2761 EDGE_TOP | EDGE_BOTTOM);
2765 h->current_slice = 0;
2771 * Replicate H264 "master" context to thread contexts.
2773 static int clone_slice(H264Context *dst, H264Context *src)
2775 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2776 dst->cur_pic_ptr = src->cur_pic_ptr;
2777 dst->cur_pic = src->cur_pic;
2778 dst->linesize = src->linesize;
2779 dst->uvlinesize = src->uvlinesize;
2780 dst->first_field = src->first_field;
2782 dst->prev_poc_msb = src->prev_poc_msb;
2783 dst->prev_poc_lsb = src->prev_poc_lsb;
2784 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2785 dst->prev_frame_num = src->prev_frame_num;
2786 dst->short_ref_count = src->short_ref_count;
2788 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2789 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2790 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2792 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2793 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2799 * Compute profile from profile_idc and constraint_set?_flags.
2803 * @return profile as defined by FF_PROFILE_H264_*
2805 int ff_h264_get_profile(SPS *sps)
2807 int profile = sps->profile_idc;
2809 switch (sps->profile_idc) {
2810 case FF_PROFILE_H264_BASELINE:
2811 // constraint_set1_flag set to 1
2812 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2814 case FF_PROFILE_H264_HIGH_10:
2815 case FF_PROFILE_H264_HIGH_422:
2816 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2817 // constraint_set3_flag set to 1
2818 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2825 static int h264_set_parameter_from_sps(H264Context *h)
2827 if (h->flags & CODEC_FLAG_LOW_DELAY ||
2828 (h->sps.bitstream_restriction_flag &&
2829 !h->sps.num_reorder_frames)) {
2830 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2831 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
2832 "Reenabling low delay requires a codec flush.\n");
2837 if (h->avctx->has_b_frames < 2)
2838 h->avctx->has_b_frames = !h->low_delay;
2840 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2841 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2842 if (h->avctx->codec &&
2843 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2844 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2845 av_log(h->avctx, AV_LOG_ERROR,
2846 "VDPAU decoding does not support video colorspace.\n");
2847 return AVERROR_INVALIDDATA;
2849 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
2850 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
2851 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2852 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2853 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2854 h->pixel_shift = h->sps.bit_depth_luma > 8;
2856 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2857 h->sps.chroma_format_idc);
2858 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2859 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2860 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
2861 h->sps.chroma_format_idc);
2862 h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2863 ff_dsputil_init(&h->dsp, h->avctx);
2864 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
2866 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2867 h->sps.bit_depth_luma);
2868 return AVERROR_INVALIDDATA;
2874 static enum PixelFormat get_pixel_format(H264Context *h)
2876 switch (h->sps.bit_depth_luma) {
2879 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2880 return AV_PIX_FMT_GBRP9;
2882 return AV_PIX_FMT_YUV444P9;
2883 } else if (CHROMA422)
2884 return AV_PIX_FMT_YUV422P9;
2886 return AV_PIX_FMT_YUV420P9;
2890 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2891 return AV_PIX_FMT_GBRP10;
2893 return AV_PIX_FMT_YUV444P10;
2894 } else if (CHROMA422)
2895 return AV_PIX_FMT_YUV422P10;
2897 return AV_PIX_FMT_YUV420P10;
2901 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2902 return AV_PIX_FMT_GBRP12;
2904 return AV_PIX_FMT_YUV444P12;
2905 } else if (CHROMA422)
2906 return AV_PIX_FMT_YUV422P12;
2908 return AV_PIX_FMT_YUV420P12;
2912 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2913 return AV_PIX_FMT_GBRP14;
2915 return AV_PIX_FMT_YUV444P14;
2916 } else if (CHROMA422)
2917 return AV_PIX_FMT_YUV422P14;
2919 return AV_PIX_FMT_YUV420P14;
2923 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2924 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2925 return AV_PIX_FMT_GBR24P;
2926 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
2927 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2929 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2930 : AV_PIX_FMT_YUV444P;
2931 } else if (CHROMA422) {
2932 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2933 : AV_PIX_FMT_YUV422P;
2936 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
2937 h->avctx->codec->pix_fmts :
2938 h->avctx->color_range == AVCOL_RANGE_JPEG ?
2939 hwaccel_pixfmt_list_h264_jpeg_420 :
2940 ff_hwaccel_pixfmt_list_420;
2942 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
2943 if (fmt[i] == h->avctx->pix_fmt)
2945 return h->avctx->get_format(h->avctx, fmt);
2949 av_log(h->avctx, AV_LOG_ERROR,
2950 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2951 return AVERROR_INVALIDDATA;
2955 static int h264_slice_header_init(H264Context *h, int reinit)
2957 int nb_slices = (HAVE_THREADS &&
2958 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
2959 h->avctx->thread_count : 1;
2962 if( FFALIGN(h->avctx->width , 16 ) == h->width
2963 && FFALIGN(h->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == h->height
2964 && !h->sps.crop_right && !h->sps.crop_bottom
2965 && (h->avctx->width != h->width || h->avctx->height && h->height)
2967 av_log(h->avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
2968 h->avctx->coded_width = h->width;
2969 h->avctx->coded_height = h->height;
2971 avcodec_set_dimensions(h->avctx, h->width, h->height);
2972 h->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2973 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);
2976 h->avctx->sample_aspect_ratio = h->sps.sar;
2977 av_assert0(h->avctx->sample_aspect_ratio.den);
2978 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
2979 &h->chroma_x_shift, &h->chroma_y_shift);
2981 if (h->sps.timing_info_present_flag) {
2982 int64_t den = h->sps.time_scale;
2983 if (h->x264_build < 44U)
2985 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
2986 h->sps.num_units_in_tick, den, 1 << 30);
2989 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
2994 h->prev_interlaced_frame = 1;
2996 init_scan_tables(h);
2997 if (ff_h264_alloc_tables(h) < 0) {
2998 av_log(h->avctx, AV_LOG_ERROR,
2999 "Could not allocate memory for h264\n");
3000 return AVERROR(ENOMEM);
3003 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3006 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3008 max_slices = MAX_THREADS;
3009 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3010 " reducing to %d\n", nb_slices, max_slices);
3011 nb_slices = max_slices;
3013 h->slice_context_count = nb_slices;
3015 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3016 if (context_init(h) < 0) {
3017 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3021 for (i = 1; i < h->slice_context_count; i++) {
3023 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3024 c->avctx = h->avctx;
3027 c->h264dsp = h->h264dsp;
3028 c->h264qpel = h->h264qpel;
3029 c->h264chroma = h->h264chroma;
3032 c->pixel_shift = h->pixel_shift;
3033 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3034 c->width = h->width;
3035 c->height = h->height;
3036 c->linesize = h->linesize;
3037 c->uvlinesize = h->uvlinesize;
3038 c->chroma_x_shift = h->chroma_x_shift;
3039 c->chroma_y_shift = h->chroma_y_shift;
3040 c->qscale = h->qscale;
3041 c->droppable = h->droppable;
3042 c->data_partitioning = h->data_partitioning;
3043 c->low_delay = h->low_delay;
3044 c->mb_width = h->mb_width;
3045 c->mb_height = h->mb_height;
3046 c->mb_stride = h->mb_stride;
3047 c->mb_num = h->mb_num;
3048 c->flags = h->flags;
3049 c->workaround_bugs = h->workaround_bugs;
3050 c->pict_type = h->pict_type;
3052 init_scan_tables(c);
3053 clone_tables(c, h, i);
3054 c->context_initialized = 1;
3057 for (i = 0; i < h->slice_context_count; i++)
3058 if (context_init(h->thread_context[i]) < 0) {
3059 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3064 h->context_initialized = 1;
3070 * Decode a slice header.
3071 * This will also call ff_MPV_common_init() and frame_start() as needed.
3073 * @param h h264context
3074 * @param h0 h264 master context (differs from 'h' when doing sliced based
3075 * parallel decoding)
3077 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3079 static int decode_slice_header(H264Context *h, H264Context *h0)
3081 unsigned int first_mb_in_slice;
3082 unsigned int pps_id;
3083 int num_ref_idx_active_override_flag, ret;
3084 unsigned int slice_type, tmp, i, j;
3085 int default_ref_list_done = 0;
3086 int last_pic_structure, last_pic_droppable;
3088 int needs_reinit = 0;
3090 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3091 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3093 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3095 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3096 if (h0->current_slice && FIELD_PICTURE) {
3100 h0->current_slice = 0;
3101 if (!h0->first_field) {
3102 if (h->cur_pic_ptr && !h->droppable &&
3103 h->cur_pic_ptr->owner2 == h) {
3104 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
3105 h->picture_structure == PICT_BOTTOM_FIELD);
3107 h->cur_pic_ptr = NULL;
3111 slice_type = get_ue_golomb_31(&h->gb);
3112 if (slice_type > 9) {
3113 av_log(h->avctx, AV_LOG_ERROR,
3114 "slice type too large (%d) at %d %d\n",
3115 slice_type, h->mb_x, h->mb_y);
3118 if (slice_type > 4) {
3120 h->slice_type_fixed = 1;
3122 h->slice_type_fixed = 0;
3124 slice_type = golomb_to_pict_type[slice_type];
3125 if (slice_type == AV_PICTURE_TYPE_I ||
3126 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3127 default_ref_list_done = 1;
3129 h->slice_type = slice_type;
3130 h->slice_type_nos = slice_type & 3;
3132 // to make a few old functions happy, it's wrong though
3133 h->pict_type = h->slice_type;
3135 pps_id = get_ue_golomb(&h->gb);
3136 if (pps_id >= MAX_PPS_COUNT) {
3137 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3140 if (!h0->pps_buffers[pps_id]) {
3141 av_log(h->avctx, AV_LOG_ERROR,
3142 "non-existing PPS %u referenced\n",
3146 h->pps = *h0->pps_buffers[pps_id];
3148 if (!h0->sps_buffers[h->pps.sps_id]) {
3149 av_log(h->avctx, AV_LOG_ERROR,
3150 "non-existing SPS %u referenced\n",
3155 if (h->pps.sps_id != h->current_sps_id ||
3156 h0->sps_buffers[h->pps.sps_id]->new) {
3157 h0->sps_buffers[h->pps.sps_id]->new = 0;
3159 h->current_sps_id = h->pps.sps_id;
3160 h->sps = *h0->sps_buffers[h->pps.sps_id];
3162 if (h->mb_width != h->sps.mb_width ||
3163 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3164 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3165 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3169 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3170 h->chroma_format_idc != h->sps.chroma_format_idc) {
3171 h->bit_depth_luma = h->sps.bit_depth_luma;
3172 h->chroma_format_idc = h->sps.chroma_format_idc;
3175 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3179 h->avctx->profile = ff_h264_get_profile(&h->sps);
3180 h->avctx->level = h->sps.level_idc;
3181 h->avctx->refs = h->sps.ref_frame_count;
3183 must_reinit = (h->context_initialized &&
3184 ( 16*h->sps.mb_width != h->avctx->coded_width
3185 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3186 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3187 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3188 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)));
3189 if (h0->avctx->pix_fmt != get_pixel_format(h0))
3192 h->mb_width = h->sps.mb_width;
3193 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3194 h->mb_num = h->mb_width * h->mb_height;
3195 h->mb_stride = h->mb_width + 1;
3197 h->b_stride = h->mb_width * 4;
3199 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3201 h->width = 16 * h->mb_width;
3202 h->height = 16 * h->mb_height;
3204 if (h->sps.video_signal_type_present_flag) {
3205 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3207 if (h->sps.colour_description_present_flag) {
3208 if (h->avctx->colorspace != h->sps.colorspace)
3210 h->avctx->color_primaries = h->sps.color_primaries;
3211 h->avctx->color_trc = h->sps.color_trc;
3212 h->avctx->colorspace = h->sps.colorspace;
3216 if (h->context_initialized &&
3222 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3223 "slice %d\n", h0->current_slice + 1);
3224 return AVERROR_INVALIDDATA;
3229 if ((ret = get_pixel_format(h)) < 0)
3231 h->avctx->pix_fmt = ret;
3233 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3234 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3236 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3237 av_log(h->avctx, AV_LOG_ERROR,
3238 "h264_slice_header_init() failed\n");
3242 if (!h->context_initialized) {
3244 av_log(h->avctx, AV_LOG_ERROR,
3245 "Cannot (re-)initialize context during parallel decoding.\n");
3249 if ((ret = get_pixel_format(h)) < 0)
3251 h->avctx->pix_fmt = ret;
3253 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3254 av_log(h->avctx, AV_LOG_ERROR,
3255 "h264_slice_header_init() failed\n");
3260 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3261 h->dequant_coeff_pps = pps_id;
3262 init_dequant_tables(h);
3265 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3268 h->mb_aff_frame = 0;
3269 last_pic_structure = h0->picture_structure;
3270 last_pic_droppable = h0->droppable;
3271 h->droppable = h->nal_ref_idc == 0;
3272 if (h->sps.frame_mbs_only_flag) {
3273 h->picture_structure = PICT_FRAME;
3275 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3276 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3279 if (get_bits1(&h->gb)) { // field_pic_flag
3280 h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
3282 h->picture_structure = PICT_FRAME;
3283 h->mb_aff_frame = h->sps.mb_aff;
3286 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3288 if (h0->current_slice != 0) {
3289 if (last_pic_structure != h->picture_structure ||
3290 last_pic_droppable != h->droppable) {
3291 av_log(h->avctx, AV_LOG_ERROR,
3292 "Changing field mode (%d -> %d) between slices is not allowed\n",
3293 last_pic_structure, h->picture_structure);
3294 h->picture_structure = last_pic_structure;
3295 h->droppable = last_pic_droppable;
3296 return AVERROR_INVALIDDATA;
3297 } else if (!h0->cur_pic_ptr) {
3298 av_log(h->avctx, AV_LOG_ERROR,
3299 "unset cur_pic_ptr on %d. slice\n",
3300 h0->current_slice + 1);
3301 return AVERROR_INVALIDDATA;
3304 /* Shorten frame num gaps so we don't have to allocate reference
3305 * frames just to throw them away */
3306 if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
3307 int unwrap_prev_frame_num = h->prev_frame_num;
3308 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3310 if (unwrap_prev_frame_num > h->frame_num)
3311 unwrap_prev_frame_num -= max_frame_num;
3313 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3314 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3315 if (unwrap_prev_frame_num < 0)
3316 unwrap_prev_frame_num += max_frame_num;
3318 h->prev_frame_num = unwrap_prev_frame_num;
3322 /* See if we have a decoded first field looking for a pair...
3323 * Here, we're using that to see if we should mark previously
3324 * decode frames as "finished".
3325 * We have to do that before the "dummy" in-between frame allocation,
3326 * since that can modify h->cur_pic_ptr. */
3327 if (h0->first_field) {
3328 assert(h0->cur_pic_ptr);
3329 assert(h0->cur_pic_ptr->f.data[0]);
3330 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3332 /* Mark old field/frame as completed */
3333 if (!last_pic_droppable && h0->cur_pic_ptr->owner2 == h0) {
3334 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3335 last_pic_structure == PICT_BOTTOM_FIELD);
3338 /* figure out if we have a complementary field pair */
3339 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3340 /* Previous field is unmatched. Don't display it, but let it
3341 * remain for reference if marked as such. */
3342 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3343 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3344 last_pic_structure == PICT_TOP_FIELD);
3347 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3348 /* This and previous field were reference, but had
3349 * different frame_nums. Consider this field first in
3350 * pair. Throw away previous field except for reference
3352 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3353 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3354 last_pic_structure == PICT_TOP_FIELD);
3357 /* Second field in complementary pair */
3358 if (!((last_pic_structure == PICT_TOP_FIELD &&
3359 h->picture_structure == PICT_BOTTOM_FIELD) ||
3360 (last_pic_structure == PICT_BOTTOM_FIELD &&
3361 h->picture_structure == PICT_TOP_FIELD))) {
3362 av_log(h->avctx, AV_LOG_ERROR,
3363 "Invalid field mode combination %d/%d\n",
3364 last_pic_structure, h->picture_structure);
3365 h->picture_structure = last_pic_structure;
3366 h->droppable = last_pic_droppable;
3367 return AVERROR_INVALIDDATA;
3368 } else if (last_pic_droppable != h->droppable) {
3369 av_log(h->avctx, AV_LOG_ERROR,
3370 "Cannot combine reference and non-reference fields in the same frame\n");
3371 av_log_ask_for_sample(h->avctx, NULL);
3372 h->picture_structure = last_pic_structure;
3373 h->droppable = last_pic_droppable;
3374 return AVERROR_PATCHWELCOME;
3377 /* Take ownership of this buffer. Note that if another thread owned
3378 * the first field of this buffer, we're not operating on that pointer,
3379 * so the original thread is still responsible for reporting progress
3380 * on that first field (or if that was us, we just did that above).
3381 * By taking ownership, we assign responsibility to ourselves to
3382 * report progress on the second field. */
3383 h0->cur_pic_ptr->owner2 = h0;
3388 while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field &&
3389 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3390 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3391 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3392 h->frame_num, h->prev_frame_num);
3393 if (!h->sps.gaps_in_frame_num_allowed_flag)
3394 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3395 h->last_pocs[i] = INT_MIN;
3396 if (ff_h264_frame_start(h) < 0)
3398 h->prev_frame_num++;
3399 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3400 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3401 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 0);
3402 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 1);
3403 if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
3404 h->avctx->err_recognition & AV_EF_EXPLODE)
3406 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3407 (h->avctx->err_recognition & AV_EF_EXPLODE))
3408 return AVERROR_INVALIDDATA;
3409 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3410 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3411 * about there being no actual duplicates.
3412 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3413 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3415 if (h->short_ref_count) {
3417 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3418 (const uint8_t **)prev->f.data, prev->f.linesize,
3419 h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
3420 h->short_ref[0]->poc = prev->poc + 2;
3422 h->short_ref[0]->frame_num = h->prev_frame_num;
3426 /* See if we have a decoded first field looking for a pair...
3427 * We're using that to see whether to continue decoding in that
3428 * frame, or to allocate a new one. */
3429 if (h0->first_field) {
3430 assert(h0->cur_pic_ptr);
3431 assert(h0->cur_pic_ptr->f.data[0]);
3432 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3434 /* figure out if we have a complementary field pair */
3435 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3436 /* Previous field is unmatched. Don't display it, but let it
3437 * remain for reference if marked as such. */
3438 h0->cur_pic_ptr = NULL;
3439 h0->first_field = FIELD_PICTURE;
3441 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3442 ff_thread_report_progress((AVFrame*)h0->cur_pic_ptr, INT_MAX,
3443 h0->picture_structure==PICT_BOTTOM_FIELD);
3444 /* This and the previous field had different frame_nums.
3445 * Consider this field first in pair. Throw away previous
3446 * one except for reference purposes. */
3447 h0->first_field = 1;
3448 h0->cur_pic_ptr = NULL;
3450 /* Second field in complementary pair */
3451 h0->first_field = 0;
3455 /* Frame or first field in a potentially complementary pair */
3456 h0->first_field = FIELD_PICTURE;
3459 if (!FIELD_PICTURE || h0->first_field) {
3460 if (ff_h264_frame_start(h) < 0) {
3461 h0->first_field = 0;
3465 release_unused_pictures(h, 0);
3468 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3471 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3473 av_assert1(h->mb_num == h->mb_width * h->mb_height);
3474 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= h->mb_num ||
3475 first_mb_in_slice >= h->mb_num) {
3476 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3479 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3480 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE;
3481 if (h->picture_structure == PICT_BOTTOM_FIELD)
3482 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3483 av_assert1(h->mb_y < h->mb_height);
3485 if (h->picture_structure == PICT_FRAME) {
3486 h->curr_pic_num = h->frame_num;
3487 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3489 h->curr_pic_num = 2 * h->frame_num + 1;
3490 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3493 if (h->nal_unit_type == NAL_IDR_SLICE)
3494 get_ue_golomb(&h->gb); /* idr_pic_id */
3496 if (h->sps.poc_type == 0) {
3497 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3499 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3500 h->delta_poc_bottom = get_se_golomb(&h->gb);
3503 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3504 h->delta_poc[0] = get_se_golomb(&h->gb);
3506 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3507 h->delta_poc[1] = get_se_golomb(&h->gb);
3512 if (h->pps.redundant_pic_cnt_present)
3513 h->redundant_pic_count = get_ue_golomb(&h->gb);
3515 // set defaults, might be overridden a few lines later
3516 h->ref_count[0] = h->pps.ref_count[0];
3517 h->ref_count[1] = h->pps.ref_count[1];
3519 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3521 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3523 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3524 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3525 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3527 if (num_ref_idx_active_override_flag) {
3528 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3529 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3530 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3532 // full range is spec-ok in this case, even for frames
3533 h->ref_count[1] = 1;
3536 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3537 av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
3538 h->ref_count[0] = h->ref_count[1] = 1;
3539 return AVERROR_INVALIDDATA;
3542 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3547 h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
3549 if (!default_ref_list_done)
3550 ff_h264_fill_default_ref_list(h);
3552 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
3553 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3554 h->ref_count[1] = h->ref_count[0] = 0;
3558 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3559 (h->pps.weighted_bipred_idc == 1 &&
3560 h->slice_type_nos == AV_PICTURE_TYPE_B))
3561 pred_weight_table(h);
3562 else if (h->pps.weighted_bipred_idc == 2 &&
3563 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3564 implicit_weight_table(h, -1);
3567 for (i = 0; i < 2; i++) {
3568 h->luma_weight_flag[i] = 0;
3569 h->chroma_weight_flag[i] = 0;
3573 // If frame-mt is enabled, only update mmco tables for the first slice
3574 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3575 // or h->mmco, which will cause ref list mix-ups and decoding errors
3576 // further down the line. This may break decoding if the first slice is
3577 // corrupt, thus we only do this if frame-mt is enabled.
3578 if (h->nal_ref_idc &&
3579 ff_h264_decode_ref_pic_marking(h0, &h->gb,
3580 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3581 h0->current_slice == 0) < 0 &&
3582 (h->avctx->err_recognition & AV_EF_EXPLODE))
3583 return AVERROR_INVALIDDATA;
3586 ff_h264_fill_mbaff_ref_list(h);
3588 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3589 implicit_weight_table(h, 0);
3590 implicit_weight_table(h, 1);
3594 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3595 ff_h264_direct_dist_scale_factor(h);
3596 ff_h264_direct_ref_list_init(h);
3598 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3599 tmp = get_ue_golomb_31(&h->gb);
3601 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3604 h->cabac_init_idc = tmp;
3607 h->last_qscale_diff = 0;
3608 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3609 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3610 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3614 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3615 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3616 // FIXME qscale / qp ... stuff
3617 if (h->slice_type == AV_PICTURE_TYPE_SP)
3618 get_bits1(&h->gb); /* sp_for_switch_flag */
3619 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3620 h->slice_type == AV_PICTURE_TYPE_SI)
3621 get_se_golomb(&h->gb); /* slice_qs_delta */
3623 h->deblocking_filter = 1;
3624 h->slice_alpha_c0_offset = 52;
3625 h->slice_beta_offset = 52;
3626 if (h->pps.deblocking_filter_parameters_present) {
3627 tmp = get_ue_golomb_31(&h->gb);
3629 av_log(h->avctx, AV_LOG_ERROR,
3630 "deblocking_filter_idc %u out of range\n", tmp);
3633 h->deblocking_filter = tmp;
3634 if (h->deblocking_filter < 2)
3635 h->deblocking_filter ^= 1; // 1<->0
3637 if (h->deblocking_filter) {
3638 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3639 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3640 if (h->slice_alpha_c0_offset > 104U ||
3641 h->slice_beta_offset > 104U) {
3642 av_log(h->avctx, AV_LOG_ERROR,
3643 "deblocking filter parameters %d %d out of range\n",
3644 h->slice_alpha_c0_offset, h->slice_beta_offset);
3650 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3651 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3652 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3653 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3654 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3655 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3656 h->nal_ref_idc == 0))
3657 h->deblocking_filter = 0;
3659 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3660 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3661 /* Cheat slightly for speed:
3662 * Do not bother to deblock across slices. */
3663 h->deblocking_filter = 2;
3665 h0->max_contexts = 1;
3666 if (!h0->single_decode_warning) {
3667 av_log(h->avctx, AV_LOG_INFO,
3668 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3669 h0->single_decode_warning = 1;
3672 av_log(h->avctx, AV_LOG_ERROR,
3673 "Deblocking switched inside frame.\n");
3678 h->qp_thresh = 15 + 52 -
3679 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3681 h->pps.chroma_qp_index_offset[0],
3682 h->pps.chroma_qp_index_offset[1]) +
3683 6 * (h->sps.bit_depth_luma - 8);
3685 h0->last_slice_type = slice_type;
3686 h->slice_num = ++h0->current_slice;
3689 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
3690 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
3691 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
3692 && h->slice_num >= MAX_SLICES) {
3693 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3694 av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
3697 for (j = 0; j < 2; j++) {
3699 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3700 for (i = 0; i < 16; i++) {
3702 if (h->ref_list[j][i].f.data[0]) {
3704 uint8_t *base = h->ref_list[j][i].f.base[0];
3705 for (k = 0; k < h->short_ref_count; k++)
3706 if (h->short_ref[k]->f.base[0] == base) {
3710 for (k = 0; k < h->long_ref_count; k++)
3711 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3712 id_list[i] = h->short_ref_count + k;
3720 for (i = 0; i < 16; i++)
3721 ref2frm[i + 2] = 4 * id_list[i] +
3722 (h->ref_list[j][i].f.reference & 3);
3724 ref2frm[18 + 1] = -1;
3725 for (i = 16; i < 48; i++)
3726 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3727 (h->ref_list[j][i].f.reference & 3);
3730 // FIXME: fix draw_edges + PAFF + frame threads
3731 h->emu_edge_width = (h->flags & CODEC_FLAG_EMU_EDGE ||
3732 (!h->sps.frame_mbs_only_flag &&
3733 h->avctx->active_thread_type))
3735 h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
3737 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
3738 av_log(h->avctx, AV_LOG_DEBUG,
3739 "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
3741 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3743 av_get_picture_type_char(h->slice_type),
3744 h->slice_type_fixed ? " fix" : "",
3745 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3746 pps_id, h->frame_num,
3747 h->cur_pic_ptr->field_poc[0],
3748 h->cur_pic_ptr->field_poc[1],
3749 h->ref_count[0], h->ref_count[1],
3751 h->deblocking_filter,
3752 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3754 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3755 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3761 int ff_h264_get_slice_type(const H264Context *h)
3763 switch (h->slice_type) {
3764 case AV_PICTURE_TYPE_P:
3766 case AV_PICTURE_TYPE_B:
3768 case AV_PICTURE_TYPE_I:
3770 case AV_PICTURE_TYPE_SP:
3772 case AV_PICTURE_TYPE_SI:
3779 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3780 int mb_type, int top_xy,
3781 int left_xy[LEFT_MBS],
3783 int left_type[LEFT_MBS],
3784 int mb_xy, int list)
3786 int b_stride = h->b_stride;
3787 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3788 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3789 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3790 if (USES_LIST(top_type, list)) {
3791 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3792 const int b8_xy = 4 * top_xy + 2;
3793 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3794 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.f.motion_val[list][b_xy + 0]);
3795 ref_cache[0 - 1 * 8] =
3796 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 0]];
3797 ref_cache[2 - 1 * 8] =
3798 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 1]];
3800 AV_ZERO128(mv_dst - 1 * 8);
3801 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3804 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3805 if (USES_LIST(left_type[LTOP], list)) {
3806 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3807 const int b8_xy = 4 * left_xy[LTOP] + 1;
3808 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3809 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.f.motion_val[list][b_xy + b_stride * 0]);
3810 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.f.motion_val[list][b_xy + b_stride * 1]);
3811 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.f.motion_val[list][b_xy + b_stride * 2]);
3812 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.f.motion_val[list][b_xy + b_stride * 3]);
3814 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 0]];
3815 ref_cache[-1 + 16] =
3816 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 1]];
3818 AV_ZERO32(mv_dst - 1 + 0);
3819 AV_ZERO32(mv_dst - 1 + 8);
3820 AV_ZERO32(mv_dst - 1 + 16);
3821 AV_ZERO32(mv_dst - 1 + 24);
3824 ref_cache[-1 + 16] =
3825 ref_cache[-1 + 24] = LIST_NOT_USED;
3830 if (!USES_LIST(mb_type, list)) {
3831 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3832 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3833 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3834 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3835 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3840 int8_t *ref = &h->cur_pic.f.ref_index[list][4 * mb_xy];
3841 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3842 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3843 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3844 AV_WN32A(&ref_cache[0 * 8], ref01);
3845 AV_WN32A(&ref_cache[1 * 8], ref01);
3846 AV_WN32A(&ref_cache[2 * 8], ref23);
3847 AV_WN32A(&ref_cache[3 * 8], ref23);
3851 int16_t(*mv_src)[2] = &h->cur_pic.f.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
3852 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3853 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3854 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3855 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3861 * @return non zero if the loop filter can be skipped
3863 static int fill_filter_caches(H264Context *h, int mb_type)
3865 const int mb_xy = h->mb_xy;
3866 int top_xy, left_xy[LEFT_MBS];
3867 int top_type, left_type[LEFT_MBS];
3871 top_xy = mb_xy - (h->mb_stride << MB_FIELD);
3873 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3874 * stuff, I can't imagine that these complex rules are worth it. */
3876 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3878 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.f.mb_type[mb_xy - 1]);
3879 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3881 if (left_mb_field_flag != curr_mb_field_flag)
3882 left_xy[LTOP] -= h->mb_stride;
3884 if (curr_mb_field_flag)
3885 top_xy += h->mb_stride &
3886 (((h->cur_pic.f.mb_type[top_xy] >> 7) & 1) - 1);
3887 if (left_mb_field_flag != curr_mb_field_flag)
3888 left_xy[LBOT] += h->mb_stride;
3892 h->top_mb_xy = top_xy;
3893 h->left_mb_xy[LTOP] = left_xy[LTOP];
3894 h->left_mb_xy[LBOT] = left_xy[LBOT];
3896 /* For sufficiently low qp, filtering wouldn't do anything.
3897 * This is a conservative estimate: could also check beta_offset
3898 * and more accurate chroma_qp. */
3899 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3900 int qp = h->cur_pic.f.qscale_table[mb_xy];
3901 if (qp <= qp_thresh &&
3902 (left_xy[LTOP] < 0 ||
3903 ((qp + h->cur_pic.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3905 ((qp + h->cur_pic.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3908 if ((left_xy[LTOP] < 0 ||
3909 ((qp + h->cur_pic.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3910 (top_xy < h->mb_stride ||
3911 ((qp + h->cur_pic.f.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
3916 top_type = h->cur_pic.f.mb_type[top_xy];
3917 left_type[LTOP] = h->cur_pic.f.mb_type[left_xy[LTOP]];
3918 left_type[LBOT] = h->cur_pic.f.mb_type[left_xy[LBOT]];
3919 if (h->deblocking_filter == 2) {
3920 if (h->slice_table[top_xy] != h->slice_num)
3922 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3923 left_type[LTOP] = left_type[LBOT] = 0;
3925 if (h->slice_table[top_xy] == 0xFFFF)
3927 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3928 left_type[LTOP] = left_type[LBOT] = 0;
3930 h->top_type = top_type;
3931 h->left_type[LTOP] = left_type[LTOP];
3932 h->left_type[LBOT] = left_type[LBOT];
3934 if (IS_INTRA(mb_type))
3937 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
3938 top_type, left_type, mb_xy, 0);
3939 if (h->list_count == 2)
3940 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
3941 top_type, left_type, mb_xy, 1);
3943 nnz = h->non_zero_count[mb_xy];
3944 nnz_cache = h->non_zero_count_cache;
3945 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3946 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3947 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3948 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3949 h->cbp = h->cbp_table[mb_xy];
3952 nnz = h->non_zero_count[top_xy];
3953 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3956 if (left_type[LTOP]) {
3957 nnz = h->non_zero_count[left_xy[LTOP]];
3958 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3959 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3960 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3961 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3964 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3965 * from what the loop filter needs */
3966 if (!CABAC && h->pps.transform_8x8_mode) {
3967 if (IS_8x8DCT(top_type)) {
3968 nnz_cache[4 + 8 * 0] =
3969 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3970 nnz_cache[6 + 8 * 0] =
3971 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3973 if (IS_8x8DCT(left_type[LTOP])) {
3974 nnz_cache[3 + 8 * 1] =
3975 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3977 if (IS_8x8DCT(left_type[LBOT])) {
3978 nnz_cache[3 + 8 * 3] =
3979 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3982 if (IS_8x8DCT(mb_type)) {
3983 nnz_cache[scan8[0]] =
3984 nnz_cache[scan8[1]] =
3985 nnz_cache[scan8[2]] =
3986 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3988 nnz_cache[scan8[0 + 4]] =
3989 nnz_cache[scan8[1 + 4]] =
3990 nnz_cache[scan8[2 + 4]] =
3991 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3993 nnz_cache[scan8[0 + 8]] =
3994 nnz_cache[scan8[1 + 8]] =
3995 nnz_cache[scan8[2 + 8]] =
3996 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3998 nnz_cache[scan8[0 + 12]] =
3999 nnz_cache[scan8[1 + 12]] =
4000 nnz_cache[scan8[2 + 12]] =
4001 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4008 static void loop_filter(H264Context *h, int start_x, int end_x)
4010 uint8_t *dest_y, *dest_cb, *dest_cr;
4011 int linesize, uvlinesize, mb_x, mb_y;
4012 const int end_mb_y = h->mb_y + FRAME_MBAFF;
4013 const int old_slice_type = h->slice_type;
4014 const int pixel_shift = h->pixel_shift;
4015 const int block_h = 16 >> h->chroma_y_shift;
4017 if (h->deblocking_filter) {
4018 for (mb_x = start_x; mb_x < end_x; mb_x++)
4019 for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
4021 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4022 h->slice_num = h->slice_table[mb_xy];
4023 mb_type = h->cur_pic.f.mb_type[mb_xy];
4024 h->list_count = h->list_counts[mb_xy];
4028 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4032 dest_y = h->cur_pic.f.data[0] +
4033 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4034 dest_cb = h->cur_pic.f.data[1] +
4035 (mb_x << pixel_shift) * (8 << CHROMA444) +
4036 mb_y * h->uvlinesize * block_h;
4037 dest_cr = h->cur_pic.f.data[2] +
4038 (mb_x << pixel_shift) * (8 << CHROMA444) +
4039 mb_y * h->uvlinesize * block_h;
4040 // FIXME simplify above
4043 linesize = h->mb_linesize = h->linesize * 2;
4044 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4045 if (mb_y & 1) { // FIXME move out of this function?
4046 dest_y -= h->linesize * 15;
4047 dest_cb -= h->uvlinesize * (block_h - 1);
4048 dest_cr -= h->uvlinesize * (block_h - 1);
4051 linesize = h->mb_linesize = h->linesize;
4052 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4054 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4056 if (fill_filter_caches(h, mb_type))
4058 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.f.qscale_table[mb_xy]);
4059 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.f.qscale_table[mb_xy]);
4062 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4063 linesize, uvlinesize);
4065 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4066 dest_cr, linesize, uvlinesize);
4070 h->slice_type = old_slice_type;
4072 h->mb_y = end_mb_y - FRAME_MBAFF;
4073 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4074 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4077 static void predict_field_decoding_flag(H264Context *h)
4079 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4080 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4081 h->cur_pic.f.mb_type[mb_xy - 1] :
4082 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4083 h->cur_pic.f.mb_type[mb_xy - h->mb_stride] : 0;
4084 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4088 * Draw edges and report progress for the last MB row.
4090 static void decode_finish_row(H264Context *h)
4092 int top = 16 * (h->mb_y >> FIELD_PICTURE);
4093 int pic_height = 16 * h->mb_height >> FIELD_PICTURE;
4094 int height = 16 << FRAME_MBAFF;
4095 int deblock_border = (16 + 4) << FRAME_MBAFF;
4097 if (h->deblocking_filter) {
4098 if ((top + height) >= pic_height)
4099 height += deblock_border;
4100 top -= deblock_border;
4103 if (top >= pic_height || (top + height) < h->emu_edge_height)
4106 height = FFMIN(height, pic_height - top);
4107 if (top < h->emu_edge_height) {
4108 height = top + height;
4112 ff_h264_draw_horiz_band(h, top, height);
4117 ff_thread_report_progress(&h->cur_pic_ptr->f, top + height - 1,
4118 h->picture_structure == PICT_BOTTOM_FIELD);
4121 static void er_add_slice(H264Context *h, int startx, int starty,
4122 int endx, int endy, int status)
4124 ERContext *er = &h->er;
4126 er->ref_count = h->ref_count[0];
4127 ff_er_add_slice(er, startx, starty, endx, endy, status);
4130 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4132 H264Context *h = *(void **)arg;
4133 int lf_x_start = h->mb_x;
4135 h->mb_skip_run = -1;
4137 av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4139 h->is_complex = FRAME_MBAFF || h->picture_structure != PICT_FRAME ||
4140 avctx->codec_id != AV_CODEC_ID_H264 ||
4141 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4145 align_get_bits(&h->gb);
4148 ff_init_cabac_decoder(&h->cabac,
4149 h->gb.buffer + get_bits_count(&h->gb) / 8,
4150 (get_bits_left(&h->gb) + 7) / 8);
4152 ff_h264_init_cabac_states(h);
4156 int ret = ff_h264_decode_mb_cabac(h);
4158 // STOP_TIMER("decode_mb_cabac")
4161 ff_h264_hl_decode_mb(h);
4163 // FIXME optimal? or let mb_decode decode 16x32 ?
4164 if (ret >= 0 && FRAME_MBAFF) {
4167 ret = ff_h264_decode_mb_cabac(h);
4170 ff_h264_hl_decode_mb(h);
4173 eos = get_cabac_terminate(&h->cabac);
4175 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4176 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4177 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4178 h->mb_y, ER_MB_END);
4179 if (h->mb_x >= lf_x_start)
4180 loop_filter(h, lf_x_start, h->mb_x + 1);
4183 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4184 av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4185 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4186 av_log(h->avctx, AV_LOG_ERROR,
4187 "error while decoding MB %d %d, bytestream (%td)\n",
4189 h->cabac.bytestream_end - h->cabac.bytestream);
4190 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4191 h->mb_y, ER_MB_ERROR);
4195 if (++h->mb_x >= h->mb_width) {
4196 loop_filter(h, lf_x_start, h->mb_x);
4197 h->mb_x = lf_x_start = 0;
4198 decode_finish_row(h);
4200 if (FIELD_OR_MBAFF_PICTURE) {
4202 if (FRAME_MBAFF && h->mb_y < h->mb_height)
4203 predict_field_decoding_flag(h);
4207 if (eos || h->mb_y >= h->mb_height) {
4208 tprintf(h->avctx, "slice end %d %d\n",
4209 get_bits_count(&h->gb), h->gb.size_in_bits);
4210 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4211 h->mb_y, ER_MB_END);
4212 if (h->mb_x > lf_x_start)
4213 loop_filter(h, lf_x_start, h->mb_x);
4219 int ret = ff_h264_decode_mb_cavlc(h);
4222 ff_h264_hl_decode_mb(h);
4224 // FIXME optimal? or let mb_decode decode 16x32 ?
4225 if (ret >= 0 && FRAME_MBAFF) {
4227 ret = ff_h264_decode_mb_cavlc(h);
4230 ff_h264_hl_decode_mb(h);
4235 av_log(h->avctx, AV_LOG_ERROR,
4236 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4237 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4238 h->mb_y, ER_MB_ERROR);
4242 if (++h->mb_x >= h->mb_width) {
4243 loop_filter(h, lf_x_start, h->mb_x);
4244 h->mb_x = lf_x_start = 0;
4245 decode_finish_row(h);
4247 if (FIELD_OR_MBAFF_PICTURE) {
4249 if (FRAME_MBAFF && h->mb_y < h->mb_height)
4250 predict_field_decoding_flag(h);
4252 if (h->mb_y >= h->mb_height) {
4253 tprintf(h->avctx, "slice end %d %d\n",
4254 get_bits_count(&h->gb), h->gb.size_in_bits);
4256 if ( get_bits_left(&h->gb) == 0
4257 || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4258 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4259 h->mb_x - 1, h->mb_y,
4264 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4273 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4274 tprintf(h->avctx, "slice end %d %d\n",
4275 get_bits_count(&h->gb), h->gb.size_in_bits);
4276 if (get_bits_left(&h->gb) == 0) {
4277 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4278 h->mb_x - 1, h->mb_y,
4280 if (h->mb_x > lf_x_start)
4281 loop_filter(h, lf_x_start, h->mb_x);
4285 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4286 h->mb_y, ER_MB_ERROR);
4296 * Call decode_slice() for each context.
4298 * @param h h264 master context
4299 * @param context_count number of contexts to execute
4301 static int execute_decode_slices(H264Context *h, int context_count)
4303 AVCodecContext *const avctx = h->avctx;
4307 if (h->avctx->hwaccel ||
4308 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4310 if (context_count == 1) {
4311 return decode_slice(avctx, &h);
4313 av_assert0(context_count > 0);
4314 for (i = 1; i < context_count; i++) {
4315 hx = h->thread_context[i];
4316 hx->er.error_count = 0;
4317 hx->x264_build = h->x264_build;
4320 avctx->execute(avctx, decode_slice, h->thread_context,
4321 NULL, context_count, sizeof(void *));
4323 /* pull back stuff from slices to master context */
4324 hx = h->thread_context[context_count - 1];
4327 h->droppable = hx->droppable;
4328 h->picture_structure = hx->picture_structure;
4329 for (i = 1; i < context_count; i++)
4330 h->er.error_count += h->thread_context[i]->er.error_count;
4336 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4337 int parse_extradata)
4339 AVCodecContext *const avctx = h->avctx;
4340 H264Context *hx; ///< thread context
4344 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4345 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4348 int first_slice = 0;
4350 h->nal_unit_type= 0;
4352 if(!h->slice_context_count)
4353 h->slice_context_count= 1;
4354 h->max_contexts = h->slice_context_count;
4355 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4356 h->current_slice = 0;
4357 if (!h->first_field)
4358 h->cur_pic_ptr = NULL;
4359 ff_h264_reset_sei(h);
4362 if (h->nal_length_size == 4) {
4363 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4365 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4369 for (; pass <= 1; pass++) {
4372 next_avc = h->is_avc ? 0 : buf_size;
4382 if (buf_index >= next_avc) {
4383 if (buf_index >= buf_size - h->nal_length_size)
4386 for (i = 0; i < h->nal_length_size; i++)
4387 nalsize = (nalsize << 8) | buf[buf_index++];
4388 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4389 av_log(h->avctx, AV_LOG_ERROR,
4390 "AVC: nal size %d\n", nalsize);
4393 next_avc = buf_index + nalsize;
4395 // start code prefix search
4396 for (; buf_index + 3 < next_avc; buf_index++)
4397 // This should always succeed in the first iteration.
4398 if (buf[buf_index] == 0 &&
4399 buf[buf_index + 1] == 0 &&
4400 buf[buf_index + 2] == 1)
4403 if (buf_index + 3 >= buf_size) {
4404 buf_index = buf_size;
4409 if (buf_index >= next_avc)
4413 hx = h->thread_context[context_count];
4415 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4416 &consumed, next_avc - buf_index);
4417 if (ptr == NULL || dst_length < 0) {
4421 i = buf_index + consumed;
4422 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4423 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4424 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4425 h->workaround_bugs |= FF_BUG_TRUNCATED;
4427 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4428 while(dst_length > 0 && ptr[dst_length - 1] == 0)
4430 bit_length = !dst_length ? 0
4432 decode_rbsp_trailing(h, ptr + dst_length - 1));
4434 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4435 av_log(h->avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d pass %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
4437 if (h->is_avc && (nalsize != consumed) && nalsize)
4438 av_log(h->avctx, AV_LOG_DEBUG,
4439 "AVC: Consumed only %d bytes instead of %d\n",
4442 buf_index += consumed;
4446 /* packets can sometimes contain multiple PPS/SPS,
4447 * e.g. two PAFF field pictures in one packet, or a demuxer
4448 * which splits NALs strangely if so, when frame threading we
4449 * can't start the next thread until we've read all of them */
4450 switch (hx->nal_unit_type) {
4453 nals_needed = nal_index;
4458 init_get_bits(&hx->gb, ptr, bit_length);
4459 if (!get_ue_golomb(&hx->gb) || !first_slice)
4460 nals_needed = nal_index;
4462 first_slice = hx->nal_unit_type;
4468 switch (hx->nal_unit_type) {
4472 first_slice = hx->nal_unit_type;
4475 // FIXME do not discard SEI id
4476 if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
4480 /* Ignore per frame NAL unit type during extradata
4481 * parsing. Decoding slices is not possible in codec init
4483 if (parse_extradata) {
4484 switch (hx->nal_unit_type) {
4490 case NAL_AUXILIARY_SLICE:
4491 av_log(h->avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header/extradata\n", hx->nal_unit_type);
4492 hx->nal_unit_type = NAL_FF_IGNORE;
4498 switch (hx->nal_unit_type) {
4500 if (first_slice != NAL_IDR_SLICE) {
4501 av_log(h->avctx, AV_LOG_ERROR,
4502 "Invalid mix of idr and non-idr slices\n");
4507 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4510 init_get_bits(&hx->gb, ptr, bit_length);
4512 hx->inter_gb_ptr = &hx->gb;
4513 hx->data_partitioning = 0;
4515 if ((err = decode_slice_header(hx, h)))
4518 if (h->sei_recovery_frame_cnt >= 0 && (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I))
4519 h->valid_recovery_point = 1;
4521 if ( h->sei_recovery_frame_cnt >= 0
4522 && ( h->recovery_frame<0
4523 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
4524 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
4525 (1 << h->sps.log2_max_frame_num);
4527 if (!h->valid_recovery_point)
4528 h->recovery_frame = h->frame_num;
4531 h->cur_pic_ptr->f.key_frame |=
4532 (hx->nal_unit_type == NAL_IDR_SLICE);
4534 if (h->recovery_frame == h->frame_num) {
4535 h->cur_pic_ptr->sync |= 1;
4536 h->recovery_frame = -1;
4539 h->sync |= !!h->cur_pic_ptr->f.key_frame;
4540 h->sync |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
4541 h->cur_pic_ptr->sync |= h->sync;
4543 if (h->current_slice == 1) {
4544 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4545 decode_postinit(h, nal_index >= nals_needed);
4547 if (h->avctx->hwaccel &&
4548 h->avctx->hwaccel->start_frame(h->avctx, NULL, 0) < 0)
4550 if (CONFIG_H264_VDPAU_DECODER &&
4551 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4552 ff_vdpau_h264_picture_start(h);
4555 if (hx->redundant_pic_count == 0 &&
4556 (avctx->skip_frame < AVDISCARD_NONREF ||
4558 (avctx->skip_frame < AVDISCARD_BIDIR ||
4559 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4560 (avctx->skip_frame < AVDISCARD_NONKEY ||
4561 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4562 avctx->skip_frame < AVDISCARD_ALL) {
4563 if (avctx->hwaccel) {
4564 if (avctx->hwaccel->decode_slice(avctx,
4565 &buf[buf_index - consumed],
4568 } else if (CONFIG_H264_VDPAU_DECODER &&
4569 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4570 static const uint8_t start_code[] = {
4572 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], start_code,
4573 sizeof(start_code));
4574 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], &buf[buf_index - consumed],
4581 init_get_bits(&hx->gb, ptr, bit_length);
4583 hx->inter_gb_ptr = NULL;
4585 if ((err = decode_slice_header(hx, h)) < 0)
4588 hx->data_partitioning = 1;
4591 init_get_bits(&hx->intra_gb, ptr, bit_length);
4592 hx->intra_gb_ptr = &hx->intra_gb;
4595 init_get_bits(&hx->inter_gb, ptr, bit_length);
4596 hx->inter_gb_ptr = &hx->inter_gb;
4598 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
4601 if (hx->redundant_pic_count == 0 &&
4603 hx->data_partitioning &&
4604 h->cur_pic_ptr && h->context_initialized &&
4605 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4606 (avctx->skip_frame < AVDISCARD_BIDIR ||
4607 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4608 (avctx->skip_frame < AVDISCARD_NONKEY ||
4609 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4610 avctx->skip_frame < AVDISCARD_ALL)
4614 init_get_bits(&h->gb, ptr, bit_length);
4615 ff_h264_decode_sei(h);
4618 init_get_bits(&h->gb, ptr, bit_length);
4619 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
4620 av_log(h->avctx, AV_LOG_DEBUG,
4621 "SPS decoding failure, trying again with the complete NAL\n");
4623 av_assert0(next_avc - buf_index + consumed == nalsize);
4624 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
4626 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
4627 8*(next_avc - buf_index + consumed - 1));
4628 ff_h264_decode_seq_parameter_set(h);
4633 init_get_bits(&h->gb, ptr, bit_length);
4634 ff_h264_decode_picture_parameter_set(h, bit_length);
4637 case NAL_END_SEQUENCE:
4638 case NAL_END_STREAM:
4639 case NAL_FILLER_DATA:
4641 case NAL_AUXILIARY_SLICE:
4646 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4647 hx->nal_unit_type, bit_length);
4650 if (context_count == h->max_contexts) {
4651 execute_decode_slices(h, context_count);
4656 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4657 else if (err == 1) {
4658 /* Slice could not be decoded in parallel mode, copy down
4659 * NAL unit stuff to context 0 and restart. Note that
4660 * rbsp_buffer is not transferred, but since we no longer
4661 * run in parallel mode this should not be an issue. */
4662 h->nal_unit_type = hx->nal_unit_type;
4663 h->nal_ref_idc = hx->nal_ref_idc;
4670 execute_decode_slices(h, context_count);
4674 if (h->cur_pic_ptr && h->cur_pic_ptr->owner2 == h &&
4676 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
4677 h->picture_structure == PICT_BOTTOM_FIELD);
4684 * Return the number of bytes consumed for building the current frame.
4686 static int get_consumed_bytes(int pos, int buf_size)
4689 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4690 if (pos + 10 > buf_size)
4691 pos = buf_size; // oops ;)
4696 static int decode_frame(AVCodecContext *avctx, void *data,
4697 int *got_frame, AVPacket *avpkt)
4699 const uint8_t *buf = avpkt->data;
4700 int buf_size = avpkt->size;
4701 H264Context *h = avctx->priv_data;
4702 AVFrame *pict = data;
4707 h->flags = avctx->flags;
4709 /* end of stream, output what is still in the buffers */
4710 if (buf_size == 0) {
4713 h->cur_pic_ptr = NULL;
4716 // FIXME factorize this with the output code below
4717 out = h->delayed_pic[0];
4720 h->delayed_pic[i] &&
4721 !h->delayed_pic[i]->f.key_frame &&
4722 !h->delayed_pic[i]->mmco_reset;
4724 if (h->delayed_pic[i]->poc < out->poc) {
4725 out = h->delayed_pic[i];
4729 for (i = out_idx; h->delayed_pic[i]; i++)
4730 h->delayed_pic[i] = h->delayed_pic[i + 1];
4733 out->f.reference &= ~DELAYED_PIC_REF;
4740 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
4741 int cnt= buf[5]&0x1f;
4742 const uint8_t *p= buf+6;
4744 int nalsize= AV_RB16(p) + 2;
4745 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
4753 int nalsize= AV_RB16(p) + 2;
4754 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
4759 return ff_h264_decode_extradata(h, buf, buf_size);
4763 buf_index = decode_nal_units(h, buf, buf_size, 0);
4767 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4768 av_assert0(buf_index <= buf_size);
4772 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
4773 if (avctx->skip_frame >= AVDISCARD_NONREF ||
4774 buf_size >= 4 && !memcmp("Q264", buf, 4))
4776 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4780 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
4781 (h->mb_y >= h->mb_height && h->mb_height)) {
4782 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
4783 decode_postinit(h, 1);
4787 /* Wait for second field. */
4789 if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
4791 *pict = h->next_output_pic->f;
4795 assert(pict->data[0] || !*got_frame);
4797 return get_consumed_bytes(buf_index, buf_size);
4800 av_cold void ff_h264_free_context(H264Context *h)
4804 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4806 for (i = 0; i < MAX_SPS_COUNT; i++)
4807 av_freep(h->sps_buffers + i);
4809 for (i = 0; i < MAX_PPS_COUNT; i++)
4810 av_freep(h->pps_buffers + i);
4813 static av_cold int h264_decode_end(AVCodecContext *avctx)
4815 H264Context *h = avctx->priv_data;
4818 ff_h264_remove_all_refs(h);
4819 ff_h264_free_context(h);
4821 if (h->DPB && !h->avctx->internal->is_copy) {
4822 for (i = 0; i < h->picture_count; i++) {
4823 free_picture(h, &h->DPB[i]);
4831 static const AVProfile profiles[] = {
4832 { FF_PROFILE_H264_BASELINE, "Baseline" },
4833 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4834 { FF_PROFILE_H264_MAIN, "Main" },
4835 { FF_PROFILE_H264_EXTENDED, "Extended" },
4836 { FF_PROFILE_H264_HIGH, "High" },
4837 { FF_PROFILE_H264_HIGH_10, "High 10" },
4838 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4839 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4840 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4841 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4842 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4843 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4844 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4845 { FF_PROFILE_UNKNOWN },
4848 static const AVOption h264_options[] = {
4849 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
4850 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
4854 static const AVClass h264_class = {
4855 .class_name = "H264 Decoder",
4856 .item_name = av_default_item_name,
4857 .option = h264_options,
4858 .version = LIBAVUTIL_VERSION_INT,
4861 static const AVClass h264_vdpau_class = {
4862 .class_name = "H264 VDPAU Decoder",
4863 .item_name = av_default_item_name,
4864 .option = h264_options,
4865 .version = LIBAVUTIL_VERSION_INT,
4868 AVCodec ff_h264_decoder = {
4870 .type = AVMEDIA_TYPE_VIDEO,
4871 .id = AV_CODEC_ID_H264,
4872 .priv_data_size = sizeof(H264Context),
4873 .init = ff_h264_decode_init,
4874 .close = h264_decode_end,
4875 .decode = decode_frame,
4876 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4877 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4878 CODEC_CAP_FRAME_THREADS,
4880 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4881 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4882 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4883 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4884 .priv_class = &h264_class,
4887 #if CONFIG_H264_VDPAU_DECODER
4888 AVCodec ff_h264_vdpau_decoder = {
4889 .name = "h264_vdpau",
4890 .type = AVMEDIA_TYPE_VIDEO,
4891 .id = AV_CODEC_ID_H264,
4892 .priv_data_size = sizeof(H264Context),
4893 .init = ff_h264_decode_init,
4894 .close = h264_decode_end,
4895 .decode = decode_frame,
4896 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4898 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4899 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
4901 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4902 .priv_class = &h264_vdpau_class,