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_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 static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
89 #if CONFIG_H264_DXVA2_HWACCEL
92 #if CONFIG_H264_VAAPI_HWACCEL
95 #if CONFIG_H264_VDA_HWACCEL
98 #if CONFIG_H264_VDPAU_HWACCEL
105 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
107 H264Context *h = avctx->priv_data;
108 return h ? h->sps.num_reorder_frames : 0;
111 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
113 int mb_x, int mb_y, int mb_intra, int mb_skipped)
115 H264Context *h = opaque;
119 h->mb_xy = mb_x + mb_y * h->mb_stride;
120 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
121 av_assert1(ref >= 0);
122 /* FIXME: It is possible albeit uncommon that slice references
123 * differ between slices. We take the easy approach and ignore
124 * it for now. If this turns out to have any relevance in
125 * practice then correct remapping should be added. */
126 if (ref >= h->ref_count[0])
128 if (!h->ref_list[0][ref].f.data[0]) {
129 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
132 if ((h->ref_list[0][ref].f.reference&3) != 3) {
133 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
136 fill_rectangle(&h->cur_pic.f.ref_index[0][4 * h->mb_xy],
138 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
139 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
140 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
142 h->mb_field_decoding_flag = 0;
143 ff_h264_hl_decode_mb(h);
146 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
148 ff_draw_horiz_band(h->avctx, NULL, &h->cur_pic,
149 h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL,
150 y, height, h->picture_structure, h->first_field, 0,
151 h->low_delay, h->mb_height * 16, h->mb_width * 16);
154 static void free_frame_buffer(H264Context *h, Picture *pic)
156 pic->period_since_free = 0;
157 ff_thread_release_buffer(h->avctx, &pic->f);
158 av_freep(&pic->f.hwaccel_picture_private);
161 static void free_picture(H264Context *h, Picture *pic)
166 free_frame_buffer(h, pic);
168 av_freep(&pic->qscale_table_base);
169 pic->f.qscale_table = NULL;
170 av_freep(&pic->mb_type_base);
171 pic->f.mb_type = NULL;
172 for (i = 0; i < 2; i++) {
173 av_freep(&pic->motion_val_base[i]);
174 av_freep(&pic->f.ref_index[i]);
175 pic->f.motion_val[i] = NULL;
179 static void release_unused_pictures(H264Context *h, int remove_current)
183 /* release non reference frames */
184 for (i = 0; i < h->picture_count; i++) {
185 if (h->DPB[i].f.data[0] && !h->DPB[i].f.reference &&
186 (!h->DPB[i].owner2 || h->DPB[i].owner2 == h) &&
187 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
188 free_frame_buffer(h, &h->DPB[i]);
193 static int alloc_scratch_buffers(H264Context *h, int linesize)
195 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
197 if (h->bipred_scratchpad)
200 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
201 // edge emu needs blocksize + filter length - 1
202 // (= 21x21 for h264)
203 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
204 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
206 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
207 av_freep(&h->bipred_scratchpad);
208 av_freep(&h->edge_emu_buffer);
209 av_freep(&h->me.scratchpad);
210 return AVERROR(ENOMEM);
213 h->me.temp = h->me.scratchpad;
218 static int alloc_picture(H264Context *h, Picture *pic)
220 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
221 const int mb_array_size = h->mb_stride * h->mb_height;
222 const int b4_stride = h->mb_width * 4 + 1;
223 const int b4_array_size = b4_stride * h->mb_height * 4;
226 av_assert0(!pic->f.data[0]);
228 if (h->avctx->hwaccel) {
229 const AVHWAccel *hwaccel = h->avctx->hwaccel;
230 av_assert0(!pic->f.hwaccel_picture_private);
231 if (hwaccel->priv_data_size) {
232 pic->f.hwaccel_picture_private = av_mallocz(hwaccel->priv_data_size);
233 if (!pic->f.hwaccel_picture_private)
234 return AVERROR(ENOMEM);
237 ret = ff_thread_get_buffer(h->avctx, &pic->f);
241 h->linesize = pic->f.linesize[0];
242 h->uvlinesize = pic->f.linesize[1];
244 if (pic->f.qscale_table == NULL) {
245 FF_ALLOCZ_OR_GOTO(h->avctx, pic->qscale_table_base,
246 (big_mb_num + h->mb_stride) * sizeof(uint8_t),
248 FF_ALLOCZ_OR_GOTO(h->avctx, pic->mb_type_base,
249 (big_mb_num + h->mb_stride) * sizeof(uint32_t),
251 pic->f.mb_type = pic->mb_type_base + 2 * h->mb_stride + 1;
252 pic->f.qscale_table = pic->qscale_table_base + 2 * h->mb_stride + 1;
254 for (i = 0; i < 2; i++) {
255 FF_ALLOCZ_OR_GOTO(h->avctx, pic->motion_val_base[i],
256 2 * (b4_array_size + 4) * sizeof(int16_t),
258 pic->f.motion_val[i] = pic->motion_val_base[i] + 4;
259 FF_ALLOCZ_OR_GOTO(h->avctx, pic->f.ref_index[i],
260 4 * mb_array_size * sizeof(uint8_t), fail)
262 pic->f.motion_subsample_log2 = 2;
264 pic->f.qstride = h->mb_stride;
271 free_frame_buffer(h, pic);
272 return (ret < 0) ? ret : AVERROR(ENOMEM);
275 static inline int pic_is_unused(H264Context *h, Picture *pic)
277 if ( (h->avctx->active_thread_type & FF_THREAD_FRAME)
278 && pic->f.qscale_table //check if the frame has anything allocated
279 && pic->period_since_free < h->avctx->thread_count)
281 if (pic->f.data[0] == NULL)
283 if (pic->needs_realloc && !(pic->f.reference & DELAYED_PIC_REF))
284 if (!pic->owner2 || pic->owner2 == h)
289 static int find_unused_picture(H264Context *h)
293 for (i = h->picture_range_start; i < h->picture_range_end; i++) {
294 if (pic_is_unused(h, &h->DPB[i]))
297 if (i == h->picture_range_end)
298 return AVERROR_INVALIDDATA;
300 if (h->DPB[i].needs_realloc) {
301 h->DPB[i].needs_realloc = 0;
302 free_picture(h, &h->DPB[i]);
303 avcodec_get_frame_defaults(&h->DPB[i].f);
310 * Check if the top & left blocks are available if needed and
311 * change the dc mode so it only uses the available blocks.
313 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
315 static const int8_t top[12] = {
316 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
318 static const int8_t left[12] = {
319 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
323 if (!(h->top_samples_available & 0x8000)) {
324 for (i = 0; i < 4; i++) {
325 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
327 av_log(h->avctx, AV_LOG_ERROR,
328 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
329 status, h->mb_x, h->mb_y);
332 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
337 if ((h->left_samples_available & 0x8888) != 0x8888) {
338 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
339 for (i = 0; i < 4; i++)
340 if (!(h->left_samples_available & mask[i])) {
341 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
343 av_log(h->avctx, AV_LOG_ERROR,
344 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
345 status, h->mb_x, h->mb_y);
348 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
354 } // FIXME cleanup like ff_h264_check_intra_pred_mode
357 * Check if the top & left blocks are available if needed and
358 * change the dc mode so it only uses the available blocks.
360 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
362 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
363 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
366 av_log(h->avctx, AV_LOG_ERROR,
367 "out of range intra chroma pred mode at %d %d\n",
372 if (!(h->top_samples_available & 0x8000)) {
375 av_log(h->avctx, AV_LOG_ERROR,
376 "top block unavailable for requested intra mode at %d %d\n",
382 if ((h->left_samples_available & 0x8080) != 0x8080) {
384 if (is_chroma && (h->left_samples_available & 0x8080)) {
385 // mad cow disease mode, aka MBAFF + constrained_intra_pred
386 mode = ALZHEIMER_DC_L0T_PRED8x8 +
387 (!(h->left_samples_available & 0x8000)) +
388 2 * (mode == DC_128_PRED8x8);
391 av_log(h->avctx, AV_LOG_ERROR,
392 "left block unavailable for requested intra mode at %d %d\n",
401 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
402 int *dst_length, int *consumed, int length)
408 // src[0]&0x80; // forbidden bit
409 h->nal_ref_idc = src[0] >> 5;
410 h->nal_unit_type = src[0] & 0x1F;
415 #define STARTCODE_TEST \
416 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
417 if (src[i + 2] != 3) { \
418 /* startcode, so we must be past the end */ \
423 #if HAVE_FAST_UNALIGNED
424 #define FIND_FIRST_ZERO \
425 if (i > 0 && !src[i]) \
430 for (i = 0; i + 1 < length; i += 9) {
431 if (!((~AV_RN64A(src + i) &
432 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
433 0x8000800080008080ULL))
440 for (i = 0; i + 1 < length; i += 5) {
441 if (!((~AV_RN32A(src + i) &
442 (AV_RN32A(src + i) - 0x01000101U)) &
451 for (i = 0; i + 1 < length; i += 2) {
454 if (i > 0 && src[i - 1] == 0)
460 // use second escape buffer for inter data
461 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
463 si = h->rbsp_buffer_size[bufidx];
464 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
465 dst = h->rbsp_buffer[bufidx];
470 if(i>=length-1){ //no escaped 0
472 *consumed= length+1; //+1 for the header
473 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
476 memcpy(dst, src, length);
483 while (si + 2 < length) {
484 // remove escapes (very rare 1:2^22)
485 if (src[si + 2] > 3) {
486 dst[di++] = src[si++];
487 dst[di++] = src[si++];
488 } else if (src[si] == 0 && src[si + 1] == 0) {
489 if (src[si + 2] == 3) { // escape
494 } else // next start code
498 dst[di++] = src[si++];
501 dst[di++] = src[si++];
504 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
507 *consumed = si + 1; // +1 for the header
508 /* FIXME store exact number of bits in the getbitcontext
509 * (it is needed for decoding) */
514 * Identify the exact end of the bitstream
515 * @return the length of the trailing, or 0 if damaged
517 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
522 tprintf(h->avctx, "rbsp trailing %X\n", v);
524 for (r = 1; r < 9; r++) {
532 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
533 int height, int y_offset, int list)
535 int raw_my = h->mv_cache[list][scan8[n]][1];
536 int filter_height_down = (raw_my & 3) ? 3 : 0;
537 int full_my = (raw_my >> 2) + y_offset;
538 int bottom = full_my + filter_height_down + height;
540 av_assert2(height >= 0);
542 return FFMAX(0, bottom);
545 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
546 int height, int y_offset, int list0,
547 int list1, int *nrefs)
551 y_offset += 16 * (h->mb_y >> MB_FIELD);
554 int ref_n = h->ref_cache[0][scan8[n]];
555 Picture *ref = &h->ref_list[0][ref_n];
557 // Error resilience puts the current picture in the ref list.
558 // Don't try to wait on these as it will cause a deadlock.
559 // Fields can wait on each other, though.
560 if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
561 (ref->f.reference & 3) != h->picture_structure) {
562 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
563 if (refs[0][ref_n] < 0)
565 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
570 int ref_n = h->ref_cache[1][scan8[n]];
571 Picture *ref = &h->ref_list[1][ref_n];
573 if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
574 (ref->f.reference & 3) != h->picture_structure) {
575 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
576 if (refs[1][ref_n] < 0)
578 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
584 * Wait until all reference frames are available for MC operations.
586 * @param h the H264 context
588 static void await_references(H264Context *h)
590 const int mb_xy = h->mb_xy;
591 const int mb_type = h->cur_pic.f.mb_type[mb_xy];
593 int nrefs[2] = { 0 };
596 memset(refs, -1, sizeof(refs));
598 if (IS_16X16(mb_type)) {
599 get_lowest_part_y(h, refs, 0, 16, 0,
600 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
601 } else if (IS_16X8(mb_type)) {
602 get_lowest_part_y(h, refs, 0, 8, 0,
603 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
604 get_lowest_part_y(h, refs, 8, 8, 8,
605 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
606 } else if (IS_8X16(mb_type)) {
607 get_lowest_part_y(h, refs, 0, 16, 0,
608 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
609 get_lowest_part_y(h, refs, 4, 16, 0,
610 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
614 av_assert2(IS_8X8(mb_type));
616 for (i = 0; i < 4; i++) {
617 const int sub_mb_type = h->sub_mb_type[i];
619 int y_offset = (i & 2) << 2;
621 if (IS_SUB_8X8(sub_mb_type)) {
622 get_lowest_part_y(h, refs, n, 8, y_offset,
623 IS_DIR(sub_mb_type, 0, 0),
624 IS_DIR(sub_mb_type, 0, 1),
626 } else if (IS_SUB_8X4(sub_mb_type)) {
627 get_lowest_part_y(h, refs, n, 4, y_offset,
628 IS_DIR(sub_mb_type, 0, 0),
629 IS_DIR(sub_mb_type, 0, 1),
631 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
632 IS_DIR(sub_mb_type, 0, 0),
633 IS_DIR(sub_mb_type, 0, 1),
635 } else if (IS_SUB_4X8(sub_mb_type)) {
636 get_lowest_part_y(h, refs, n, 8, y_offset,
637 IS_DIR(sub_mb_type, 0, 0),
638 IS_DIR(sub_mb_type, 0, 1),
640 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
641 IS_DIR(sub_mb_type, 0, 0),
642 IS_DIR(sub_mb_type, 0, 1),
646 av_assert2(IS_SUB_4X4(sub_mb_type));
647 for (j = 0; j < 4; j++) {
648 int sub_y_offset = y_offset + 2 * (j & 2);
649 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
650 IS_DIR(sub_mb_type, 0, 0),
651 IS_DIR(sub_mb_type, 0, 1),
658 for (list = h->list_count - 1; list >= 0; list--)
659 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
660 int row = refs[list][ref];
662 Picture *ref_pic = &h->ref_list[list][ref];
663 int ref_field = ref_pic->f.reference - 1;
664 int ref_field_picture = ref_pic->field_picture;
665 int pic_height = 16 * h->mb_height >> ref_field_picture;
670 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
671 ff_thread_await_progress(&ref_pic->f,
672 FFMIN((row >> 1) - !(row & 1),
675 ff_thread_await_progress(&ref_pic->f,
676 FFMIN((row >> 1), pic_height - 1),
678 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
679 ff_thread_await_progress(&ref_pic->f,
680 FFMIN(row * 2 + ref_field,
683 } else if (FIELD_PICTURE) {
684 ff_thread_await_progress(&ref_pic->f,
685 FFMIN(row, pic_height - 1),
688 ff_thread_await_progress(&ref_pic->f,
689 FFMIN(row, pic_height - 1),
696 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
697 int n, int square, int height,
699 uint8_t *dest_y, uint8_t *dest_cb,
701 int src_x_offset, int src_y_offset,
702 qpel_mc_func *qpix_op,
703 h264_chroma_mc_func chroma_op,
704 int pixel_shift, int chroma_idc)
706 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
707 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
708 const int luma_xy = (mx & 3) + ((my & 3) << 2);
709 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
710 uint8_t *src_y = pic->f.data[0] + offset;
711 uint8_t *src_cb, *src_cr;
713 int extra_height = 0;
715 const int full_mx = mx >> 2;
716 const int full_my = my >> 2;
717 const int pic_width = 16 * h->mb_width;
718 const int pic_height = 16 * h->mb_height >> MB_FIELD;
726 if (full_mx < 0 - extra_width ||
727 full_my < 0 - extra_height ||
728 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
729 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
730 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
731 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
733 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
734 full_my - 2, pic_width, pic_height);
735 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
739 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
741 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
743 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
746 if (chroma_idc == 3 /* yuv444 */) {
747 src_cb = pic->f.data[1] + offset;
749 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
750 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
752 16 + 5, 16 + 5 /*FIXME*/,
753 full_mx - 2, full_my - 2,
754 pic_width, pic_height);
755 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
757 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
759 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
761 src_cr = pic->f.data[2] + offset;
763 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
764 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
766 16 + 5, 16 + 5 /*FIXME*/,
767 full_mx - 2, full_my - 2,
768 pic_width, pic_height);
769 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
771 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
773 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
777 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
778 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
779 // chroma offset when predicting from a field of opposite parity
780 my += 2 * ((h->mb_y & 1) - (pic->f.reference - 1));
781 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
784 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
785 (my >> ysh) * h->mb_uvlinesize;
786 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
787 (my >> ysh) * h->mb_uvlinesize;
790 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
791 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
792 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
793 src_cb = h->edge_emu_buffer;
795 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
796 height >> (chroma_idc == 1 /* yuv420 */),
797 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
800 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
801 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
802 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
803 src_cr = h->edge_emu_buffer;
805 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
806 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
809 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
810 int height, int delta,
811 uint8_t *dest_y, uint8_t *dest_cb,
813 int x_offset, int y_offset,
814 qpel_mc_func *qpix_put,
815 h264_chroma_mc_func chroma_put,
816 qpel_mc_func *qpix_avg,
817 h264_chroma_mc_func chroma_avg,
818 int list0, int list1,
819 int pixel_shift, int chroma_idc)
821 qpel_mc_func *qpix_op = qpix_put;
822 h264_chroma_mc_func chroma_op = chroma_put;
824 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
825 if (chroma_idc == 3 /* yuv444 */) {
826 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
827 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
828 } else if (chroma_idc == 2 /* yuv422 */) {
829 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
830 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
831 } else { /* yuv420 */
832 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
833 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
835 x_offset += 8 * h->mb_x;
836 y_offset += 8 * (h->mb_y >> MB_FIELD);
839 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
840 mc_dir_part(h, ref, n, square, height, delta, 0,
841 dest_y, dest_cb, dest_cr, x_offset, y_offset,
842 qpix_op, chroma_op, pixel_shift, chroma_idc);
845 chroma_op = chroma_avg;
849 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
850 mc_dir_part(h, ref, n, square, height, delta, 1,
851 dest_y, dest_cb, dest_cr, x_offset, y_offset,
852 qpix_op, chroma_op, pixel_shift, chroma_idc);
856 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
857 int height, int delta,
858 uint8_t *dest_y, uint8_t *dest_cb,
860 int x_offset, int y_offset,
861 qpel_mc_func *qpix_put,
862 h264_chroma_mc_func chroma_put,
863 h264_weight_func luma_weight_op,
864 h264_weight_func chroma_weight_op,
865 h264_biweight_func luma_weight_avg,
866 h264_biweight_func chroma_weight_avg,
867 int list0, int list1,
868 int pixel_shift, int chroma_idc)
872 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
873 if (chroma_idc == 3 /* yuv444 */) {
874 chroma_height = height;
875 chroma_weight_avg = luma_weight_avg;
876 chroma_weight_op = luma_weight_op;
877 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
878 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
879 } else if (chroma_idc == 2 /* yuv422 */) {
880 chroma_height = height;
881 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
882 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
883 } else { /* yuv420 */
884 chroma_height = height >> 1;
885 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
886 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
888 x_offset += 8 * h->mb_x;
889 y_offset += 8 * (h->mb_y >> MB_FIELD);
891 if (list0 && list1) {
892 /* don't optimize for luma-only case, since B-frames usually
893 * use implicit weights => chroma too. */
894 uint8_t *tmp_cb = h->bipred_scratchpad;
895 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
896 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
897 int refn0 = h->ref_cache[0][scan8[n]];
898 int refn1 = h->ref_cache[1][scan8[n]];
900 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
901 dest_y, dest_cb, dest_cr,
902 x_offset, y_offset, qpix_put, chroma_put,
903 pixel_shift, chroma_idc);
904 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
905 tmp_y, tmp_cb, tmp_cr,
906 x_offset, y_offset, qpix_put, chroma_put,
907 pixel_shift, chroma_idc);
909 if (h->use_weight == 2) {
910 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
911 int weight1 = 64 - weight0;
912 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
913 height, 5, weight0, weight1, 0);
914 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
915 chroma_height, 5, weight0, weight1, 0);
916 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
917 chroma_height, 5, weight0, weight1, 0);
919 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
920 h->luma_log2_weight_denom,
921 h->luma_weight[refn0][0][0],
922 h->luma_weight[refn1][1][0],
923 h->luma_weight[refn0][0][1] +
924 h->luma_weight[refn1][1][1]);
925 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
926 h->chroma_log2_weight_denom,
927 h->chroma_weight[refn0][0][0][0],
928 h->chroma_weight[refn1][1][0][0],
929 h->chroma_weight[refn0][0][0][1] +
930 h->chroma_weight[refn1][1][0][1]);
931 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
932 h->chroma_log2_weight_denom,
933 h->chroma_weight[refn0][0][1][0],
934 h->chroma_weight[refn1][1][1][0],
935 h->chroma_weight[refn0][0][1][1] +
936 h->chroma_weight[refn1][1][1][1]);
939 int list = list1 ? 1 : 0;
940 int refn = h->ref_cache[list][scan8[n]];
941 Picture *ref = &h->ref_list[list][refn];
942 mc_dir_part(h, ref, n, square, height, delta, list,
943 dest_y, dest_cb, dest_cr, x_offset, y_offset,
944 qpix_put, chroma_put, pixel_shift, chroma_idc);
946 luma_weight_op(dest_y, h->mb_linesize, height,
947 h->luma_log2_weight_denom,
948 h->luma_weight[refn][list][0],
949 h->luma_weight[refn][list][1]);
950 if (h->use_weight_chroma) {
951 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
952 h->chroma_log2_weight_denom,
953 h->chroma_weight[refn][list][0][0],
954 h->chroma_weight[refn][list][0][1]);
955 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
956 h->chroma_log2_weight_denom,
957 h->chroma_weight[refn][list][1][0],
958 h->chroma_weight[refn][list][1][1]);
963 static av_always_inline void prefetch_motion(H264Context *h, int list,
964 int pixel_shift, int chroma_idc)
966 /* fetch pixels for estimated mv 4 macroblocks ahead
967 * optimized for 64byte cache lines */
968 const int refn = h->ref_cache[list][scan8[0]];
970 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
971 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
972 uint8_t **src = h->ref_list[list][refn].f.data;
973 int off = (mx << pixel_shift) +
974 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
976 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
977 if (chroma_idc == 3 /* yuv444 */) {
978 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
979 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
981 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
982 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
987 static void free_tables(H264Context *h, int free_rbsp)
992 av_freep(&h->intra4x4_pred_mode);
993 av_freep(&h->chroma_pred_mode_table);
994 av_freep(&h->cbp_table);
995 av_freep(&h->mvd_table[0]);
996 av_freep(&h->mvd_table[1]);
997 av_freep(&h->direct_table);
998 av_freep(&h->non_zero_count);
999 av_freep(&h->slice_table_base);
1000 h->slice_table = NULL;
1001 av_freep(&h->list_counts);
1003 av_freep(&h->mb2b_xy);
1004 av_freep(&h->mb2br_xy);
1006 for (i = 0; i < 3; i++)
1007 av_freep(&h->visualization_buffer[i]);
1010 for (i = 0; i < h->picture_count && !h->avctx->internal->is_copy; i++)
1011 free_picture(h, &h->DPB[i]);
1013 h->picture_count = 0;
1014 } else if (h->DPB) {
1015 for (i = 0; i < h->picture_count; i++)
1016 h->DPB[i].needs_realloc = 1;
1019 h->cur_pic_ptr = NULL;
1021 for (i = 0; i < MAX_THREADS; i++) {
1022 hx = h->thread_context[i];
1025 av_freep(&hx->top_borders[1]);
1026 av_freep(&hx->top_borders[0]);
1027 av_freep(&hx->bipred_scratchpad);
1028 av_freep(&hx->edge_emu_buffer);
1029 av_freep(&hx->dc_val_base);
1030 av_freep(&hx->me.scratchpad);
1031 av_freep(&hx->er.mb_index2xy);
1032 av_freep(&hx->er.error_status_table);
1033 av_freep(&hx->er.er_temp_buffer);
1034 av_freep(&hx->er.mbintra_table);
1035 av_freep(&hx->er.mbskip_table);
1038 av_freep(&hx->rbsp_buffer[1]);
1039 av_freep(&hx->rbsp_buffer[0]);
1040 hx->rbsp_buffer_size[0] = 0;
1041 hx->rbsp_buffer_size[1] = 0;
1044 av_freep(&h->thread_context[i]);
1048 static void init_dequant8_coeff_table(H264Context *h)
1051 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1053 for (i = 0; i < 6; i++) {
1054 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1055 for (j = 0; j < i; j++)
1056 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1057 64 * sizeof(uint8_t))) {
1058 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1064 for (q = 0; q < max_qp + 1; q++) {
1065 int shift = div6[q];
1067 for (x = 0; x < 64; x++)
1068 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1069 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1070 h->pps.scaling_matrix8[i][x]) << shift;
1075 static void init_dequant4_coeff_table(H264Context *h)
1078 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1079 for (i = 0; i < 6; i++) {
1080 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1081 for (j = 0; j < i; j++)
1082 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1083 16 * sizeof(uint8_t))) {
1084 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1090 for (q = 0; q < max_qp + 1; q++) {
1091 int shift = div6[q] + 2;
1093 for (x = 0; x < 16; x++)
1094 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1095 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1096 h->pps.scaling_matrix4[i][x]) << shift;
1101 static void init_dequant_tables(H264Context *h)
1104 init_dequant4_coeff_table(h);
1105 if (h->pps.transform_8x8_mode)
1106 init_dequant8_coeff_table(h);
1107 if (h->sps.transform_bypass) {
1108 for (i = 0; i < 6; i++)
1109 for (x = 0; x < 16; x++)
1110 h->dequant4_coeff[i][0][x] = 1 << 6;
1111 if (h->pps.transform_8x8_mode)
1112 for (i = 0; i < 6; i++)
1113 for (x = 0; x < 64; x++)
1114 h->dequant8_coeff[i][0][x] = 1 << 6;
1118 int ff_h264_alloc_tables(H264Context *h)
1120 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1121 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1124 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1125 row_mb_num * 8 * sizeof(uint8_t), fail)
1126 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1127 big_mb_num * 48 * sizeof(uint8_t), fail)
1128 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1129 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1130 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1131 big_mb_num * sizeof(uint16_t), fail)
1132 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1133 big_mb_num * sizeof(uint8_t), fail)
1134 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1135 16 * row_mb_num * sizeof(uint8_t), fail);
1136 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1137 16 * row_mb_num * sizeof(uint8_t), fail);
1138 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1139 4 * big_mb_num * sizeof(uint8_t), fail);
1140 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1141 big_mb_num * sizeof(uint8_t), fail)
1143 memset(h->slice_table_base, -1,
1144 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1145 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1147 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1148 big_mb_num * sizeof(uint32_t), fail);
1149 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1150 big_mb_num * sizeof(uint32_t), fail);
1151 for (y = 0; y < h->mb_height; y++)
1152 for (x = 0; x < h->mb_width; x++) {
1153 const int mb_xy = x + y * h->mb_stride;
1154 const int b_xy = 4 * x + 4 * y * h->b_stride;
1156 h->mb2b_xy[mb_xy] = b_xy;
1157 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1160 if (!h->dequant4_coeff[0])
1161 init_dequant_tables(h);
1164 h->picture_count = MAX_PICTURE_COUNT * FFMAX(1, h->avctx->thread_count);
1165 h->DPB = av_mallocz_array(h->picture_count, sizeof(*h->DPB));
1167 return AVERROR(ENOMEM);
1168 for (i = 0; i < h->picture_count; i++)
1169 avcodec_get_frame_defaults(&h->DPB[i].f);
1170 avcodec_get_frame_defaults(&h->cur_pic.f);
1181 * Mimic alloc_tables(), but for every context thread.
1183 static void clone_tables(H264Context *dst, H264Context *src, int i)
1185 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1186 dst->non_zero_count = src->non_zero_count;
1187 dst->slice_table = src->slice_table;
1188 dst->cbp_table = src->cbp_table;
1189 dst->mb2b_xy = src->mb2b_xy;
1190 dst->mb2br_xy = src->mb2br_xy;
1191 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1192 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1193 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1194 dst->direct_table = src->direct_table;
1195 dst->list_counts = src->list_counts;
1196 dst->DPB = src->DPB;
1197 dst->cur_pic_ptr = src->cur_pic_ptr;
1198 dst->cur_pic = src->cur_pic;
1199 dst->bipred_scratchpad = NULL;
1200 dst->edge_emu_buffer = NULL;
1201 dst->me.scratchpad = NULL;
1202 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1203 src->sps.chroma_format_idc);
1208 * Allocate buffers which are not shared amongst multiple threads.
1210 static int context_init(H264Context *h)
1212 ERContext *er = &h->er;
1213 int mb_array_size = h->mb_height * h->mb_stride;
1214 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1215 int c_size = h->mb_stride * (h->mb_height + 1);
1216 int yc_size = y_size + 2 * c_size;
1219 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1220 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1221 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1222 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1224 h->ref_cache[0][scan8[5] + 1] =
1225 h->ref_cache[0][scan8[7] + 1] =
1226 h->ref_cache[0][scan8[13] + 1] =
1227 h->ref_cache[1][scan8[5] + 1] =
1228 h->ref_cache[1][scan8[7] + 1] =
1229 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1232 er->avctx = h->avctx;
1234 er->decode_mb = h264_er_decode_mb;
1236 er->quarter_sample = 1;
1238 er->mb_num = h->mb_num;
1239 er->mb_width = h->mb_width;
1240 er->mb_height = h->mb_height;
1241 er->mb_stride = h->mb_stride;
1242 er->b8_stride = h->mb_width * 2 + 1;
1244 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1245 fail); // error ressilience code looks cleaner with this
1246 for (y = 0; y < h->mb_height; y++)
1247 for (x = 0; x < h->mb_width; x++)
1248 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1250 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1251 h->mb_stride + h->mb_width;
1253 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1254 mb_array_size * sizeof(uint8_t), fail);
1256 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1257 memset(er->mbintra_table, 1, mb_array_size);
1259 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1261 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1264 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1265 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1266 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1267 er->dc_val[2] = er->dc_val[1] + c_size;
1268 for (i = 0; i < yc_size; i++)
1269 h->dc_val_base[i] = 1024;
1274 return -1; // free_tables will clean up for us
1277 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1278 int parse_extradata);
1280 static av_cold void common_init(H264Context *h)
1283 h->width = h->avctx->width;
1284 h->height = h->avctx->height;
1286 h->bit_depth_luma = 8;
1287 h->chroma_format_idc = 1;
1289 h->avctx->bits_per_raw_sample = 8;
1290 h->cur_chroma_format_idc = 1;
1292 ff_h264dsp_init(&h->h264dsp, 8, 1);
1293 av_assert0(h->sps.bit_depth_chroma == 0);
1294 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1295 ff_h264qpel_init(&h->h264qpel, 8);
1296 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1298 h->dequant_coeff_pps = -1;
1300 h->dsp.dct_bits = 16;
1301 /* needed so that IDCT permutation is known early */
1302 ff_dsputil_init(&h->dsp, h->avctx);
1303 ff_videodsp_init(&h->vdsp, 8);
1305 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1306 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1309 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1311 AVCodecContext *avctx = h->avctx;
1313 if (!buf || size <= 0)
1317 int i, cnt, nalsize;
1318 const unsigned char *p = buf;
1323 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1326 /* sps and pps in the avcC always have length coded with 2 bytes,
1327 * so put a fake nal_length_size = 2 while parsing them */
1328 h->nal_length_size = 2;
1329 // Decode sps from avcC
1330 cnt = *(p + 5) & 0x1f; // Number of sps
1332 for (i = 0; i < cnt; i++) {
1333 nalsize = AV_RB16(p) + 2;
1334 if(nalsize > size - (p-buf))
1336 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1337 av_log(avctx, AV_LOG_ERROR,
1338 "Decoding sps %d from avcC failed\n", i);
1343 // Decode pps from avcC
1344 cnt = *(p++); // Number of pps
1345 for (i = 0; i < cnt; i++) {
1346 nalsize = AV_RB16(p) + 2;
1347 if(nalsize > size - (p-buf))
1349 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1350 av_log(avctx, AV_LOG_ERROR,
1351 "Decoding pps %d from avcC failed\n", i);
1356 // Now store right nal length size, that will be used to parse all other nals
1357 h->nal_length_size = (buf[4] & 0x03) + 1;
1360 if (decode_nal_units(h, buf, size, 1) < 0)
1366 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1368 H264Context *h = avctx->priv_data;
1374 h->picture_structure = PICT_FRAME;
1375 h->picture_range_start = 0;
1376 h->picture_range_end = MAX_PICTURE_COUNT;
1377 h->slice_context_count = 1;
1378 h->workaround_bugs = avctx->workaround_bugs;
1379 h->flags = avctx->flags;
1382 // s->decode_mb = ff_h263_decode_mb;
1383 if (!avctx->has_b_frames)
1386 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1388 ff_h264_decode_init_vlc();
1391 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1393 h->thread_context[0] = h;
1394 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1395 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1396 h->last_pocs[i] = INT_MIN;
1397 h->prev_poc_msb = 1 << 16;
1398 h->prev_frame_num = -1;
1400 ff_h264_reset_sei(h);
1401 if (avctx->codec_id == AV_CODEC_ID_H264) {
1402 if (avctx->ticks_per_frame == 1) {
1403 if(h->avctx->time_base.den < INT_MAX/2) {
1404 h->avctx->time_base.den *= 2;
1406 h->avctx->time_base.num /= 2;
1408 avctx->ticks_per_frame = 2;
1411 if (avctx->extradata_size > 0 && avctx->extradata &&
1412 ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
1413 ff_h264_free_context(h);
1417 if (h->sps.bitstream_restriction_flag &&
1418 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1419 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1423 ff_init_cabac_states();
1428 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1429 #undef REBASE_PICTURE
1430 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1431 ((pic && pic >= old_ctx->DPB && \
1432 pic < old_ctx->DPB + old_ctx->picture_count) ? \
1433 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1435 static void copy_picture_range(Picture **to, Picture **from, int count,
1436 H264Context *new_base,
1437 H264Context *old_base)
1441 for (i = 0; i < count; i++) {
1442 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1443 IN_RANGE(from[i], old_base->DPB,
1444 sizeof(Picture) * old_base->picture_count) ||
1446 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1450 static void copy_parameter_set(void **to, void **from, int count, int size)
1454 for (i = 0; i < count; i++) {
1455 if (to[i] && !from[i])
1457 else if (from[i] && !to[i])
1458 to[i] = av_malloc(size);
1461 memcpy(to[i], from[i], size);
1465 static int decode_init_thread_copy(AVCodecContext *avctx)
1467 H264Context *h = avctx->priv_data;
1469 if (!avctx->internal->is_copy)
1471 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1472 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1474 h->context_initialized = 0;
1479 #define copy_fields(to, from, start_field, end_field) \
1480 memcpy(&to->start_field, &from->start_field, \
1481 (char *)&to->end_field - (char *)&to->start_field)
1483 static int h264_slice_header_init(H264Context *, int);
1485 static int h264_set_parameter_from_sps(H264Context *h);
1487 static int decode_update_thread_context(AVCodecContext *dst,
1488 const AVCodecContext *src)
1490 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1491 int inited = h->context_initialized, err = 0;
1492 int context_reinitialized = 0;
1499 (h->width != h1->width ||
1500 h->height != h1->height ||
1501 h->mb_width != h1->mb_width ||
1502 h->mb_height != h1->mb_height ||
1503 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1504 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1505 h->sps.colorspace != h1->sps.colorspace)) {
1507 av_freep(&h->bipred_scratchpad);
1509 h->width = h1->width;
1510 h->height = h1->height;
1511 h->mb_height = h1->mb_height;
1512 h->mb_width = h1->mb_width;
1513 h->mb_num = h1->mb_num;
1514 h->mb_stride = h1->mb_stride;
1515 h->b_stride = h1->b_stride;
1517 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1518 MAX_SPS_COUNT, sizeof(SPS));
1520 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1521 MAX_PPS_COUNT, sizeof(PPS));
1524 if ((err = h264_slice_header_init(h, 1)) < 0) {
1525 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1528 context_reinitialized = 1;
1531 h264_set_parameter_from_sps(h);
1532 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1533 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1536 /* update linesize on resize for h264. The h264 decoder doesn't
1537 * necessarily call ff_MPV_frame_start in the new thread */
1538 h->linesize = h1->linesize;
1539 h->uvlinesize = h1->uvlinesize;
1541 /* copy block_offset since frame_start may not be called */
1542 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1545 for (i = 0; i < MAX_SPS_COUNT; i++)
1546 av_freep(h->sps_buffers + i);
1548 for (i = 0; i < MAX_PPS_COUNT; i++)
1549 av_freep(h->pps_buffers + i);
1551 memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1552 memcpy(&h->cabac, &h1->cabac,
1553 sizeof(H264Context) - offsetof(H264Context, cabac));
1554 av_assert0(&h->cabac == &h->mb_padding + 1);
1556 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1557 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1559 memset(&h->er, 0, sizeof(h->er));
1560 memset(&h->me, 0, sizeof(h->me));
1564 if (h1->context_initialized) {
1565 h->context_initialized = 0;
1567 h->picture_range_start += MAX_PICTURE_COUNT;
1568 h->picture_range_end += MAX_PICTURE_COUNT;
1570 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1572 if (ff_h264_alloc_tables(h) < 0) {
1573 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1574 return AVERROR(ENOMEM);
1579 for (i = 0; i < 2; i++) {
1580 h->rbsp_buffer[i] = NULL;
1581 h->rbsp_buffer_size[i] = 0;
1583 h->bipred_scratchpad = NULL;
1584 h->edge_emu_buffer = NULL;
1586 h->thread_context[0] = h;
1587 h->context_initialized = h1->context_initialized;
1590 h->avctx->coded_height = h1->avctx->coded_height;
1591 h->avctx->coded_width = h1->avctx->coded_width;
1592 h->avctx->width = h1->avctx->width;
1593 h->avctx->height = h1->avctx->height;
1594 h->coded_picture_number = h1->coded_picture_number;
1595 h->first_field = h1->first_field;
1596 h->picture_structure = h1->picture_structure;
1597 h->qscale = h1->qscale;
1598 h->droppable = h1->droppable;
1599 h->data_partitioning = h1->data_partitioning;
1600 h->low_delay = h1->low_delay;
1602 memcpy(h->DPB, h1->DPB, h1->picture_count * sizeof(*h1->DPB));
1604 // reset s->picture[].f.extended_data to s->picture[].f.data
1605 for (i = 0; i < h->picture_count; i++) {
1606 h->DPB[i].f.extended_data = h->DPB[i].f.data;
1607 h->DPB[i].period_since_free ++;
1610 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1611 h->cur_pic = h1->cur_pic;
1612 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1614 h->workaround_bugs = h1->workaround_bugs;
1615 h->low_delay = h1->low_delay;
1616 h->droppable = h1->droppable;
1618 // extradata/NAL handling
1619 h->is_avc = h1->is_avc;
1622 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1623 MAX_SPS_COUNT, sizeof(SPS));
1625 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1626 MAX_PPS_COUNT, sizeof(PPS));
1629 // Dequantization matrices
1630 // FIXME these are big - can they be only copied when PPS changes?
1631 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1633 for (i = 0; i < 6; i++)
1634 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1635 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1637 for (i = 0; i < 6; i++)
1638 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1639 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1641 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1644 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1647 copy_fields(h, h1, ref_count, list_count);
1648 copy_fields(h, h1, ref2frm, intra_gb);
1649 copy_fields(h, h1, short_ref, cabac_init_idc);
1651 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1652 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1653 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1654 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1656 h->last_slice_type = h1->last_slice_type;
1658 memcpy(h->last_ref_count, h1->last_ref_count, sizeof(h->last_ref_count));
1660 if (context_reinitialized)
1661 h264_set_parameter_from_sps(h);
1663 if (!h->cur_pic_ptr)
1666 if (!h->droppable) {
1667 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1668 h->prev_poc_msb = h->poc_msb;
1669 h->prev_poc_lsb = h->poc_lsb;
1671 h->prev_frame_num_offset = h->frame_num_offset;
1672 h->prev_frame_num = h->frame_num;
1673 h->outputed_poc = h->next_outputed_poc;
1678 int ff_h264_frame_start(H264Context *h)
1682 const int pixel_shift = h->pixel_shift;
1684 1<<(h->sps.bit_depth_luma-1),
1685 1<<(h->sps.bit_depth_chroma-1),
1686 1<<(h->sps.bit_depth_chroma-1),
1690 if (!ff_thread_can_start_frame(h->avctx)) {
1691 av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1695 release_unused_pictures(h, 1);
1696 h->cur_pic_ptr = NULL;
1698 i = find_unused_picture(h);
1700 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1705 pic->f.reference = h->droppable ? 0 : h->picture_structure;
1706 pic->f.coded_picture_number = h->coded_picture_number++;
1707 pic->field_picture = h->picture_structure != PICT_FRAME;
1710 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1712 * See decode_nal_units().
1714 pic->f.key_frame = 0;
1716 pic->mmco_reset = 0;
1718 if ((ret = alloc_picture(h, pic)) < 0)
1720 if(!h->sync && !h->avctx->hwaccel &&
1721 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1722 avpriv_color_frame(&pic->f, c);
1724 h->cur_pic_ptr = pic;
1725 h->cur_pic = *h->cur_pic_ptr;
1726 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1728 ff_er_frame_start(&h->er);
1730 h->er.next_pic = NULL;
1732 assert(h->linesize && h->uvlinesize);
1734 for (i = 0; i < 16; i++) {
1735 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1736 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1738 for (i = 0; i < 16; i++) {
1739 h->block_offset[16 + i] =
1740 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1741 h->block_offset[48 + 16 + i] =
1742 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1745 /* Some macroblocks can be accessed before they're available in case
1746 * of lost slices, MBAFF or threading. */
1747 memset(h->slice_table, -1,
1748 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1750 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1751 // h->cur_pic.f.reference /* || h->contains_intra */ || 1;
1753 /* We mark the current picture as non-reference after allocating it, so
1754 * that if we break out due to an error it can be released automatically
1755 * in the next ff_MPV_frame_start().
1756 * SVQ3 as well as most other codecs have only last/next/current and thus
1757 * get released even with set reference, besides SVQ3 and others do not
1758 * mark frames as reference later "naturally". */
1759 if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
1760 h->cur_pic_ptr->f.reference = 0;
1762 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1764 h->next_output_pic = NULL;
1766 assert(h->cur_pic_ptr->long_ref == 0);
1772 * Run setup operations that must be run after slice header decoding.
1773 * This includes finding the next displayed frame.
1775 * @param h h264 master context
1776 * @param setup_finished enough NALs have been read that we can call
1777 * ff_thread_finish_setup()
1779 static void decode_postinit(H264Context *h, int setup_finished)
1781 Picture *out = h->cur_pic_ptr;
1782 Picture *cur = h->cur_pic_ptr;
1783 int i, pics, out_of_order, out_idx;
1785 h->cur_pic_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1786 h->cur_pic_ptr->f.pict_type = h->pict_type;
1788 if (h->next_output_pic)
1791 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1792 /* FIXME: if we have two PAFF fields in one packet, we can't start
1793 * the next thread here. If we have one field per packet, we can.
1794 * The check in decode_nal_units() is not good enough to find this
1795 * yet, so we assume the worst for now. */
1796 // if (setup_finished)
1797 // ff_thread_finish_setup(h->avctx);
1801 cur->f.interlaced_frame = 0;
1802 cur->f.repeat_pict = 0;
1804 /* Signal interlacing information externally. */
1805 /* Prioritize picture timing SEI information over used
1806 * decoding process if it exists. */
1808 if (h->sps.pic_struct_present_flag) {
1809 switch (h->sei_pic_struct) {
1810 case SEI_PIC_STRUCT_FRAME:
1812 case SEI_PIC_STRUCT_TOP_FIELD:
1813 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1814 cur->f.interlaced_frame = 1;
1816 case SEI_PIC_STRUCT_TOP_BOTTOM:
1817 case SEI_PIC_STRUCT_BOTTOM_TOP:
1818 if (FIELD_OR_MBAFF_PICTURE)
1819 cur->f.interlaced_frame = 1;
1821 // try to flag soft telecine progressive
1822 cur->f.interlaced_frame = h->prev_interlaced_frame;
1824 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1825 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1826 /* Signal the possibility of telecined film externally
1827 * (pic_struct 5,6). From these hints, let the applications
1828 * decide if they apply deinterlacing. */
1829 cur->f.repeat_pict = 1;
1831 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1832 cur->f.repeat_pict = 2;
1834 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1835 cur->f.repeat_pict = 4;
1839 if ((h->sei_ct_type & 3) &&
1840 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1841 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1843 /* Derive interlacing flag from used decoding process. */
1844 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1846 h->prev_interlaced_frame = cur->f.interlaced_frame;
1848 if (cur->field_poc[0] != cur->field_poc[1]) {
1849 /* Derive top_field_first from field pocs. */
1850 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1852 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1853 /* Use picture timing SEI information. Even if it is a
1854 * information of a past frame, better than nothing. */
1855 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1856 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1857 cur->f.top_field_first = 1;
1859 cur->f.top_field_first = 0;
1861 /* Most likely progressive */
1862 cur->f.top_field_first = 0;
1866 cur->mmco_reset = h->mmco_reset;
1868 // FIXME do something with unavailable reference frames
1870 /* Sort B-frames into display order */
1872 if (h->sps.bitstream_restriction_flag &&
1873 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1874 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1878 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1879 !h->sps.bitstream_restriction_flag) {
1880 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1884 for (i = 0; 1; i++) {
1885 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
1887 h->last_pocs[i-1] = cur->poc;
1890 h->last_pocs[i-1]= h->last_pocs[i];
1893 out_of_order = MAX_DELAYED_PIC_COUNT - i;
1894 if( cur->f.pict_type == AV_PICTURE_TYPE_B
1895 || (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))
1896 out_of_order = FFMAX(out_of_order, 1);
1897 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
1898 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
1899 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
1900 h->last_pocs[i] = INT_MIN;
1901 h->last_pocs[0] = cur->poc;
1902 cur->mmco_reset = 1;
1903 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
1904 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
1905 h->avctx->has_b_frames = out_of_order;
1910 while (h->delayed_pic[pics])
1913 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
1915 h->delayed_pic[pics++] = cur;
1916 if (cur->f.reference == 0)
1917 cur->f.reference = DELAYED_PIC_REF;
1919 out = h->delayed_pic[0];
1921 for (i = 1; h->delayed_pic[i] &&
1922 !h->delayed_pic[i]->f.key_frame &&
1923 !h->delayed_pic[i]->mmco_reset;
1925 if (h->delayed_pic[i]->poc < out->poc) {
1926 out = h->delayed_pic[i];
1929 if (h->avctx->has_b_frames == 0 &&
1930 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
1931 h->next_outputed_poc = INT_MIN;
1932 out_of_order = out->poc < h->next_outputed_poc;
1934 if (out_of_order || pics > h->avctx->has_b_frames) {
1935 out->f.reference &= ~DELAYED_PIC_REF;
1936 // for frame threading, the owner must be the second field's thread or
1937 // else the first thread can release the picture and reuse it unsafely
1939 for (i = out_idx; h->delayed_pic[i]; i++)
1940 h->delayed_pic[i] = h->delayed_pic[i + 1];
1942 if (!out_of_order && pics > h->avctx->has_b_frames) {
1943 h->next_output_pic = out;
1944 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
1945 h->next_outputed_poc = INT_MIN;
1947 h->next_outputed_poc = out->poc;
1949 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1952 if (h->next_output_pic && h->next_output_pic->sync) {
1957 ff_thread_finish_setup(h->avctx);
1960 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1961 uint8_t *src_cb, uint8_t *src_cr,
1962 int linesize, int uvlinesize,
1965 uint8_t *top_border;
1967 const int pixel_shift = h->pixel_shift;
1968 int chroma444 = CHROMA444;
1969 int chroma422 = CHROMA422;
1972 src_cb -= uvlinesize;
1973 src_cr -= uvlinesize;
1975 if (!simple && FRAME_MBAFF) {
1978 top_border = h->top_borders[0][h->mb_x];
1979 AV_COPY128(top_border, src_y + 15 * linesize);
1981 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1982 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
1985 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1986 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1987 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1988 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1990 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1991 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1993 } else if (chroma422) {
1995 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1996 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1998 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1999 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2003 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2004 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2006 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2007 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2012 } else if (MB_MBAFF) {
2018 top_border = h->top_borders[top_idx][h->mb_x];
2019 /* There are two lines saved, the line above the top macroblock
2020 * of a pair, and the line above the bottom macroblock. */
2021 AV_COPY128(top_border, src_y + 16 * linesize);
2023 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2025 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2028 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2029 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2030 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2031 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2033 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2034 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2036 } else if (chroma422) {
2038 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2039 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2041 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2042 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2046 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2047 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2049 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2050 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2056 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2057 uint8_t *src_cb, uint8_t *src_cr,
2058 int linesize, int uvlinesize,
2059 int xchg, int chroma444,
2060 int simple, int pixel_shift)
2062 int deblock_topleft;
2065 uint8_t *top_border_m1;
2066 uint8_t *top_border;
2068 if (!simple && FRAME_MBAFF) {
2073 top_idx = MB_MBAFF ? 0 : 1;
2077 if (h->deblocking_filter == 2) {
2078 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2079 deblock_top = h->top_type;
2081 deblock_topleft = (h->mb_x > 0);
2082 deblock_top = (h->mb_y > !!MB_FIELD);
2085 src_y -= linesize + 1 + pixel_shift;
2086 src_cb -= uvlinesize + 1 + pixel_shift;
2087 src_cr -= uvlinesize + 1 + pixel_shift;
2089 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2090 top_border = h->top_borders[top_idx][h->mb_x];
2092 #define XCHG(a, b, xchg) \
2093 if (pixel_shift) { \
2095 AV_SWAP64(b + 0, a + 0); \
2096 AV_SWAP64(b + 8, a + 8); \
2106 if (deblock_topleft) {
2107 XCHG(top_border_m1 + (8 << pixel_shift),
2108 src_y - (7 << pixel_shift), 1);
2110 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2111 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2112 if (h->mb_x + 1 < h->mb_width) {
2113 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2114 src_y + (17 << pixel_shift), 1);
2117 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2119 if (deblock_topleft) {
2120 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2121 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2123 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2124 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2125 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2126 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2127 if (h->mb_x + 1 < h->mb_width) {
2128 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2129 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2133 if (deblock_topleft) {
2134 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2135 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2137 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2138 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2144 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2147 if (high_bit_depth) {
2148 return AV_RN32A(((int32_t *)mb) + index);
2150 return AV_RN16A(mb + index);
2153 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2154 int index, int value)
2156 if (high_bit_depth) {
2157 AV_WN32A(((int32_t *)mb) + index, value);
2159 AV_WN16A(mb + index, value);
2162 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2163 int mb_type, int is_h264,
2165 int transform_bypass,
2169 uint8_t *dest_y, int p)
2171 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2172 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2174 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2175 block_offset += 16 * p;
2176 if (IS_INTRA4x4(mb_type)) {
2177 if (IS_8x8DCT(mb_type)) {
2178 if (transform_bypass) {
2180 idct_add = h->h264dsp.h264_add_pixels8_clear;
2182 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2183 idct_add = h->h264dsp.h264_idct8_add;
2185 for (i = 0; i < 16; i += 4) {
2186 uint8_t *const ptr = dest_y + block_offset[i];
2187 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2188 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2189 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2191 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2192 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2193 (h->topright_samples_available << i) & 0x4000, linesize);
2195 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2196 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2198 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2203 if (transform_bypass) {
2205 idct_add = h->h264dsp.h264_add_pixels4_clear;
2207 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2208 idct_add = h->h264dsp.h264_idct_add;
2210 for (i = 0; i < 16; i++) {
2211 uint8_t *const ptr = dest_y + block_offset[i];
2212 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2214 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2215 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2220 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2221 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2222 av_assert2(h->mb_y || linesize <= block_offset[i]);
2223 if (!topright_avail) {
2225 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2226 topright = (uint8_t *)&tr_high;
2228 tr = ptr[3 - linesize] * 0x01010101u;
2229 topright = (uint8_t *)&tr;
2232 topright = ptr + (4 << pixel_shift) - linesize;
2236 h->hpc.pred4x4[dir](ptr, topright, linesize);
2237 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2240 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2241 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2243 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2244 } else if (CONFIG_SVQ3_DECODER)
2245 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2251 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2253 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2254 if (!transform_bypass)
2255 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2257 h->dequant4_coeff[p][qscale][0]);
2259 static const uint8_t dc_mapping[16] = {
2260 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2261 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2262 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2263 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
2264 for (i = 0; i < 16; i++)
2265 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2266 pixel_shift, dc_mapping[i],
2267 dctcoef_get(h->mb_luma_dc[p],
2271 } else if (CONFIG_SVQ3_DECODER)
2272 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2273 h->mb_luma_dc[p], qscale);
2277 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2278 int is_h264, int simple,
2279 int transform_bypass,
2283 uint8_t *dest_y, int p)
2285 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2287 block_offset += 16 * p;
2288 if (!IS_INTRA4x4(mb_type)) {
2290 if (IS_INTRA16x16(mb_type)) {
2291 if (transform_bypass) {
2292 if (h->sps.profile_idc == 244 &&
2293 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2294 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2295 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2296 h->mb + (p * 256 << pixel_shift),
2299 for (i = 0; i < 16; i++)
2300 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2301 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2302 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2303 h->mb + (i * 16 + p * 256 << pixel_shift),
2307 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2308 h->mb + (p * 256 << pixel_shift),
2310 h->non_zero_count_cache + p * 5 * 8);
2312 } else if (h->cbp & 15) {
2313 if (transform_bypass) {
2314 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2315 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2316 : h->h264dsp.h264_add_pixels4_clear;
2317 for (i = 0; i < 16; i += di)
2318 if (h->non_zero_count_cache[scan8[i + p * 16]])
2319 idct_add(dest_y + block_offset[i],
2320 h->mb + (i * 16 + p * 256 << pixel_shift),
2323 if (IS_8x8DCT(mb_type))
2324 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2325 h->mb + (p * 256 << pixel_shift),
2327 h->non_zero_count_cache + p * 5 * 8);
2329 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2330 h->mb + (p * 256 << pixel_shift),
2332 h->non_zero_count_cache + p * 5 * 8);
2335 } else if (CONFIG_SVQ3_DECODER) {
2336 for (i = 0; i < 16; i++)
2337 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2338 // FIXME benchmark weird rule, & below
2339 uint8_t *const ptr = dest_y + block_offset[i];
2340 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2341 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2349 #include "h264_mb_template.c"
2353 #include "h264_mb_template.c"
2357 #include "h264_mb_template.c"
2359 void ff_h264_hl_decode_mb(H264Context *h)
2361 const int mb_xy = h->mb_xy;
2362 const int mb_type = h->cur_pic.f.mb_type[mb_xy];
2363 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
2366 if (is_complex || h->pixel_shift)
2367 hl_decode_mb_444_complex(h);
2369 hl_decode_mb_444_simple_8(h);
2370 } else if (is_complex) {
2371 hl_decode_mb_complex(h);
2372 } else if (h->pixel_shift) {
2373 hl_decode_mb_simple_16(h);
2375 hl_decode_mb_simple_8(h);
2378 static int pred_weight_table(H264Context *h)
2381 int luma_def, chroma_def;
2384 h->use_weight_chroma = 0;
2385 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2386 if (h->sps.chroma_format_idc)
2387 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2388 luma_def = 1 << h->luma_log2_weight_denom;
2389 chroma_def = 1 << h->chroma_log2_weight_denom;
2391 for (list = 0; list < 2; list++) {
2392 h->luma_weight_flag[list] = 0;
2393 h->chroma_weight_flag[list] = 0;
2394 for (i = 0; i < h->ref_count[list]; i++) {
2395 int luma_weight_flag, chroma_weight_flag;
2397 luma_weight_flag = get_bits1(&h->gb);
2398 if (luma_weight_flag) {
2399 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2400 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2401 if (h->luma_weight[i][list][0] != luma_def ||
2402 h->luma_weight[i][list][1] != 0) {
2404 h->luma_weight_flag[list] = 1;
2407 h->luma_weight[i][list][0] = luma_def;
2408 h->luma_weight[i][list][1] = 0;
2411 if (h->sps.chroma_format_idc) {
2412 chroma_weight_flag = get_bits1(&h->gb);
2413 if (chroma_weight_flag) {
2415 for (j = 0; j < 2; j++) {
2416 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2417 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2418 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2419 h->chroma_weight[i][list][j][1] != 0) {
2420 h->use_weight_chroma = 1;
2421 h->chroma_weight_flag[list] = 1;
2426 for (j = 0; j < 2; j++) {
2427 h->chroma_weight[i][list][j][0] = chroma_def;
2428 h->chroma_weight[i][list][j][1] = 0;
2433 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2436 h->use_weight = h->use_weight || h->use_weight_chroma;
2441 * Initialize implicit_weight table.
2442 * @param field 0/1 initialize the weight for interlaced MBAFF
2443 * -1 initializes the rest
2445 static void implicit_weight_table(H264Context *h, int field)
2447 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2449 for (i = 0; i < 2; i++) {
2450 h->luma_weight_flag[i] = 0;
2451 h->chroma_weight_flag[i] = 0;
2455 if (h->picture_structure == PICT_FRAME) {
2456 cur_poc = h->cur_pic_ptr->poc;
2458 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2460 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2461 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2463 h->use_weight_chroma = 0;
2467 ref_count0 = h->ref_count[0];
2468 ref_count1 = h->ref_count[1];
2470 cur_poc = h->cur_pic_ptr->field_poc[field];
2472 ref_count0 = 16 + 2 * h->ref_count[0];
2473 ref_count1 = 16 + 2 * h->ref_count[1];
2477 h->use_weight_chroma = 2;
2478 h->luma_log2_weight_denom = 5;
2479 h->chroma_log2_weight_denom = 5;
2481 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2482 int poc0 = h->ref_list[0][ref0].poc;
2483 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2485 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2486 int poc1 = h->ref_list[1][ref1].poc;
2487 int td = av_clip(poc1 - poc0, -128, 127);
2489 int tb = av_clip(cur_poc - poc0, -128, 127);
2490 int tx = (16384 + (FFABS(td) >> 1)) / td;
2491 int dist_scale_factor = (tb * tx + 32) >> 8;
2492 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2493 w = 64 - dist_scale_factor;
2497 h->implicit_weight[ref0][ref1][0] =
2498 h->implicit_weight[ref0][ref1][1] = w;
2500 h->implicit_weight[ref0][ref1][field] = w;
2507 * instantaneous decoder refresh.
2509 static void idr(H264Context *h)
2512 ff_h264_remove_all_refs(h);
2513 h->prev_frame_num = 0;
2514 h->prev_frame_num_offset = 0;
2515 h->prev_poc_msb = 1<<16;
2516 h->prev_poc_lsb = 0;
2517 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2518 h->last_pocs[i] = INT_MIN;
2521 /* forget old pics after a seek */
2522 static void flush_change(H264Context *h)
2526 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2527 h->prev_interlaced_frame = 1;
2529 h->prev_frame_num = -1;
2530 if (h->cur_pic_ptr) {
2531 h->cur_pic_ptr->f.reference = 0;
2532 for (j=i=0; h->delayed_pic[i]; i++)
2533 if (h->delayed_pic[i] != h->cur_pic_ptr)
2534 h->delayed_pic[j++] = h->delayed_pic[i];
2535 h->delayed_pic[j] = NULL;
2538 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2539 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2540 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2541 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2542 ff_h264_reset_sei(h);
2543 h->recovery_frame= -1;
2546 h->current_slice = 0;
2549 /* forget old pics after a seek */
2550 static void flush_dpb(AVCodecContext *avctx)
2552 H264Context *h = avctx->priv_data;
2555 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2556 if (h->delayed_pic[i])
2557 h->delayed_pic[i]->f.reference = 0;
2558 h->delayed_pic[i] = NULL;
2563 for (i = 0; i < h->picture_count; i++) {
2564 if (h->DPB[i].f.data[0])
2565 free_frame_buffer(h, &h->DPB[i]);
2567 h->cur_pic_ptr = NULL;
2569 h->mb_x = h->mb_y = 0;
2571 h->parse_context.state = -1;
2572 h->parse_context.frame_start_found = 0;
2573 h->parse_context.overread = 0;
2574 h->parse_context.overread_index = 0;
2575 h->parse_context.index = 0;
2576 h->parse_context.last_index = 0;
2579 static int init_poc(H264Context *h)
2581 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2583 Picture *cur = h->cur_pic_ptr;
2585 h->frame_num_offset = h->prev_frame_num_offset;
2586 if (h->frame_num < h->prev_frame_num)
2587 h->frame_num_offset += max_frame_num;
2589 if (h->sps.poc_type == 0) {
2590 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2592 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2593 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2594 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2595 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2597 h->poc_msb = h->prev_poc_msb;
2599 field_poc[1] = h->poc_msb + h->poc_lsb;
2600 if (h->picture_structure == PICT_FRAME)
2601 field_poc[1] += h->delta_poc_bottom;
2602 } else if (h->sps.poc_type == 1) {
2603 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2606 if (h->sps.poc_cycle_length != 0)
2607 abs_frame_num = h->frame_num_offset + h->frame_num;
2611 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2614 expected_delta_per_poc_cycle = 0;
2615 for (i = 0; i < h->sps.poc_cycle_length; i++)
2616 // FIXME integrate during sps parse
2617 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2619 if (abs_frame_num > 0) {
2620 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2621 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2623 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2624 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2625 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2629 if (h->nal_ref_idc == 0)
2630 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2632 field_poc[0] = expectedpoc + h->delta_poc[0];
2633 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2635 if (h->picture_structure == PICT_FRAME)
2636 field_poc[1] += h->delta_poc[1];
2638 int poc = 2 * (h->frame_num_offset + h->frame_num);
2640 if (!h->nal_ref_idc)
2647 if (h->picture_structure != PICT_BOTTOM_FIELD)
2648 h->cur_pic_ptr->field_poc[0] = field_poc[0];
2649 if (h->picture_structure != PICT_TOP_FIELD)
2650 h->cur_pic_ptr->field_poc[1] = field_poc[1];
2651 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2657 * initialize scan tables
2659 static void init_scan_tables(H264Context *h)
2662 for (i = 0; i < 16; i++) {
2663 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2664 h->zigzag_scan[i] = T(zigzag_scan[i]);
2665 h->field_scan[i] = T(field_scan[i]);
2668 for (i = 0; i < 64; i++) {
2669 #define T(x) (x >> 3) | ((x & 7) << 3)
2670 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2671 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2672 h->field_scan8x8[i] = T(field_scan8x8[i]);
2673 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2676 if (h->sps.transform_bypass) { // FIXME same ugly
2677 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2678 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2679 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2680 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2681 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2682 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2684 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2685 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2686 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2687 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2688 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2689 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2693 static int field_end(H264Context *h, int in_setup)
2695 AVCodecContext *const avctx = h->avctx;
2699 if (!in_setup && !h->droppable)
2700 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
2701 h->picture_structure == PICT_BOTTOM_FIELD);
2703 if (CONFIG_H264_VDPAU_DECODER &&
2704 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2705 ff_vdpau_h264_set_reference_frames(h);
2707 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2708 if (!h->droppable) {
2709 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2710 h->prev_poc_msb = h->poc_msb;
2711 h->prev_poc_lsb = h->poc_lsb;
2713 h->prev_frame_num_offset = h->frame_num_offset;
2714 h->prev_frame_num = h->frame_num;
2715 h->outputed_poc = h->next_outputed_poc;
2718 if (avctx->hwaccel) {
2719 if (avctx->hwaccel->end_frame(avctx) < 0)
2720 av_log(avctx, AV_LOG_ERROR,
2721 "hardware accelerator failed to decode picture\n");
2724 if (CONFIG_H264_VDPAU_DECODER &&
2725 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2726 ff_vdpau_h264_picture_complete(h);
2729 * FIXME: Error handling code does not seem to support interlaced
2730 * when slices span multiple rows
2731 * The ff_er_add_slice calls don't work right for bottom
2732 * fields; they cause massive erroneous error concealing
2733 * Error marking covers both fields (top and bottom).
2734 * This causes a mismatched s->error_count
2735 * and a bad error table. Further, the error count goes to
2736 * INT_MAX when called for bottom field, because mb_y is
2737 * past end by one (callers fault) and resync_mb_y != 0
2738 * causes problems for the first MB line, too.
2740 if (!FIELD_PICTURE && h->current_slice && !h->sps.new) {
2741 h->er.cur_pic = h->cur_pic_ptr;
2742 ff_er_frame_end(&h->er);
2746 h->current_slice = 0;
2752 * Replicate H264 "master" context to thread contexts.
2754 static int clone_slice(H264Context *dst, H264Context *src)
2756 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2757 dst->cur_pic_ptr = src->cur_pic_ptr;
2758 dst->cur_pic = src->cur_pic;
2759 dst->linesize = src->linesize;
2760 dst->uvlinesize = src->uvlinesize;
2761 dst->first_field = src->first_field;
2763 dst->prev_poc_msb = src->prev_poc_msb;
2764 dst->prev_poc_lsb = src->prev_poc_lsb;
2765 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2766 dst->prev_frame_num = src->prev_frame_num;
2767 dst->short_ref_count = src->short_ref_count;
2769 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2770 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2771 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2773 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2774 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2780 * Compute profile from profile_idc and constraint_set?_flags.
2784 * @return profile as defined by FF_PROFILE_H264_*
2786 int ff_h264_get_profile(SPS *sps)
2788 int profile = sps->profile_idc;
2790 switch (sps->profile_idc) {
2791 case FF_PROFILE_H264_BASELINE:
2792 // constraint_set1_flag set to 1
2793 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2795 case FF_PROFILE_H264_HIGH_10:
2796 case FF_PROFILE_H264_HIGH_422:
2797 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2798 // constraint_set3_flag set to 1
2799 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2806 static int h264_set_parameter_from_sps(H264Context *h)
2808 if (h->flags & CODEC_FLAG_LOW_DELAY ||
2809 (h->sps.bitstream_restriction_flag &&
2810 !h->sps.num_reorder_frames)) {
2811 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2812 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
2813 "Reenabling low delay requires a codec flush.\n");
2818 if (h->avctx->has_b_frames < 2)
2819 h->avctx->has_b_frames = !h->low_delay;
2821 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2822 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2823 if (h->avctx->codec &&
2824 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2825 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2826 av_log(h->avctx, AV_LOG_ERROR,
2827 "VDPAU decoding does not support video colorspace.\n");
2828 return AVERROR_INVALIDDATA;
2830 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
2831 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
2832 (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
2833 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2834 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2835 h->pixel_shift = h->sps.bit_depth_luma > 8;
2837 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2838 h->sps.chroma_format_idc);
2839 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2840 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2841 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
2842 h->sps.chroma_format_idc);
2843 h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2844 ff_dsputil_init(&h->dsp, h->avctx);
2845 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
2847 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2848 h->sps.bit_depth_luma);
2849 return AVERROR_INVALIDDATA;
2855 static enum PixelFormat get_pixel_format(H264Context *h, int force_callback)
2857 switch (h->sps.bit_depth_luma) {
2860 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2861 return AV_PIX_FMT_GBRP9;
2863 return AV_PIX_FMT_YUV444P9;
2864 } else if (CHROMA422)
2865 return AV_PIX_FMT_YUV422P9;
2867 return AV_PIX_FMT_YUV420P9;
2871 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2872 return AV_PIX_FMT_GBRP10;
2874 return AV_PIX_FMT_YUV444P10;
2875 } else if (CHROMA422)
2876 return AV_PIX_FMT_YUV422P10;
2878 return AV_PIX_FMT_YUV420P10;
2882 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2883 return AV_PIX_FMT_GBRP12;
2885 return AV_PIX_FMT_YUV444P12;
2886 } else if (CHROMA422)
2887 return AV_PIX_FMT_YUV422P12;
2889 return AV_PIX_FMT_YUV420P12;
2893 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2894 return AV_PIX_FMT_GBRP14;
2896 return AV_PIX_FMT_YUV444P14;
2897 } else if (CHROMA422)
2898 return AV_PIX_FMT_YUV422P14;
2900 return AV_PIX_FMT_YUV420P14;
2904 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2905 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
2906 return AV_PIX_FMT_GBR24P;
2907 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
2908 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
2910 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2911 : AV_PIX_FMT_YUV444P;
2912 } else if (CHROMA422) {
2913 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2914 : AV_PIX_FMT_YUV422P;
2917 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
2918 h->avctx->codec->pix_fmts :
2919 h->avctx->color_range == AVCOL_RANGE_JPEG ?
2920 hwaccel_pixfmt_list_h264_jpeg_420 :
2921 hwaccel_pixfmt_list_h264_420;
2923 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
2924 if (fmt[i] == h->avctx->pix_fmt && !force_callback)
2926 return h->avctx->get_format(h->avctx, fmt);
2930 av_log(h->avctx, AV_LOG_ERROR,
2931 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2932 return AVERROR_INVALIDDATA;
2936 static int h264_slice_header_init(H264Context *h, int reinit)
2938 int nb_slices = (HAVE_THREADS &&
2939 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
2940 h->avctx->thread_count : 1;
2943 if( FFALIGN(h->avctx->width , 16 ) == h->width
2944 && FFALIGN(h->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == h->height
2945 && !h->sps.crop_right && !h->sps.crop_bottom
2946 && (h->avctx->width != h->width || h->avctx->height && h->height)
2948 av_log(h->avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
2949 h->avctx->coded_width = h->width;
2950 h->avctx->coded_height = h->height;
2952 avcodec_set_dimensions(h->avctx, h->width, h->height);
2953 h->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
2954 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);
2957 h->avctx->sample_aspect_ratio = h->sps.sar;
2958 av_assert0(h->avctx->sample_aspect_ratio.den);
2959 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
2960 &h->chroma_x_shift, &h->chroma_y_shift);
2962 if (h->sps.timing_info_present_flag) {
2963 int64_t den = h->sps.time_scale;
2964 if (h->x264_build < 44U)
2966 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
2967 h->sps.num_units_in_tick, den, 1 << 30);
2970 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
2975 h->prev_interlaced_frame = 1;
2977 init_scan_tables(h);
2978 if (ff_h264_alloc_tables(h) < 0) {
2979 av_log(h->avctx, AV_LOG_ERROR,
2980 "Could not allocate memory for h264\n");
2981 return AVERROR(ENOMEM);
2984 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
2987 max_slices = FFMIN(MAX_THREADS, h->mb_height);
2989 max_slices = MAX_THREADS;
2990 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
2991 " reducing to %d\n", nb_slices, max_slices);
2992 nb_slices = max_slices;
2994 h->slice_context_count = nb_slices;
2996 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
2997 if (context_init(h) < 0) {
2998 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3002 for (i = 1; i < h->slice_context_count; i++) {
3004 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3005 c->avctx = h->avctx;
3008 c->h264dsp = h->h264dsp;
3009 c->h264qpel = h->h264qpel;
3010 c->h264chroma = h->h264chroma;
3013 c->pixel_shift = h->pixel_shift;
3014 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3015 c->width = h->width;
3016 c->height = h->height;
3017 c->linesize = h->linesize;
3018 c->uvlinesize = h->uvlinesize;
3019 c->chroma_x_shift = h->chroma_x_shift;
3020 c->chroma_y_shift = h->chroma_y_shift;
3021 c->qscale = h->qscale;
3022 c->droppable = h->droppable;
3023 c->data_partitioning = h->data_partitioning;
3024 c->low_delay = h->low_delay;
3025 c->mb_width = h->mb_width;
3026 c->mb_height = h->mb_height;
3027 c->mb_stride = h->mb_stride;
3028 c->mb_num = h->mb_num;
3029 c->flags = h->flags;
3030 c->workaround_bugs = h->workaround_bugs;
3031 c->pict_type = h->pict_type;
3033 init_scan_tables(c);
3034 clone_tables(c, h, i);
3035 c->context_initialized = 1;
3038 for (i = 0; i < h->slice_context_count; i++)
3039 if (context_init(h->thread_context[i]) < 0) {
3040 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3045 h->context_initialized = 1;
3051 * Decode a slice header.
3052 * This will also call ff_MPV_common_init() and frame_start() as needed.
3054 * @param h h264context
3055 * @param h0 h264 master context (differs from 'h' when doing sliced based
3056 * parallel decoding)
3058 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3060 static int decode_slice_header(H264Context *h, H264Context *h0)
3062 unsigned int first_mb_in_slice;
3063 unsigned int pps_id;
3064 int num_ref_idx_active_override_flag, ret;
3065 unsigned int slice_type, tmp, i, j;
3066 int default_ref_list_done = 0;
3067 int last_pic_structure, last_pic_droppable;
3069 int needs_reinit = 0;
3071 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3072 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3074 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3076 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3077 if (h0->current_slice && FIELD_PICTURE) {
3081 h0->current_slice = 0;
3082 if (!h0->first_field) {
3083 if (h->cur_pic_ptr && !h->droppable &&
3084 h->cur_pic_ptr->owner2 == h) {
3085 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
3086 h->picture_structure == PICT_BOTTOM_FIELD);
3088 h->cur_pic_ptr = NULL;
3092 slice_type = get_ue_golomb_31(&h->gb);
3093 if (slice_type > 9) {
3094 av_log(h->avctx, AV_LOG_ERROR,
3095 "slice type too large (%d) at %d %d\n",
3096 slice_type, h->mb_x, h->mb_y);
3099 if (slice_type > 4) {
3101 h->slice_type_fixed = 1;
3103 h->slice_type_fixed = 0;
3105 slice_type = golomb_to_pict_type[slice_type];
3106 if (slice_type == AV_PICTURE_TYPE_I ||
3107 (h0->current_slice != 0 &&
3108 slice_type == h0->last_slice_type &&
3109 !memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3110 default_ref_list_done = 1;
3112 h->slice_type = slice_type;
3113 h->slice_type_nos = slice_type & 3;
3115 // to make a few old functions happy, it's wrong though
3116 h->pict_type = h->slice_type;
3118 pps_id = get_ue_golomb(&h->gb);
3119 if (pps_id >= MAX_PPS_COUNT) {
3120 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3123 if (!h0->pps_buffers[pps_id]) {
3124 av_log(h->avctx, AV_LOG_ERROR,
3125 "non-existing PPS %u referenced\n",
3129 h->pps = *h0->pps_buffers[pps_id];
3131 if (!h0->sps_buffers[h->pps.sps_id]) {
3132 av_log(h->avctx, AV_LOG_ERROR,
3133 "non-existing SPS %u referenced\n",
3138 if (h->pps.sps_id != h->current_sps_id ||
3139 h0->sps_buffers[h->pps.sps_id]->new) {
3140 h0->sps_buffers[h->pps.sps_id]->new = 0;
3142 h->current_sps_id = h->pps.sps_id;
3143 h->sps = *h0->sps_buffers[h->pps.sps_id];
3145 if (h->mb_width != h->sps.mb_width ||
3146 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3147 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3148 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3152 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3153 h->chroma_format_idc != h->sps.chroma_format_idc) {
3154 h->bit_depth_luma = h->sps.bit_depth_luma;
3155 h->chroma_format_idc = h->sps.chroma_format_idc;
3158 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3162 h->avctx->profile = ff_h264_get_profile(&h->sps);
3163 h->avctx->level = h->sps.level_idc;
3164 h->avctx->refs = h->sps.ref_frame_count;
3166 must_reinit = (h->context_initialized &&
3167 ( 16*h->sps.mb_width != h->avctx->coded_width
3168 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3169 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3170 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3171 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)));
3172 if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3175 h->mb_width = h->sps.mb_width;
3176 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3177 h->mb_num = h->mb_width * h->mb_height;
3178 h->mb_stride = h->mb_width + 1;
3180 h->b_stride = h->mb_width * 4;
3182 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3184 h->width = 16 * h->mb_width;
3185 h->height = 16 * h->mb_height;
3187 if (h->sps.video_signal_type_present_flag) {
3188 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3190 if (h->sps.colour_description_present_flag) {
3191 if (h->avctx->colorspace != h->sps.colorspace)
3193 h->avctx->color_primaries = h->sps.color_primaries;
3194 h->avctx->color_trc = h->sps.color_trc;
3195 h->avctx->colorspace = h->sps.colorspace;
3199 if (h->context_initialized &&
3205 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3206 "slice %d\n", h0->current_slice + 1);
3207 return AVERROR_INVALIDDATA;
3212 if ((ret = get_pixel_format(h, 1)) < 0)
3214 h->avctx->pix_fmt = ret;
3216 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3217 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3219 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3220 av_log(h->avctx, AV_LOG_ERROR,
3221 "h264_slice_header_init() failed\n");
3225 if (!h->context_initialized) {
3227 av_log(h->avctx, AV_LOG_ERROR,
3228 "Cannot (re-)initialize context during parallel decoding.\n");
3232 if ((ret = get_pixel_format(h, 1)) < 0)
3234 h->avctx->pix_fmt = ret;
3236 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3237 av_log(h->avctx, AV_LOG_ERROR,
3238 "h264_slice_header_init() failed\n");
3243 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3244 h->dequant_coeff_pps = pps_id;
3245 init_dequant_tables(h);
3248 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3251 h->mb_aff_frame = 0;
3252 last_pic_structure = h0->picture_structure;
3253 last_pic_droppable = h0->droppable;
3254 h->droppable = h->nal_ref_idc == 0;
3255 if (h->sps.frame_mbs_only_flag) {
3256 h->picture_structure = PICT_FRAME;
3258 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3259 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3262 if (get_bits1(&h->gb)) { // field_pic_flag
3263 h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
3265 h->picture_structure = PICT_FRAME;
3266 h->mb_aff_frame = h->sps.mb_aff;
3269 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3271 if (h0->current_slice != 0) {
3272 if (last_pic_structure != h->picture_structure ||
3273 last_pic_droppable != h->droppable) {
3274 av_log(h->avctx, AV_LOG_ERROR,
3275 "Changing field mode (%d -> %d) between slices is not allowed\n",
3276 last_pic_structure, h->picture_structure);
3277 h->picture_structure = last_pic_structure;
3278 h->droppable = last_pic_droppable;
3279 return AVERROR_INVALIDDATA;
3280 } else if (!h0->cur_pic_ptr) {
3281 av_log(h->avctx, AV_LOG_ERROR,
3282 "unset cur_pic_ptr on %d. slice\n",
3283 h0->current_slice + 1);
3284 return AVERROR_INVALIDDATA;
3287 /* Shorten frame num gaps so we don't have to allocate reference
3288 * frames just to throw them away */
3289 if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
3290 int unwrap_prev_frame_num = h->prev_frame_num;
3291 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3293 if (unwrap_prev_frame_num > h->frame_num)
3294 unwrap_prev_frame_num -= max_frame_num;
3296 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3297 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3298 if (unwrap_prev_frame_num < 0)
3299 unwrap_prev_frame_num += max_frame_num;
3301 h->prev_frame_num = unwrap_prev_frame_num;
3305 /* See if we have a decoded first field looking for a pair...
3306 * Here, we're using that to see if we should mark previously
3307 * decode frames as "finished".
3308 * We have to do that before the "dummy" in-between frame allocation,
3309 * since that can modify h->cur_pic_ptr. */
3310 if (h0->first_field) {
3311 assert(h0->cur_pic_ptr);
3312 assert(h0->cur_pic_ptr->f.data[0]);
3313 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3315 /* Mark old field/frame as completed */
3316 if (!last_pic_droppable && h0->cur_pic_ptr->owner2 == h0) {
3317 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3318 last_pic_structure == PICT_BOTTOM_FIELD);
3321 /* figure out if we have a complementary field pair */
3322 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3323 /* Previous field is unmatched. Don't display it, but let it
3324 * remain for reference if marked as such. */
3325 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3326 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3327 last_pic_structure == PICT_TOP_FIELD);
3330 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3331 /* This and previous field were reference, but had
3332 * different frame_nums. Consider this field first in
3333 * pair. Throw away previous field except for reference
3335 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3336 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3337 last_pic_structure == PICT_TOP_FIELD);
3340 /* Second field in complementary pair */
3341 if (!((last_pic_structure == PICT_TOP_FIELD &&
3342 h->picture_structure == PICT_BOTTOM_FIELD) ||
3343 (last_pic_structure == PICT_BOTTOM_FIELD &&
3344 h->picture_structure == PICT_TOP_FIELD))) {
3345 av_log(h->avctx, AV_LOG_ERROR,
3346 "Invalid field mode combination %d/%d\n",
3347 last_pic_structure, h->picture_structure);
3348 h->picture_structure = last_pic_structure;
3349 h->droppable = last_pic_droppable;
3350 return AVERROR_INVALIDDATA;
3351 } else if (last_pic_droppable != h->droppable) {
3352 av_log(h->avctx, AV_LOG_ERROR,
3353 "Cannot combine reference and non-reference fields in the same frame\n");
3354 av_log_ask_for_sample(h->avctx, NULL);
3355 h->picture_structure = last_pic_structure;
3356 h->droppable = last_pic_droppable;
3357 return AVERROR_PATCHWELCOME;
3360 /* Take ownership of this buffer. Note that if another thread owned
3361 * the first field of this buffer, we're not operating on that pointer,
3362 * so the original thread is still responsible for reporting progress
3363 * on that first field (or if that was us, we just did that above).
3364 * By taking ownership, we assign responsibility to ourselves to
3365 * report progress on the second field. */
3366 h0->cur_pic_ptr->owner2 = h0;
3371 while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field &&
3372 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3373 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3374 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3375 h->frame_num, h->prev_frame_num);
3376 if (!h->sps.gaps_in_frame_num_allowed_flag)
3377 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3378 h->last_pocs[i] = INT_MIN;
3379 if (ff_h264_frame_start(h) < 0)
3381 h->prev_frame_num++;
3382 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3383 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3384 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 0);
3385 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 1);
3386 if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
3387 h->avctx->err_recognition & AV_EF_EXPLODE)
3389 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3390 (h->avctx->err_recognition & AV_EF_EXPLODE))
3391 return AVERROR_INVALIDDATA;
3392 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3393 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3394 * about there being no actual duplicates.
3395 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3396 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3398 if (h->short_ref_count) {
3400 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3401 (const uint8_t **)prev->f.data, prev->f.linesize,
3402 h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
3403 h->short_ref[0]->poc = prev->poc + 2;
3405 h->short_ref[0]->frame_num = h->prev_frame_num;
3409 /* See if we have a decoded first field looking for a pair...
3410 * We're using that to see whether to continue decoding in that
3411 * frame, or to allocate a new one. */
3412 if (h0->first_field) {
3413 assert(h0->cur_pic_ptr);
3414 assert(h0->cur_pic_ptr->f.data[0]);
3415 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3417 /* figure out if we have a complementary field pair */
3418 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3419 /* Previous field is unmatched. Don't display it, but let it
3420 * remain for reference if marked as such. */
3421 h0->cur_pic_ptr = NULL;
3422 h0->first_field = FIELD_PICTURE;
3424 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3425 ff_thread_report_progress((AVFrame*)h0->cur_pic_ptr, INT_MAX,
3426 h0->picture_structure==PICT_BOTTOM_FIELD);
3427 /* This and the previous field had different frame_nums.
3428 * Consider this field first in pair. Throw away previous
3429 * one except for reference purposes. */
3430 h0->first_field = 1;
3431 h0->cur_pic_ptr = NULL;
3433 /* Second field in complementary pair */
3434 h0->first_field = 0;
3438 /* Frame or first field in a potentially complementary pair */
3439 h0->first_field = FIELD_PICTURE;
3442 if (!FIELD_PICTURE || h0->first_field) {
3443 if (ff_h264_frame_start(h) < 0) {
3444 h0->first_field = 0;
3448 release_unused_pictures(h, 0);
3451 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3454 /* can't be in alloc_tables because linesize isn't known there.
3455 * FIXME: redo bipred weight to not require extra buffer? */
3456 for (i = 0; i < h->slice_context_count; i++)
3457 if (h->thread_context[i]) {
3458 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
3463 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3465 av_assert1(h->mb_num == h->mb_width * h->mb_height);
3466 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= h->mb_num ||
3467 first_mb_in_slice >= h->mb_num) {
3468 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3471 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3472 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE;
3473 if (h->picture_structure == PICT_BOTTOM_FIELD)
3474 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3475 av_assert1(h->mb_y < h->mb_height);
3477 if (h->picture_structure == PICT_FRAME) {
3478 h->curr_pic_num = h->frame_num;
3479 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3481 h->curr_pic_num = 2 * h->frame_num + 1;
3482 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3485 if (h->nal_unit_type == NAL_IDR_SLICE)
3486 get_ue_golomb(&h->gb); /* idr_pic_id */
3488 if (h->sps.poc_type == 0) {
3489 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3491 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3492 h->delta_poc_bottom = get_se_golomb(&h->gb);
3495 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3496 h->delta_poc[0] = get_se_golomb(&h->gb);
3498 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3499 h->delta_poc[1] = get_se_golomb(&h->gb);
3504 if (h->pps.redundant_pic_cnt_present)
3505 h->redundant_pic_count = get_ue_golomb(&h->gb);
3507 // set defaults, might be overridden a few lines later
3508 h->ref_count[0] = h->pps.ref_count[0];
3509 h->ref_count[1] = h->pps.ref_count[1];
3511 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3513 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3515 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3516 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3517 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3519 if (num_ref_idx_active_override_flag) {
3520 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3521 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3522 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3524 // full range is spec-ok in this case, even for frames
3525 h->ref_count[1] = 1;
3528 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3529 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]);
3530 h->ref_count[0] = h->ref_count[1] = 1;
3531 return AVERROR_INVALIDDATA;
3534 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3539 h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
3541 if (!default_ref_list_done)
3542 ff_h264_fill_default_ref_list(h);
3544 if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
3545 ff_h264_decode_ref_pic_list_reordering(h) < 0) {
3546 h->ref_count[1] = h->ref_count[0] = 0;
3550 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3551 (h->pps.weighted_bipred_idc == 1 &&
3552 h->slice_type_nos == AV_PICTURE_TYPE_B))
3553 pred_weight_table(h);
3554 else if (h->pps.weighted_bipred_idc == 2 &&
3555 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3556 implicit_weight_table(h, -1);
3559 for (i = 0; i < 2; i++) {
3560 h->luma_weight_flag[i] = 0;
3561 h->chroma_weight_flag[i] = 0;
3565 // If frame-mt is enabled, only update mmco tables for the first slice
3566 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3567 // or h->mmco, which will cause ref list mix-ups and decoding errors
3568 // further down the line. This may break decoding if the first slice is
3569 // corrupt, thus we only do this if frame-mt is enabled.
3570 if (h->nal_ref_idc &&
3571 ff_h264_decode_ref_pic_marking(h0, &h->gb,
3572 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3573 h0->current_slice == 0) < 0 &&
3574 (h->avctx->err_recognition & AV_EF_EXPLODE))
3575 return AVERROR_INVALIDDATA;
3578 ff_h264_fill_mbaff_ref_list(h);
3580 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3581 implicit_weight_table(h, 0);
3582 implicit_weight_table(h, 1);
3586 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3587 ff_h264_direct_dist_scale_factor(h);
3588 ff_h264_direct_ref_list_init(h);
3590 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3591 tmp = get_ue_golomb_31(&h->gb);
3593 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3596 h->cabac_init_idc = tmp;
3599 h->last_qscale_diff = 0;
3600 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3601 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3602 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3606 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3607 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3608 // FIXME qscale / qp ... stuff
3609 if (h->slice_type == AV_PICTURE_TYPE_SP)
3610 get_bits1(&h->gb); /* sp_for_switch_flag */
3611 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3612 h->slice_type == AV_PICTURE_TYPE_SI)
3613 get_se_golomb(&h->gb); /* slice_qs_delta */
3615 h->deblocking_filter = 1;
3616 h->slice_alpha_c0_offset = 52;
3617 h->slice_beta_offset = 52;
3618 if (h->pps.deblocking_filter_parameters_present) {
3619 tmp = get_ue_golomb_31(&h->gb);
3621 av_log(h->avctx, AV_LOG_ERROR,
3622 "deblocking_filter_idc %u out of range\n", tmp);
3625 h->deblocking_filter = tmp;
3626 if (h->deblocking_filter < 2)
3627 h->deblocking_filter ^= 1; // 1<->0
3629 if (h->deblocking_filter) {
3630 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3631 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3632 if (h->slice_alpha_c0_offset > 104U ||
3633 h->slice_beta_offset > 104U) {
3634 av_log(h->avctx, AV_LOG_ERROR,
3635 "deblocking filter parameters %d %d out of range\n",
3636 h->slice_alpha_c0_offset, h->slice_beta_offset);
3642 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3643 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3644 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3645 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3646 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3647 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3648 h->nal_ref_idc == 0))
3649 h->deblocking_filter = 0;
3651 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3652 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3653 /* Cheat slightly for speed:
3654 * Do not bother to deblock across slices. */
3655 h->deblocking_filter = 2;
3657 h0->max_contexts = 1;
3658 if (!h0->single_decode_warning) {
3659 av_log(h->avctx, AV_LOG_INFO,
3660 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3661 h0->single_decode_warning = 1;
3664 av_log(h->avctx, AV_LOG_ERROR,
3665 "Deblocking switched inside frame.\n");
3670 h->qp_thresh = 15 + 52 -
3671 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3673 h->pps.chroma_qp_index_offset[0],
3674 h->pps.chroma_qp_index_offset[1]) +
3675 6 * (h->sps.bit_depth_luma - 8);
3677 h0->last_slice_type = slice_type;
3678 memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
3679 h->slice_num = ++h0->current_slice;
3682 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
3683 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
3684 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
3685 && h->slice_num >= MAX_SLICES) {
3686 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3687 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);
3690 for (j = 0; j < 2; j++) {
3692 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3693 for (i = 0; i < 16; i++) {
3695 if (h->ref_list[j][i].f.data[0]) {
3697 uint8_t *base = h->ref_list[j][i].f.base[0];
3698 for (k = 0; k < h->short_ref_count; k++)
3699 if (h->short_ref[k]->f.base[0] == base) {
3703 for (k = 0; k < h->long_ref_count; k++)
3704 if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
3705 id_list[i] = h->short_ref_count + k;
3713 for (i = 0; i < 16; i++)
3714 ref2frm[i + 2] = 4 * id_list[i] +
3715 (h->ref_list[j][i].f.reference & 3);
3717 ref2frm[18 + 1] = -1;
3718 for (i = 16; i < 48; i++)
3719 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3720 (h->ref_list[j][i].f.reference & 3);
3723 if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
3724 if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
3726 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
3727 av_log(h->avctx, AV_LOG_DEBUG,
3728 "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",
3730 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3732 av_get_picture_type_char(h->slice_type),
3733 h->slice_type_fixed ? " fix" : "",
3734 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3735 pps_id, h->frame_num,
3736 h->cur_pic_ptr->field_poc[0],
3737 h->cur_pic_ptr->field_poc[1],
3738 h->ref_count[0], h->ref_count[1],
3740 h->deblocking_filter,
3741 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3743 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3744 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3750 int ff_h264_get_slice_type(const H264Context *h)
3752 switch (h->slice_type) {
3753 case AV_PICTURE_TYPE_P:
3755 case AV_PICTURE_TYPE_B:
3757 case AV_PICTURE_TYPE_I:
3759 case AV_PICTURE_TYPE_SP:
3761 case AV_PICTURE_TYPE_SI:
3768 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3769 int mb_type, int top_xy,
3770 int left_xy[LEFT_MBS],
3772 int left_type[LEFT_MBS],
3773 int mb_xy, int list)
3775 int b_stride = h->b_stride;
3776 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3777 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3778 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3779 if (USES_LIST(top_type, list)) {
3780 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3781 const int b8_xy = 4 * top_xy + 2;
3782 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3783 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.f.motion_val[list][b_xy + 0]);
3784 ref_cache[0 - 1 * 8] =
3785 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 0]];
3786 ref_cache[2 - 1 * 8] =
3787 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 1]];
3789 AV_ZERO128(mv_dst - 1 * 8);
3790 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3793 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3794 if (USES_LIST(left_type[LTOP], list)) {
3795 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3796 const int b8_xy = 4 * left_xy[LTOP] + 1;
3797 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3798 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.f.motion_val[list][b_xy + b_stride * 0]);
3799 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.f.motion_val[list][b_xy + b_stride * 1]);
3800 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.f.motion_val[list][b_xy + b_stride * 2]);
3801 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.f.motion_val[list][b_xy + b_stride * 3]);
3803 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 0]];
3804 ref_cache[-1 + 16] =
3805 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 1]];
3807 AV_ZERO32(mv_dst - 1 + 0);
3808 AV_ZERO32(mv_dst - 1 + 8);
3809 AV_ZERO32(mv_dst - 1 + 16);
3810 AV_ZERO32(mv_dst - 1 + 24);
3813 ref_cache[-1 + 16] =
3814 ref_cache[-1 + 24] = LIST_NOT_USED;
3819 if (!USES_LIST(mb_type, list)) {
3820 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3821 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3822 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3823 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3824 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3829 int8_t *ref = &h->cur_pic.f.ref_index[list][4 * mb_xy];
3830 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
3831 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3832 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3833 AV_WN32A(&ref_cache[0 * 8], ref01);
3834 AV_WN32A(&ref_cache[1 * 8], ref01);
3835 AV_WN32A(&ref_cache[2 * 8], ref23);
3836 AV_WN32A(&ref_cache[3 * 8], ref23);
3840 int16_t(*mv_src)[2] = &h->cur_pic.f.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
3841 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3842 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3843 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3844 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3850 * @return non zero if the loop filter can be skipped
3852 static int fill_filter_caches(H264Context *h, int mb_type)
3854 const int mb_xy = h->mb_xy;
3855 int top_xy, left_xy[LEFT_MBS];
3856 int top_type, left_type[LEFT_MBS];
3860 top_xy = mb_xy - (h->mb_stride << MB_FIELD);
3862 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3863 * stuff, I can't imagine that these complex rules are worth it. */
3865 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3867 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.f.mb_type[mb_xy - 1]);
3868 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3870 if (left_mb_field_flag != curr_mb_field_flag)
3871 left_xy[LTOP] -= h->mb_stride;
3873 if (curr_mb_field_flag)
3874 top_xy += h->mb_stride &
3875 (((h->cur_pic.f.mb_type[top_xy] >> 7) & 1) - 1);
3876 if (left_mb_field_flag != curr_mb_field_flag)
3877 left_xy[LBOT] += h->mb_stride;
3881 h->top_mb_xy = top_xy;
3882 h->left_mb_xy[LTOP] = left_xy[LTOP];
3883 h->left_mb_xy[LBOT] = left_xy[LBOT];
3885 /* For sufficiently low qp, filtering wouldn't do anything.
3886 * This is a conservative estimate: could also check beta_offset
3887 * and more accurate chroma_qp. */
3888 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
3889 int qp = h->cur_pic.f.qscale_table[mb_xy];
3890 if (qp <= qp_thresh &&
3891 (left_xy[LTOP] < 0 ||
3892 ((qp + h->cur_pic.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
3894 ((qp + h->cur_pic.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
3897 if ((left_xy[LTOP] < 0 ||
3898 ((qp + h->cur_pic.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
3899 (top_xy < h->mb_stride ||
3900 ((qp + h->cur_pic.f.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
3905 top_type = h->cur_pic.f.mb_type[top_xy];
3906 left_type[LTOP] = h->cur_pic.f.mb_type[left_xy[LTOP]];
3907 left_type[LBOT] = h->cur_pic.f.mb_type[left_xy[LBOT]];
3908 if (h->deblocking_filter == 2) {
3909 if (h->slice_table[top_xy] != h->slice_num)
3911 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
3912 left_type[LTOP] = left_type[LBOT] = 0;
3914 if (h->slice_table[top_xy] == 0xFFFF)
3916 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
3917 left_type[LTOP] = left_type[LBOT] = 0;
3919 h->top_type = top_type;
3920 h->left_type[LTOP] = left_type[LTOP];
3921 h->left_type[LBOT] = left_type[LBOT];
3923 if (IS_INTRA(mb_type))
3926 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
3927 top_type, left_type, mb_xy, 0);
3928 if (h->list_count == 2)
3929 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
3930 top_type, left_type, mb_xy, 1);
3932 nnz = h->non_zero_count[mb_xy];
3933 nnz_cache = h->non_zero_count_cache;
3934 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
3935 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
3936 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
3937 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
3938 h->cbp = h->cbp_table[mb_xy];
3941 nnz = h->non_zero_count[top_xy];
3942 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
3945 if (left_type[LTOP]) {
3946 nnz = h->non_zero_count[left_xy[LTOP]];
3947 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
3948 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
3949 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
3950 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
3953 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
3954 * from what the loop filter needs */
3955 if (!CABAC && h->pps.transform_8x8_mode) {
3956 if (IS_8x8DCT(top_type)) {
3957 nnz_cache[4 + 8 * 0] =
3958 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
3959 nnz_cache[6 + 8 * 0] =
3960 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
3962 if (IS_8x8DCT(left_type[LTOP])) {
3963 nnz_cache[3 + 8 * 1] =
3964 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
3966 if (IS_8x8DCT(left_type[LBOT])) {
3967 nnz_cache[3 + 8 * 3] =
3968 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
3971 if (IS_8x8DCT(mb_type)) {
3972 nnz_cache[scan8[0]] =
3973 nnz_cache[scan8[1]] =
3974 nnz_cache[scan8[2]] =
3975 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
3977 nnz_cache[scan8[0 + 4]] =
3978 nnz_cache[scan8[1 + 4]] =
3979 nnz_cache[scan8[2 + 4]] =
3980 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
3982 nnz_cache[scan8[0 + 8]] =
3983 nnz_cache[scan8[1 + 8]] =
3984 nnz_cache[scan8[2 + 8]] =
3985 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
3987 nnz_cache[scan8[0 + 12]] =
3988 nnz_cache[scan8[1 + 12]] =
3989 nnz_cache[scan8[2 + 12]] =
3990 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
3997 static void loop_filter(H264Context *h, int start_x, int end_x)
3999 uint8_t *dest_y, *dest_cb, *dest_cr;
4000 int linesize, uvlinesize, mb_x, mb_y;
4001 const int end_mb_y = h->mb_y + FRAME_MBAFF;
4002 const int old_slice_type = h->slice_type;
4003 const int pixel_shift = h->pixel_shift;
4004 const int block_h = 16 >> h->chroma_y_shift;
4006 if (h->deblocking_filter) {
4007 for (mb_x = start_x; mb_x < end_x; mb_x++)
4008 for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
4010 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4011 h->slice_num = h->slice_table[mb_xy];
4012 mb_type = h->cur_pic.f.mb_type[mb_xy];
4013 h->list_count = h->list_counts[mb_xy];
4017 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4021 dest_y = h->cur_pic.f.data[0] +
4022 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4023 dest_cb = h->cur_pic.f.data[1] +
4024 (mb_x << pixel_shift) * (8 << CHROMA444) +
4025 mb_y * h->uvlinesize * block_h;
4026 dest_cr = h->cur_pic.f.data[2] +
4027 (mb_x << pixel_shift) * (8 << CHROMA444) +
4028 mb_y * h->uvlinesize * block_h;
4029 // FIXME simplify above
4032 linesize = h->mb_linesize = h->linesize * 2;
4033 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4034 if (mb_y & 1) { // FIXME move out of this function?
4035 dest_y -= h->linesize * 15;
4036 dest_cb -= h->uvlinesize * (block_h - 1);
4037 dest_cr -= h->uvlinesize * (block_h - 1);
4040 linesize = h->mb_linesize = h->linesize;
4041 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4043 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4045 if (fill_filter_caches(h, mb_type))
4047 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.f.qscale_table[mb_xy]);
4048 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.f.qscale_table[mb_xy]);
4051 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4052 linesize, uvlinesize);
4054 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4055 dest_cr, linesize, uvlinesize);
4059 h->slice_type = old_slice_type;
4061 h->mb_y = end_mb_y - FRAME_MBAFF;
4062 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4063 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4066 static void predict_field_decoding_flag(H264Context *h)
4068 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4069 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4070 h->cur_pic.f.mb_type[mb_xy - 1] :
4071 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4072 h->cur_pic.f.mb_type[mb_xy - h->mb_stride] : 0;
4073 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4077 * Draw edges and report progress for the last MB row.
4079 static void decode_finish_row(H264Context *h)
4081 int top = 16 * (h->mb_y >> FIELD_PICTURE);
4082 int pic_height = 16 * h->mb_height >> FIELD_PICTURE;
4083 int height = 16 << FRAME_MBAFF;
4084 int deblock_border = (16 + 4) << FRAME_MBAFF;
4086 if (h->deblocking_filter) {
4087 if ((top + height) >= pic_height)
4088 height += deblock_border;
4089 top -= deblock_border;
4092 if (top >= pic_height || (top + height) < 0)
4095 height = FFMIN(height, pic_height - top);
4097 height = top + height;
4101 ff_h264_draw_horiz_band(h, top, height);
4106 ff_thread_report_progress(&h->cur_pic_ptr->f, top + height - 1,
4107 h->picture_structure == PICT_BOTTOM_FIELD);
4110 static void er_add_slice(H264Context *h, int startx, int starty,
4111 int endx, int endy, int status)
4113 ERContext *er = &h->er;
4115 er->ref_count = h->ref_count[0];
4116 ff_er_add_slice(er, startx, starty, endx, endy, status);
4119 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4121 H264Context *h = *(void **)arg;
4122 int lf_x_start = h->mb_x;
4124 h->mb_skip_run = -1;
4126 av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4128 h->is_complex = FRAME_MBAFF || h->picture_structure != PICT_FRAME ||
4129 avctx->codec_id != AV_CODEC_ID_H264 ||
4130 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4134 align_get_bits(&h->gb);
4137 ff_init_cabac_decoder(&h->cabac,
4138 h->gb.buffer + get_bits_count(&h->gb) / 8,
4139 (get_bits_left(&h->gb) + 7) / 8);
4141 ff_h264_init_cabac_states(h);
4145 int ret = ff_h264_decode_mb_cabac(h);
4147 // STOP_TIMER("decode_mb_cabac")
4150 ff_h264_hl_decode_mb(h);
4152 // FIXME optimal? or let mb_decode decode 16x32 ?
4153 if (ret >= 0 && FRAME_MBAFF) {
4156 ret = ff_h264_decode_mb_cabac(h);
4159 ff_h264_hl_decode_mb(h);
4162 eos = get_cabac_terminate(&h->cabac);
4164 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4165 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4166 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4167 h->mb_y, ER_MB_END);
4168 if (h->mb_x >= lf_x_start)
4169 loop_filter(h, lf_x_start, h->mb_x + 1);
4172 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4173 av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4174 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4175 av_log(h->avctx, AV_LOG_ERROR,
4176 "error while decoding MB %d %d, bytestream (%td)\n",
4178 h->cabac.bytestream_end - h->cabac.bytestream);
4179 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4180 h->mb_y, ER_MB_ERROR);
4184 if (++h->mb_x >= h->mb_width) {
4185 loop_filter(h, lf_x_start, h->mb_x);
4186 h->mb_x = lf_x_start = 0;
4187 decode_finish_row(h);
4189 if (FIELD_OR_MBAFF_PICTURE) {
4191 if (FRAME_MBAFF && h->mb_y < h->mb_height)
4192 predict_field_decoding_flag(h);
4196 if (eos || h->mb_y >= h->mb_height) {
4197 tprintf(h->avctx, "slice end %d %d\n",
4198 get_bits_count(&h->gb), h->gb.size_in_bits);
4199 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4200 h->mb_y, ER_MB_END);
4201 if (h->mb_x > lf_x_start)
4202 loop_filter(h, lf_x_start, h->mb_x);
4208 int ret = ff_h264_decode_mb_cavlc(h);
4211 ff_h264_hl_decode_mb(h);
4213 // FIXME optimal? or let mb_decode decode 16x32 ?
4214 if (ret >= 0 && FRAME_MBAFF) {
4216 ret = ff_h264_decode_mb_cavlc(h);
4219 ff_h264_hl_decode_mb(h);
4224 av_log(h->avctx, AV_LOG_ERROR,
4225 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4226 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4227 h->mb_y, ER_MB_ERROR);
4231 if (++h->mb_x >= h->mb_width) {
4232 loop_filter(h, lf_x_start, h->mb_x);
4233 h->mb_x = lf_x_start = 0;
4234 decode_finish_row(h);
4236 if (FIELD_OR_MBAFF_PICTURE) {
4238 if (FRAME_MBAFF && h->mb_y < h->mb_height)
4239 predict_field_decoding_flag(h);
4241 if (h->mb_y >= h->mb_height) {
4242 tprintf(h->avctx, "slice end %d %d\n",
4243 get_bits_count(&h->gb), h->gb.size_in_bits);
4245 if ( get_bits_left(&h->gb) == 0
4246 || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4247 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4248 h->mb_x - 1, h->mb_y,
4253 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4262 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4263 tprintf(h->avctx, "slice end %d %d\n",
4264 get_bits_count(&h->gb), h->gb.size_in_bits);
4265 if (get_bits_left(&h->gb) == 0) {
4266 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4267 h->mb_x - 1, h->mb_y,
4269 if (h->mb_x > lf_x_start)
4270 loop_filter(h, lf_x_start, h->mb_x);
4274 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4275 h->mb_y, ER_MB_ERROR);
4285 * Call decode_slice() for each context.
4287 * @param h h264 master context
4288 * @param context_count number of contexts to execute
4290 static int execute_decode_slices(H264Context *h, int context_count)
4292 AVCodecContext *const avctx = h->avctx;
4296 if (h->avctx->hwaccel ||
4297 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4299 if (context_count == 1) {
4300 return decode_slice(avctx, &h);
4302 av_assert0(context_count > 0);
4303 for (i = 1; i < context_count; i++) {
4304 hx = h->thread_context[i];
4305 hx->er.error_count = 0;
4306 hx->x264_build = h->x264_build;
4309 avctx->execute(avctx, decode_slice, h->thread_context,
4310 NULL, context_count, sizeof(void *));
4312 /* pull back stuff from slices to master context */
4313 hx = h->thread_context[context_count - 1];
4316 h->droppable = hx->droppable;
4317 h->picture_structure = hx->picture_structure;
4318 for (i = 1; i < context_count; i++)
4319 h->er.error_count += h->thread_context[i]->er.error_count;
4325 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4326 int parse_extradata)
4328 AVCodecContext *const avctx = h->avctx;
4329 H264Context *hx; ///< thread context
4333 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4334 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4337 int first_slice = 0;
4339 h->nal_unit_type= 0;
4341 if(!h->slice_context_count)
4342 h->slice_context_count= 1;
4343 h->max_contexts = h->slice_context_count;
4344 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4345 h->current_slice = 0;
4346 if (!h->first_field)
4347 h->cur_pic_ptr = NULL;
4348 ff_h264_reset_sei(h);
4351 if (h->nal_length_size == 4) {
4352 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4354 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4358 for (; pass <= 1; pass++) {
4361 next_avc = h->is_avc ? 0 : buf_size;
4371 if (buf_index >= next_avc) {
4372 if (buf_index >= buf_size - h->nal_length_size)
4375 for (i = 0; i < h->nal_length_size; i++)
4376 nalsize = (nalsize << 8) | buf[buf_index++];
4377 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4378 av_log(h->avctx, AV_LOG_ERROR,
4379 "AVC: nal size %d\n", nalsize);
4382 next_avc = buf_index + nalsize;
4384 // start code prefix search
4385 for (; buf_index + 3 < next_avc; buf_index++)
4386 // This should always succeed in the first iteration.
4387 if (buf[buf_index] == 0 &&
4388 buf[buf_index + 1] == 0 &&
4389 buf[buf_index + 2] == 1)
4392 if (buf_index + 3 >= buf_size) {
4393 buf_index = buf_size;
4398 if (buf_index >= next_avc)
4402 hx = h->thread_context[context_count];
4404 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4405 &consumed, next_avc - buf_index);
4406 if (ptr == NULL || dst_length < 0) {
4410 i = buf_index + consumed;
4411 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4412 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4413 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4414 h->workaround_bugs |= FF_BUG_TRUNCATED;
4416 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4417 while(dst_length > 0 && ptr[dst_length - 1] == 0)
4419 bit_length = !dst_length ? 0
4421 decode_rbsp_trailing(h, ptr + dst_length - 1));
4423 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4424 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);
4426 if (h->is_avc && (nalsize != consumed) && nalsize)
4427 av_log(h->avctx, AV_LOG_DEBUG,
4428 "AVC: Consumed only %d bytes instead of %d\n",
4431 buf_index += consumed;
4435 /* packets can sometimes contain multiple PPS/SPS,
4436 * e.g. two PAFF field pictures in one packet, or a demuxer
4437 * which splits NALs strangely if so, when frame threading we
4438 * can't start the next thread until we've read all of them */
4439 switch (hx->nal_unit_type) {
4442 nals_needed = nal_index;
4447 init_get_bits(&hx->gb, ptr, bit_length);
4448 if (!get_ue_golomb(&hx->gb) || !first_slice)
4449 nals_needed = nal_index;
4451 first_slice = hx->nal_unit_type;
4457 switch (hx->nal_unit_type) {
4461 first_slice = hx->nal_unit_type;
4464 // FIXME do not discard SEI id
4465 if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
4469 /* Ignore per frame NAL unit type during extradata
4470 * parsing. Decoding slices is not possible in codec init
4472 if (parse_extradata) {
4473 switch (hx->nal_unit_type) {
4479 case NAL_AUXILIARY_SLICE:
4480 av_log(h->avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header/extradata\n", hx->nal_unit_type);
4481 hx->nal_unit_type = NAL_FF_IGNORE;
4487 switch (hx->nal_unit_type) {
4489 if (first_slice != NAL_IDR_SLICE) {
4490 av_log(h->avctx, AV_LOG_ERROR,
4491 "Invalid mix of idr and non-idr slices\n");
4496 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4499 init_get_bits(&hx->gb, ptr, bit_length);
4501 hx->inter_gb_ptr = &hx->gb;
4502 hx->data_partitioning = 0;
4504 if ((err = decode_slice_header(hx, h)))
4507 if (h->sei_recovery_frame_cnt >= 0 && (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I))
4508 h->valid_recovery_point = 1;
4510 if ( h->sei_recovery_frame_cnt >= 0
4511 && ( h->recovery_frame<0
4512 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
4513 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
4514 (1 << h->sps.log2_max_frame_num);
4516 if (!h->valid_recovery_point)
4517 h->recovery_frame = h->frame_num;
4520 h->cur_pic_ptr->f.key_frame |=
4521 (hx->nal_unit_type == NAL_IDR_SLICE);
4523 if (h->recovery_frame == h->frame_num) {
4524 h->cur_pic_ptr->sync |= 1;
4525 h->recovery_frame = -1;
4528 h->sync |= !!h->cur_pic_ptr->f.key_frame;
4529 h->sync |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
4530 h->cur_pic_ptr->sync |= h->sync;
4532 if (h->current_slice == 1) {
4533 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4534 decode_postinit(h, nal_index >= nals_needed);
4536 if (h->avctx->hwaccel &&
4537 h->avctx->hwaccel->start_frame(h->avctx, NULL, 0) < 0)
4539 if (CONFIG_H264_VDPAU_DECODER &&
4540 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4541 ff_vdpau_h264_picture_start(h);
4544 if (hx->redundant_pic_count == 0 &&
4545 (avctx->skip_frame < AVDISCARD_NONREF ||
4547 (avctx->skip_frame < AVDISCARD_BIDIR ||
4548 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4549 (avctx->skip_frame < AVDISCARD_NONKEY ||
4550 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4551 avctx->skip_frame < AVDISCARD_ALL) {
4552 if (avctx->hwaccel) {
4553 if (avctx->hwaccel->decode_slice(avctx,
4554 &buf[buf_index - consumed],
4557 } else if (CONFIG_H264_VDPAU_DECODER &&
4558 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4559 static const uint8_t start_code[] = {
4561 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], start_code,
4562 sizeof(start_code));
4563 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], &buf[buf_index - consumed],
4570 init_get_bits(&hx->gb, ptr, bit_length);
4572 hx->inter_gb_ptr = NULL;
4574 if ((err = decode_slice_header(hx, h)) < 0)
4577 hx->data_partitioning = 1;
4580 init_get_bits(&hx->intra_gb, ptr, bit_length);
4581 hx->intra_gb_ptr = &hx->intra_gb;
4584 init_get_bits(&hx->inter_gb, ptr, bit_length);
4585 hx->inter_gb_ptr = &hx->inter_gb;
4587 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
4590 if (hx->redundant_pic_count == 0 &&
4592 hx->data_partitioning &&
4593 h->cur_pic_ptr && h->context_initialized &&
4594 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4595 (avctx->skip_frame < AVDISCARD_BIDIR ||
4596 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4597 (avctx->skip_frame < AVDISCARD_NONKEY ||
4598 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4599 avctx->skip_frame < AVDISCARD_ALL)
4603 init_get_bits(&h->gb, ptr, bit_length);
4604 ff_h264_decode_sei(h);
4607 init_get_bits(&h->gb, ptr, bit_length);
4608 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
4609 av_log(h->avctx, AV_LOG_DEBUG,
4610 "SPS decoding failure, trying again with the complete NAL\n");
4612 av_assert0(next_avc - buf_index + consumed == nalsize);
4613 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
4615 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
4616 8*(next_avc - buf_index + consumed - 1));
4617 ff_h264_decode_seq_parameter_set(h);
4622 init_get_bits(&h->gb, ptr, bit_length);
4623 ff_h264_decode_picture_parameter_set(h, bit_length);
4626 case NAL_END_SEQUENCE:
4627 case NAL_END_STREAM:
4628 case NAL_FILLER_DATA:
4630 case NAL_AUXILIARY_SLICE:
4635 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4636 hx->nal_unit_type, bit_length);
4639 if (context_count == h->max_contexts) {
4640 execute_decode_slices(h, context_count);
4645 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4646 else if (err == 1) {
4647 /* Slice could not be decoded in parallel mode, copy down
4648 * NAL unit stuff to context 0 and restart. Note that
4649 * rbsp_buffer is not transferred, but since we no longer
4650 * run in parallel mode this should not be an issue. */
4651 h->nal_unit_type = hx->nal_unit_type;
4652 h->nal_ref_idc = hx->nal_ref_idc;
4659 execute_decode_slices(h, context_count);
4663 if (h->cur_pic_ptr && h->cur_pic_ptr->owner2 == h &&
4665 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
4666 h->picture_structure == PICT_BOTTOM_FIELD);
4673 * Return the number of bytes consumed for building the current frame.
4675 static int get_consumed_bytes(int pos, int buf_size)
4678 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4679 if (pos + 10 > buf_size)
4680 pos = buf_size; // oops ;)
4685 static int decode_frame(AVCodecContext *avctx, void *data,
4686 int *got_frame, AVPacket *avpkt)
4688 const uint8_t *buf = avpkt->data;
4689 int buf_size = avpkt->size;
4690 H264Context *h = avctx->priv_data;
4691 AVFrame *pict = data;
4696 h->flags = avctx->flags;
4698 /* end of stream, output what is still in the buffers */
4699 if (buf_size == 0) {
4702 h->cur_pic_ptr = NULL;
4705 // FIXME factorize this with the output code below
4706 out = h->delayed_pic[0];
4709 h->delayed_pic[i] &&
4710 !h->delayed_pic[i]->f.key_frame &&
4711 !h->delayed_pic[i]->mmco_reset;
4713 if (h->delayed_pic[i]->poc < out->poc) {
4714 out = h->delayed_pic[i];
4718 for (i = out_idx; h->delayed_pic[i]; i++)
4719 h->delayed_pic[i] = h->delayed_pic[i + 1];
4722 out->f.reference &= ~DELAYED_PIC_REF;
4729 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
4730 int cnt= buf[5]&0x1f;
4731 const uint8_t *p= buf+6;
4733 int nalsize= AV_RB16(p) + 2;
4734 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
4742 int nalsize= AV_RB16(p) + 2;
4743 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
4748 return ff_h264_decode_extradata(h, buf, buf_size);
4752 buf_index = decode_nal_units(h, buf, buf_size, 0);
4756 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4757 av_assert0(buf_index <= buf_size);
4761 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
4762 if (avctx->skip_frame >= AVDISCARD_NONREF ||
4763 buf_size >= 4 && !memcmp("Q264", buf, 4))
4765 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4769 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
4770 (h->mb_y >= h->mb_height && h->mb_height)) {
4771 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
4772 decode_postinit(h, 1);
4776 /* Wait for second field. */
4778 if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
4780 *pict = h->next_output_pic->f;
4784 assert(pict->data[0] || !*got_frame);
4786 ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table, h->visualization_buffer, &h->low_delay,
4787 h->mb_width, h->mb_height, h->mb_stride, 1);
4789 return get_consumed_bytes(buf_index, buf_size);
4792 av_cold void ff_h264_free_context(H264Context *h)
4796 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4798 for (i = 0; i < MAX_SPS_COUNT; i++)
4799 av_freep(h->sps_buffers + i);
4801 for (i = 0; i < MAX_PPS_COUNT; i++)
4802 av_freep(h->pps_buffers + i);
4805 static av_cold int h264_decode_end(AVCodecContext *avctx)
4807 H264Context *h = avctx->priv_data;
4810 ff_h264_remove_all_refs(h);
4811 ff_h264_free_context(h);
4813 if (h->DPB && !h->avctx->internal->is_copy) {
4814 for (i = 0; i < h->picture_count; i++) {
4815 free_picture(h, &h->DPB[i]);
4823 static const AVProfile profiles[] = {
4824 { FF_PROFILE_H264_BASELINE, "Baseline" },
4825 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4826 { FF_PROFILE_H264_MAIN, "Main" },
4827 { FF_PROFILE_H264_EXTENDED, "Extended" },
4828 { FF_PROFILE_H264_HIGH, "High" },
4829 { FF_PROFILE_H264_HIGH_10, "High 10" },
4830 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4831 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4832 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4833 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4834 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4835 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4836 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4837 { FF_PROFILE_UNKNOWN },
4840 static const AVOption h264_options[] = {
4841 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
4842 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
4846 static const AVClass h264_class = {
4847 .class_name = "H264 Decoder",
4848 .item_name = av_default_item_name,
4849 .option = h264_options,
4850 .version = LIBAVUTIL_VERSION_INT,
4853 static const AVClass h264_vdpau_class = {
4854 .class_name = "H264 VDPAU Decoder",
4855 .item_name = av_default_item_name,
4856 .option = h264_options,
4857 .version = LIBAVUTIL_VERSION_INT,
4860 AVCodec ff_h264_decoder = {
4862 .type = AVMEDIA_TYPE_VIDEO,
4863 .id = AV_CODEC_ID_H264,
4864 .priv_data_size = sizeof(H264Context),
4865 .init = ff_h264_decode_init,
4866 .close = h264_decode_end,
4867 .decode = decode_frame,
4868 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4869 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4870 CODEC_CAP_FRAME_THREADS,
4872 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4873 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4874 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4875 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4876 .priv_class = &h264_class,
4879 #if CONFIG_H264_VDPAU_DECODER
4880 AVCodec ff_h264_vdpau_decoder = {
4881 .name = "h264_vdpau",
4882 .type = AVMEDIA_TYPE_VIDEO,
4883 .id = AV_CODEC_ID_H264,
4884 .priv_data_size = sizeof(H264Context),
4885 .init = ff_h264_decode_init,
4886 .close = h264_decode_end,
4887 .decode = decode_frame,
4888 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
4890 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
4891 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
4893 .profiles = NULL_IF_CONFIG_SMALL(profiles),
4894 .priv_class = &h264_vdpau_class,