2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/imgutils.h"
31 #include "cabac_functions.h"
34 #include "mpegvideo.h"
37 #include "h264chroma.h"
38 #include "h264_mvpred.h"
41 #include "rectangle.h"
44 #include "vdpau_internal.h"
45 #include "libavutil/avassert.h"
50 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
52 static const uint8_t rem6[QP_MAX_NUM + 1] = {
53 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
54 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
55 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
58 static const uint8_t div6[QP_MAX_NUM + 1] = {
59 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
60 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
61 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
64 static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
65 #if CONFIG_H264_DXVA2_HWACCEL
68 #if CONFIG_H264_VAAPI_HWACCEL
71 #if CONFIG_H264_VDA_HWACCEL
74 #if CONFIG_H264_VDPAU_HWACCEL
81 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
83 int mb_x, int mb_y, int mb_intra, int mb_skipped)
85 H264Context *h = opaque;
89 h->mb_xy = mb_x + mb_y * h->mb_stride;
90 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
92 /* FIXME: It is possible albeit uncommon that slice references
93 * differ between slices. We take the easy approach and ignore
94 * it for now. If this turns out to have any relevance in
95 * practice then correct remapping should be added. */
96 if (ref >= h->ref_count[0])
98 fill_rectangle(&h->cur_pic.f.ref_index[0][4 * h->mb_xy],
100 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
101 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
102 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
103 assert(!FRAME_MBAFF);
104 ff_h264_hl_decode_mb(h);
107 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
109 ff_draw_horiz_band(h->avctx, &h->dsp, &h->cur_pic,
110 h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL,
111 y, height, h->picture_structure, h->first_field, 1,
112 h->low_delay, h->mb_height * 16, h->mb_width * 16);
115 static void free_frame_buffer(H264Context *h, Picture *pic)
117 ff_thread_release_buffer(h->avctx, &pic->f);
118 av_freep(&pic->f.hwaccel_picture_private);
121 static void free_picture(H264Context *h, Picture *pic)
126 free_frame_buffer(h, pic);
128 av_freep(&pic->qscale_table_base);
129 pic->f.qscale_table = NULL;
130 av_freep(&pic->mb_type_base);
131 pic->f.mb_type = NULL;
132 for (i = 0; i < 2; i++) {
133 av_freep(&pic->motion_val_base[i]);
134 av_freep(&pic->f.ref_index[i]);
135 pic->f.motion_val[i] = NULL;
139 static void release_unused_pictures(H264Context *h, int remove_current)
143 /* release non reference frames */
144 for (i = 0; i < h->picture_count; i++) {
145 if (h->DPB[i].f.data[0] && !h->DPB[i].f.reference &&
146 (!h->DPB[i].owner2 || h->DPB[i].owner2 == h) &&
147 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
148 free_frame_buffer(h, &h->DPB[i]);
153 static int alloc_scratch_buffers(H264Context *h, int linesize)
155 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
157 if (h->bipred_scratchpad)
160 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
161 // edge emu needs blocksize + filter length - 1
162 // (= 21x21 for h264)
163 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
164 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
166 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
167 av_freep(&h->bipred_scratchpad);
168 av_freep(&h->edge_emu_buffer);
169 av_freep(&h->me.scratchpad);
170 return AVERROR(ENOMEM);
173 h->me.temp = h->me.scratchpad;
178 static int alloc_picture(H264Context *h, Picture *pic)
180 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
181 const int mb_array_size = h->mb_stride * h->mb_height;
182 const int b4_stride = h->mb_width * 4 + 1;
183 const int b4_array_size = b4_stride * h->mb_height * 4;
186 av_assert0(!pic->f.data[0]);
188 if (h->avctx->hwaccel) {
189 const AVHWAccel *hwaccel = h->avctx->hwaccel;
190 av_assert0(!pic->f.hwaccel_picture_private);
191 if (hwaccel->priv_data_size) {
192 pic->f.hwaccel_picture_private = av_mallocz(hwaccel->priv_data_size);
193 if (!pic->f.hwaccel_picture_private)
194 return AVERROR(ENOMEM);
197 ret = ff_thread_get_buffer(h->avctx, &pic->f);
201 h->linesize = pic->f.linesize[0];
202 h->uvlinesize = pic->f.linesize[1];
204 if (pic->f.qscale_table == NULL) {
205 FF_ALLOCZ_OR_GOTO(h->avctx, pic->qscale_table_base,
206 (big_mb_num + h->mb_stride) * sizeof(uint8_t),
208 FF_ALLOCZ_OR_GOTO(h->avctx, pic->mb_type_base,
209 (big_mb_num + h->mb_stride) * sizeof(uint32_t),
211 pic->f.mb_type = pic->mb_type_base + 2 * h->mb_stride + 1;
212 pic->f.qscale_table = pic->qscale_table_base + 2 * h->mb_stride + 1;
214 for (i = 0; i < 2; i++) {
215 FF_ALLOCZ_OR_GOTO(h->avctx, pic->motion_val_base[i],
216 2 * (b4_array_size + 4) * sizeof(int16_t),
218 pic->f.motion_val[i] = pic->motion_val_base[i] + 4;
219 FF_ALLOCZ_OR_GOTO(h->avctx, pic->f.ref_index[i],
220 4 * mb_array_size * sizeof(uint8_t), fail)
222 pic->f.motion_subsample_log2 = 2;
224 pic->f.qstride = h->mb_stride;
231 free_frame_buffer(h, pic);
232 return (ret < 0) ? ret : AVERROR(ENOMEM);
235 static inline int pic_is_unused(H264Context *h, Picture *pic)
237 if (pic->f.data[0] == NULL)
239 if (pic->needs_realloc && !(pic->f.reference & DELAYED_PIC_REF))
240 if (!pic->owner2 || pic->owner2 == h)
245 static int find_unused_picture(H264Context *h)
249 for (i = h->picture_range_start; i < h->picture_range_end; i++) {
250 if (pic_is_unused(h, &h->DPB[i]))
253 if (i == h->picture_range_end)
254 return AVERROR_INVALIDDATA;
256 if (h->DPB[i].needs_realloc) {
257 h->DPB[i].needs_realloc = 0;
258 free_picture(h, &h->DPB[i]);
259 avcodec_get_frame_defaults(&h->DPB[i].f);
266 * Check if the top & left blocks are available if needed and
267 * change the dc mode so it only uses the available blocks.
269 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
271 static const int8_t top[12] = {
272 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
274 static const int8_t left[12] = {
275 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
279 if (!(h->top_samples_available & 0x8000)) {
280 for (i = 0; i < 4; i++) {
281 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
283 av_log(h->avctx, AV_LOG_ERROR,
284 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
285 status, h->mb_x, h->mb_y);
288 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
293 if ((h->left_samples_available & 0x8888) != 0x8888) {
294 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
295 for (i = 0; i < 4; i++)
296 if (!(h->left_samples_available & mask[i])) {
297 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
299 av_log(h->avctx, AV_LOG_ERROR,
300 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
301 status, h->mb_x, h->mb_y);
304 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
310 } // FIXME cleanup like ff_h264_check_intra_pred_mode
313 * Check if the top & left blocks are available if needed and
314 * change the dc mode so it only uses the available blocks.
316 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
318 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
319 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
322 av_log(h->avctx, AV_LOG_ERROR,
323 "out of range intra chroma pred mode at %d %d\n",
328 if (!(h->top_samples_available & 0x8000)) {
331 av_log(h->avctx, AV_LOG_ERROR,
332 "top block unavailable for requested intra mode at %d %d\n",
338 if ((h->left_samples_available & 0x8080) != 0x8080) {
340 if (is_chroma && (h->left_samples_available & 0x8080)) {
341 // mad cow disease mode, aka MBAFF + constrained_intra_pred
342 mode = ALZHEIMER_DC_L0T_PRED8x8 +
343 (!(h->left_samples_available & 0x8000)) +
344 2 * (mode == DC_128_PRED8x8);
347 av_log(h->avctx, AV_LOG_ERROR,
348 "left block unavailable for requested intra mode at %d %d\n",
357 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
358 int *dst_length, int *consumed, int length)
364 // src[0]&0x80; // forbidden bit
365 h->nal_ref_idc = src[0] >> 5;
366 h->nal_unit_type = src[0] & 0x1F;
371 #define STARTCODE_TEST \
372 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
373 if (src[i + 2] != 3) { \
374 /* startcode, so we must be past the end */ \
379 #if HAVE_FAST_UNALIGNED
380 #define FIND_FIRST_ZERO \
381 if (i > 0 && !src[i]) \
386 for (i = 0; i + 1 < length; i += 9) {
387 if (!((~AV_RN64A(src + i) &
388 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
389 0x8000800080008080ULL))
396 for (i = 0; i + 1 < length; i += 5) {
397 if (!((~AV_RN32A(src + i) &
398 (AV_RN32A(src + i) - 0x01000101U)) &
407 for (i = 0; i + 1 < length; i += 2) {
410 if (i > 0 && src[i - 1] == 0)
416 if (i >= length - 1) { // no escaped 0
417 *dst_length = length;
418 *consumed = length + 1; // +1 for the header
422 // use second escape buffer for inter data
423 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
424 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
425 length + FF_INPUT_BUFFER_PADDING_SIZE);
426 dst = h->rbsp_buffer[bufidx];
433 while (si + 2 < length) {
434 // remove escapes (very rare 1:2^22)
435 if (src[si + 2] > 3) {
436 dst[di++] = src[si++];
437 dst[di++] = src[si++];
438 } else if (src[si] == 0 && src[si + 1] == 0) {
439 if (src[si + 2] == 3) { // escape
444 } else // next start code
448 dst[di++] = src[si++];
451 dst[di++] = src[si++];
454 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
457 *consumed = si + 1; // +1 for the header
458 /* FIXME store exact number of bits in the getbitcontext
459 * (it is needed for decoding) */
464 * Identify the exact end of the bitstream
465 * @return the length of the trailing, or 0 if damaged
467 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
472 tprintf(h->avctx, "rbsp trailing %X\n", v);
474 for (r = 1; r < 9; r++) {
482 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
483 int height, int y_offset, int list)
485 int raw_my = h->mv_cache[list][scan8[n]][1];
486 int filter_height_up = (raw_my & 3) ? 2 : 0;
487 int filter_height_down = (raw_my & 3) ? 3 : 0;
488 int full_my = (raw_my >> 2) + y_offset;
489 int top = full_my - filter_height_up;
490 int bottom = full_my + filter_height_down + height;
492 return FFMAX(abs(top), bottom);
495 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
496 int height, int y_offset, int list0,
497 int list1, int *nrefs)
501 y_offset += 16 * (h->mb_y >> MB_FIELD);
504 int ref_n = h->ref_cache[0][scan8[n]];
505 Picture *ref = &h->ref_list[0][ref_n];
507 // Error resilience puts the current picture in the ref list.
508 // Don't try to wait on these as it will cause a deadlock.
509 // Fields can wait on each other, though.
510 if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
511 (ref->f.reference & 3) != h->picture_structure) {
512 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
513 if (refs[0][ref_n] < 0)
515 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
520 int ref_n = h->ref_cache[1][scan8[n]];
521 Picture *ref = &h->ref_list[1][ref_n];
523 if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
524 (ref->f.reference & 3) != h->picture_structure) {
525 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
526 if (refs[1][ref_n] < 0)
528 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
534 * Wait until all reference frames are available for MC operations.
536 * @param h the H264 context
538 static void await_references(H264Context *h)
540 const int mb_xy = h->mb_xy;
541 const int mb_type = h->cur_pic.f.mb_type[mb_xy];
543 int nrefs[2] = { 0 };
546 memset(refs, -1, sizeof(refs));
548 if (IS_16X16(mb_type)) {
549 get_lowest_part_y(h, refs, 0, 16, 0,
550 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
551 } else if (IS_16X8(mb_type)) {
552 get_lowest_part_y(h, refs, 0, 8, 0,
553 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
554 get_lowest_part_y(h, refs, 8, 8, 8,
555 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
556 } else if (IS_8X16(mb_type)) {
557 get_lowest_part_y(h, refs, 0, 16, 0,
558 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
559 get_lowest_part_y(h, refs, 4, 16, 0,
560 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
564 assert(IS_8X8(mb_type));
566 for (i = 0; i < 4; i++) {
567 const int sub_mb_type = h->sub_mb_type[i];
569 int y_offset = (i & 2) << 2;
571 if (IS_SUB_8X8(sub_mb_type)) {
572 get_lowest_part_y(h, refs, n, 8, y_offset,
573 IS_DIR(sub_mb_type, 0, 0),
574 IS_DIR(sub_mb_type, 0, 1),
576 } else if (IS_SUB_8X4(sub_mb_type)) {
577 get_lowest_part_y(h, refs, n, 4, y_offset,
578 IS_DIR(sub_mb_type, 0, 0),
579 IS_DIR(sub_mb_type, 0, 1),
581 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
582 IS_DIR(sub_mb_type, 0, 0),
583 IS_DIR(sub_mb_type, 0, 1),
585 } else if (IS_SUB_4X8(sub_mb_type)) {
586 get_lowest_part_y(h, refs, n, 8, y_offset,
587 IS_DIR(sub_mb_type, 0, 0),
588 IS_DIR(sub_mb_type, 0, 1),
590 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
591 IS_DIR(sub_mb_type, 0, 0),
592 IS_DIR(sub_mb_type, 0, 1),
596 assert(IS_SUB_4X4(sub_mb_type));
597 for (j = 0; j < 4; j++) {
598 int sub_y_offset = y_offset + 2 * (j & 2);
599 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
600 IS_DIR(sub_mb_type, 0, 0),
601 IS_DIR(sub_mb_type, 0, 1),
608 for (list = h->list_count - 1; list >= 0; list--)
609 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
610 int row = refs[list][ref];
612 Picture *ref_pic = &h->ref_list[list][ref];
613 int ref_field = ref_pic->f.reference - 1;
614 int ref_field_picture = ref_pic->field_picture;
615 int pic_height = 16 * h->mb_height >> ref_field_picture;
620 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
621 ff_thread_await_progress(&ref_pic->f,
622 FFMIN((row >> 1) - !(row & 1),
625 ff_thread_await_progress(&ref_pic->f,
626 FFMIN((row >> 1), pic_height - 1),
628 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
629 ff_thread_await_progress(&ref_pic->f,
630 FFMIN(row * 2 + ref_field,
633 } else if (FIELD_PICTURE) {
634 ff_thread_await_progress(&ref_pic->f,
635 FFMIN(row, pic_height - 1),
638 ff_thread_await_progress(&ref_pic->f,
639 FFMIN(row, pic_height - 1),
646 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
647 int n, int square, int height,
649 uint8_t *dest_y, uint8_t *dest_cb,
651 int src_x_offset, int src_y_offset,
652 qpel_mc_func *qpix_op,
653 h264_chroma_mc_func chroma_op,
654 int pixel_shift, int chroma_idc)
656 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
657 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
658 const int luma_xy = (mx & 3) + ((my & 3) << 2);
659 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
660 uint8_t *src_y = pic->f.data[0] + offset;
661 uint8_t *src_cb, *src_cr;
662 int extra_width = h->emu_edge_width;
663 int extra_height = h->emu_edge_height;
665 const int full_mx = mx >> 2;
666 const int full_my = my >> 2;
667 const int pic_width = 16 * h->mb_width;
668 const int pic_height = 16 * h->mb_height >> MB_FIELD;
676 if (full_mx < 0 - extra_width ||
677 full_my < 0 - extra_height ||
678 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
679 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
680 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
681 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
683 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
684 full_my - 2, pic_width, pic_height);
685 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
689 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
691 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
693 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
696 if (chroma_idc == 3 /* yuv444 */) {
697 src_cb = pic->f.data[1] + offset;
699 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
700 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
702 16 + 5, 16 + 5 /*FIXME*/,
703 full_mx - 2, full_my - 2,
704 pic_width, pic_height);
705 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
707 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
709 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
711 src_cr = pic->f.data[2] + offset;
713 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
714 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
716 16 + 5, 16 + 5 /*FIXME*/,
717 full_mx - 2, full_my - 2,
718 pic_width, pic_height);
719 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
721 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
723 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
727 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
728 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
729 // chroma offset when predicting from a field of opposite parity
730 my += 2 * ((h->mb_y & 1) - (pic->f.reference - 1));
731 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
734 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
735 (my >> ysh) * h->mb_uvlinesize;
736 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
737 (my >> ysh) * h->mb_uvlinesize;
740 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
741 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
742 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
743 src_cb = h->edge_emu_buffer;
745 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
746 height >> (chroma_idc == 1 /* yuv420 */),
747 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
750 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
751 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
752 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
753 src_cr = h->edge_emu_buffer;
755 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
756 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
759 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
760 int height, int delta,
761 uint8_t *dest_y, uint8_t *dest_cb,
763 int x_offset, int y_offset,
764 qpel_mc_func *qpix_put,
765 h264_chroma_mc_func chroma_put,
766 qpel_mc_func *qpix_avg,
767 h264_chroma_mc_func chroma_avg,
768 int list0, int list1,
769 int pixel_shift, int chroma_idc)
771 qpel_mc_func *qpix_op = qpix_put;
772 h264_chroma_mc_func chroma_op = chroma_put;
774 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
775 if (chroma_idc == 3 /* yuv444 */) {
776 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
777 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
778 } else if (chroma_idc == 2 /* yuv422 */) {
779 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
780 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
781 } else { /* yuv420 */
782 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
783 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
785 x_offset += 8 * h->mb_x;
786 y_offset += 8 * (h->mb_y >> MB_FIELD);
789 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
790 mc_dir_part(h, ref, n, square, height, delta, 0,
791 dest_y, dest_cb, dest_cr, x_offset, y_offset,
792 qpix_op, chroma_op, pixel_shift, chroma_idc);
795 chroma_op = chroma_avg;
799 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
800 mc_dir_part(h, ref, n, square, height, delta, 1,
801 dest_y, dest_cb, dest_cr, x_offset, y_offset,
802 qpix_op, chroma_op, pixel_shift, chroma_idc);
806 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
807 int height, int delta,
808 uint8_t *dest_y, uint8_t *dest_cb,
810 int x_offset, int y_offset,
811 qpel_mc_func *qpix_put,
812 h264_chroma_mc_func chroma_put,
813 h264_weight_func luma_weight_op,
814 h264_weight_func chroma_weight_op,
815 h264_biweight_func luma_weight_avg,
816 h264_biweight_func chroma_weight_avg,
817 int list0, int list1,
818 int pixel_shift, int chroma_idc)
822 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
823 if (chroma_idc == 3 /* yuv444 */) {
824 chroma_height = height;
825 chroma_weight_avg = luma_weight_avg;
826 chroma_weight_op = luma_weight_op;
827 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
828 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
829 } else if (chroma_idc == 2 /* yuv422 */) {
830 chroma_height = height;
831 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
832 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
833 } else { /* yuv420 */
834 chroma_height = height >> 1;
835 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
836 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
838 x_offset += 8 * h->mb_x;
839 y_offset += 8 * (h->mb_y >> MB_FIELD);
841 if (list0 && list1) {
842 /* don't optimize for luma-only case, since B-frames usually
843 * use implicit weights => chroma too. */
844 uint8_t *tmp_cb = h->bipred_scratchpad;
845 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
846 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
847 int refn0 = h->ref_cache[0][scan8[n]];
848 int refn1 = h->ref_cache[1][scan8[n]];
850 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
851 dest_y, dest_cb, dest_cr,
852 x_offset, y_offset, qpix_put, chroma_put,
853 pixel_shift, chroma_idc);
854 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
855 tmp_y, tmp_cb, tmp_cr,
856 x_offset, y_offset, qpix_put, chroma_put,
857 pixel_shift, chroma_idc);
859 if (h->use_weight == 2) {
860 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
861 int weight1 = 64 - weight0;
862 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
863 height, 5, weight0, weight1, 0);
864 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
865 chroma_height, 5, weight0, weight1, 0);
866 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
867 chroma_height, 5, weight0, weight1, 0);
869 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
870 h->luma_log2_weight_denom,
871 h->luma_weight[refn0][0][0],
872 h->luma_weight[refn1][1][0],
873 h->luma_weight[refn0][0][1] +
874 h->luma_weight[refn1][1][1]);
875 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
876 h->chroma_log2_weight_denom,
877 h->chroma_weight[refn0][0][0][0],
878 h->chroma_weight[refn1][1][0][0],
879 h->chroma_weight[refn0][0][0][1] +
880 h->chroma_weight[refn1][1][0][1]);
881 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
882 h->chroma_log2_weight_denom,
883 h->chroma_weight[refn0][0][1][0],
884 h->chroma_weight[refn1][1][1][0],
885 h->chroma_weight[refn0][0][1][1] +
886 h->chroma_weight[refn1][1][1][1]);
889 int list = list1 ? 1 : 0;
890 int refn = h->ref_cache[list][scan8[n]];
891 Picture *ref = &h->ref_list[list][refn];
892 mc_dir_part(h, ref, n, square, height, delta, list,
893 dest_y, dest_cb, dest_cr, x_offset, y_offset,
894 qpix_put, chroma_put, pixel_shift, chroma_idc);
896 luma_weight_op(dest_y, h->mb_linesize, height,
897 h->luma_log2_weight_denom,
898 h->luma_weight[refn][list][0],
899 h->luma_weight[refn][list][1]);
900 if (h->use_weight_chroma) {
901 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
902 h->chroma_log2_weight_denom,
903 h->chroma_weight[refn][list][0][0],
904 h->chroma_weight[refn][list][0][1]);
905 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
906 h->chroma_log2_weight_denom,
907 h->chroma_weight[refn][list][1][0],
908 h->chroma_weight[refn][list][1][1]);
913 static av_always_inline void prefetch_motion(H264Context *h, int list,
914 int pixel_shift, int chroma_idc)
916 /* fetch pixels for estimated mv 4 macroblocks ahead
917 * optimized for 64byte cache lines */
918 const int refn = h->ref_cache[list][scan8[0]];
920 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
921 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
922 uint8_t **src = h->ref_list[list][refn].f.data;
923 int off = (mx << pixel_shift) +
924 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
926 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
927 if (chroma_idc == 3 /* yuv444 */) {
928 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
929 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
931 off = ((mx >> 1) << pixel_shift) +
932 ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
934 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
939 static void free_tables(H264Context *h, int free_rbsp)
944 av_freep(&h->intra4x4_pred_mode);
945 av_freep(&h->chroma_pred_mode_table);
946 av_freep(&h->cbp_table);
947 av_freep(&h->mvd_table[0]);
948 av_freep(&h->mvd_table[1]);
949 av_freep(&h->direct_table);
950 av_freep(&h->non_zero_count);
951 av_freep(&h->slice_table_base);
952 h->slice_table = NULL;
953 av_freep(&h->list_counts);
955 av_freep(&h->mb2b_xy);
956 av_freep(&h->mb2br_xy);
959 for (i = 0; i < h->picture_count && !h->avctx->internal->is_copy; i++)
960 free_picture(h, &h->DPB[i]);
962 h->picture_count = 0;
964 for (i = 0; i < h->picture_count; i++)
965 h->DPB[i].needs_realloc = 1;
968 h->cur_pic_ptr = NULL;
970 for (i = 0; i < MAX_THREADS; i++) {
971 hx = h->thread_context[i];
974 av_freep(&hx->top_borders[1]);
975 av_freep(&hx->top_borders[0]);
976 av_freep(&hx->bipred_scratchpad);
977 av_freep(&hx->edge_emu_buffer);
978 av_freep(&hx->dc_val_base);
979 av_freep(&hx->me.scratchpad);
980 av_freep(&hx->er.mb_index2xy);
981 av_freep(&hx->er.error_status_table);
982 av_freep(&hx->er.er_temp_buffer);
983 av_freep(&hx->er.mbintra_table);
984 av_freep(&hx->er.mbskip_table);
987 av_freep(&hx->rbsp_buffer[1]);
988 av_freep(&hx->rbsp_buffer[0]);
989 hx->rbsp_buffer_size[0] = 0;
990 hx->rbsp_buffer_size[1] = 0;
993 av_freep(&h->thread_context[i]);
997 static void init_dequant8_coeff_table(H264Context *h)
1000 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1002 for (i = 0; i < 6; i++) {
1003 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1004 for (j = 0; j < i; j++)
1005 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1006 64 * sizeof(uint8_t))) {
1007 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1013 for (q = 0; q < max_qp + 1; q++) {
1014 int shift = div6[q];
1016 for (x = 0; x < 64; x++)
1017 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1018 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1019 h->pps.scaling_matrix8[i][x]) << shift;
1024 static void init_dequant4_coeff_table(H264Context *h)
1027 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1028 for (i = 0; i < 6; i++) {
1029 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1030 for (j = 0; j < i; j++)
1031 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1032 16 * sizeof(uint8_t))) {
1033 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1039 for (q = 0; q < max_qp + 1; q++) {
1040 int shift = div6[q] + 2;
1042 for (x = 0; x < 16; x++)
1043 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1044 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1045 h->pps.scaling_matrix4[i][x]) << shift;
1050 static void init_dequant_tables(H264Context *h)
1053 init_dequant4_coeff_table(h);
1054 if (h->pps.transform_8x8_mode)
1055 init_dequant8_coeff_table(h);
1056 if (h->sps.transform_bypass) {
1057 for (i = 0; i < 6; i++)
1058 for (x = 0; x < 16; x++)
1059 h->dequant4_coeff[i][0][x] = 1 << 6;
1060 if (h->pps.transform_8x8_mode)
1061 for (i = 0; i < 6; i++)
1062 for (x = 0; x < 64; x++)
1063 h->dequant8_coeff[i][0][x] = 1 << 6;
1067 int ff_h264_alloc_tables(H264Context *h)
1069 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1070 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
1073 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1074 row_mb_num * 8 * sizeof(uint8_t), fail)
1075 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1076 big_mb_num * 48 * sizeof(uint8_t), fail)
1077 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1078 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1079 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1080 big_mb_num * sizeof(uint16_t), fail)
1081 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1082 big_mb_num * sizeof(uint8_t), fail)
1083 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1084 16 * row_mb_num * sizeof(uint8_t), fail);
1085 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1086 16 * row_mb_num * sizeof(uint8_t), fail);
1087 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1088 4 * big_mb_num * sizeof(uint8_t), fail);
1089 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1090 big_mb_num * sizeof(uint8_t), fail)
1092 memset(h->slice_table_base, -1,
1093 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1094 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1096 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1097 big_mb_num * sizeof(uint32_t), fail);
1098 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1099 big_mb_num * sizeof(uint32_t), fail);
1100 for (y = 0; y < h->mb_height; y++)
1101 for (x = 0; x < h->mb_width; x++) {
1102 const int mb_xy = x + y * h->mb_stride;
1103 const int b_xy = 4 * x + 4 * y * h->b_stride;
1105 h->mb2b_xy[mb_xy] = b_xy;
1106 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1109 if (!h->dequant4_coeff[0])
1110 init_dequant_tables(h);
1113 h->picture_count = MAX_PICTURE_COUNT * FFMAX(1, h->avctx->thread_count);
1114 h->DPB = av_mallocz_array(h->picture_count, sizeof(*h->DPB));
1116 return AVERROR(ENOMEM);
1117 for (i = 0; i < h->picture_count; i++)
1118 avcodec_get_frame_defaults(&h->DPB[i].f);
1119 avcodec_get_frame_defaults(&h->cur_pic.f);
1130 * Mimic alloc_tables(), but for every context thread.
1132 static void clone_tables(H264Context *dst, H264Context *src, int i)
1134 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1135 dst->non_zero_count = src->non_zero_count;
1136 dst->slice_table = src->slice_table;
1137 dst->cbp_table = src->cbp_table;
1138 dst->mb2b_xy = src->mb2b_xy;
1139 dst->mb2br_xy = src->mb2br_xy;
1140 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1141 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1142 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1143 dst->direct_table = src->direct_table;
1144 dst->list_counts = src->list_counts;
1145 dst->DPB = src->DPB;
1146 dst->cur_pic_ptr = src->cur_pic_ptr;
1147 dst->cur_pic = src->cur_pic;
1148 dst->bipred_scratchpad = NULL;
1149 dst->edge_emu_buffer = NULL;
1150 dst->me.scratchpad = NULL;
1151 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1152 src->sps.chroma_format_idc);
1157 * Allocate buffers which are not shared amongst multiple threads.
1159 static int context_init(H264Context *h)
1161 ERContext *er = &h->er;
1162 int mb_array_size = h->mb_height * h->mb_stride;
1163 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1164 int c_size = h->mb_stride * (h->mb_height + 1);
1165 int yc_size = y_size + 2 * c_size;
1168 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1169 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1170 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1171 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1173 h->ref_cache[0][scan8[5] + 1] =
1174 h->ref_cache[0][scan8[7] + 1] =
1175 h->ref_cache[0][scan8[13] + 1] =
1176 h->ref_cache[1][scan8[5] + 1] =
1177 h->ref_cache[1][scan8[7] + 1] =
1178 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1181 er->avctx = h->avctx;
1183 er->decode_mb = h264_er_decode_mb;
1185 er->quarter_sample = 1;
1187 er->mb_num = h->mb_num;
1188 er->mb_width = h->mb_width;
1189 er->mb_height = h->mb_height;
1190 er->mb_stride = h->mb_stride;
1191 er->b8_stride = h->mb_width * 2 + 1;
1193 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1194 fail); // error ressilience code looks cleaner with this
1195 for (y = 0; y < h->mb_height; y++)
1196 for (x = 0; x < h->mb_width; x++)
1197 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1199 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1200 h->mb_stride + h->mb_width;
1202 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1203 mb_array_size * sizeof(uint8_t), fail);
1205 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1206 memset(er->mbintra_table, 1, mb_array_size);
1208 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1210 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1213 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1214 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1215 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1216 er->dc_val[2] = er->dc_val[1] + c_size;
1217 for (i = 0; i < yc_size; i++)
1218 h->dc_val_base[i] = 1024;
1223 return -1; // free_tables will clean up for us
1226 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1227 int parse_extradata);
1229 static av_cold void common_init(H264Context *h)
1232 h->width = h->avctx->width;
1233 h->height = h->avctx->height;
1235 h->bit_depth_luma = 8;
1236 h->chroma_format_idc = 1;
1238 ff_h264dsp_init(&h->h264dsp, 8, 1);
1239 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1240 ff_h264qpel_init(&h->h264qpel, 8);
1241 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1243 h->dequant_coeff_pps = -1;
1245 /* needed so that IDCT permutation is known early */
1246 ff_dsputil_init(&h->dsp, h->avctx);
1247 ff_videodsp_init(&h->vdsp, 8);
1249 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1250 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1253 int ff_h264_decode_extradata(H264Context *h)
1255 AVCodecContext *avctx = h->avctx;
1257 if (avctx->extradata[0] == 1) {
1258 int i, cnt, nalsize;
1259 unsigned char *p = avctx->extradata;
1263 if (avctx->extradata_size < 7) {
1264 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1267 /* sps and pps in the avcC always have length coded with 2 bytes,
1268 * so put a fake nal_length_size = 2 while parsing them */
1269 h->nal_length_size = 2;
1270 // Decode sps from avcC
1271 cnt = *(p + 5) & 0x1f; // Number of sps
1273 for (i = 0; i < cnt; i++) {
1274 nalsize = AV_RB16(p) + 2;
1275 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1277 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1278 av_log(avctx, AV_LOG_ERROR,
1279 "Decoding sps %d from avcC failed\n", i);
1284 // Decode pps from avcC
1285 cnt = *(p++); // Number of pps
1286 for (i = 0; i < cnt; i++) {
1287 nalsize = AV_RB16(p) + 2;
1288 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1290 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1291 av_log(avctx, AV_LOG_ERROR,
1292 "Decoding pps %d from avcC failed\n", i);
1297 // Now store right nal length size, that will be used to parse all other nals
1298 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1301 if (decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1) < 0)
1307 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1309 H264Context *h = avctx->priv_data;
1315 h->picture_structure = PICT_FRAME;
1316 h->picture_range_start = 0;
1317 h->picture_range_end = MAX_PICTURE_COUNT;
1318 h->slice_context_count = 1;
1319 h->workaround_bugs = avctx->workaround_bugs;
1320 h->flags = avctx->flags;
1323 // s->decode_mb = ff_h263_decode_mb;
1324 if (!avctx->has_b_frames)
1327 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1329 ff_h264_decode_init_vlc();
1332 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1334 h->thread_context[0] = h;
1335 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1336 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1337 h->last_pocs[i] = INT_MIN;
1338 h->prev_poc_msb = 1 << 16;
1340 ff_h264_reset_sei(h);
1341 if (avctx->codec_id == AV_CODEC_ID_H264) {
1342 if (avctx->ticks_per_frame == 1)
1343 h->avctx->time_base.den *= 2;
1344 avctx->ticks_per_frame = 2;
1347 if (avctx->extradata_size > 0 && avctx->extradata &&
1348 ff_h264_decode_extradata(h))
1351 if (h->sps.bitstream_restriction_flag &&
1352 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1353 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1360 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1361 #undef REBASE_PICTURE
1362 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1363 ((pic && pic >= old_ctx->DPB && \
1364 pic < old_ctx->DPB + old_ctx->picture_count) ? \
1365 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1367 static void copy_picture_range(Picture **to, Picture **from, int count,
1368 H264Context *new_base,
1369 H264Context *old_base)
1373 for (i = 0; i < count; i++) {
1374 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1375 IN_RANGE(from[i], old_base->DPB,
1376 sizeof(Picture) * old_base->picture_count) ||
1378 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1382 static void copy_parameter_set(void **to, void **from, int count, int size)
1386 for (i = 0; i < count; i++) {
1387 if (to[i] && !from[i])
1389 else if (from[i] && !to[i])
1390 to[i] = av_malloc(size);
1393 memcpy(to[i], from[i], size);
1397 static int decode_init_thread_copy(AVCodecContext *avctx)
1399 H264Context *h = avctx->priv_data;
1401 if (!avctx->internal->is_copy)
1403 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1404 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1406 h->context_initialized = 0;
1411 #define copy_fields(to, from, start_field, end_field) \
1412 memcpy(&to->start_field, &from->start_field, \
1413 (char *)&to->end_field - (char *)&to->start_field)
1415 static int h264_slice_header_init(H264Context *, int);
1417 static int h264_set_parameter_from_sps(H264Context *h);
1419 static int decode_update_thread_context(AVCodecContext *dst,
1420 const AVCodecContext *src)
1422 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1423 int inited = h->context_initialized, err = 0;
1424 int context_reinitialized = 0;
1427 if (dst == src || !h1->context_initialized)
1431 (h->width != h1->width ||
1432 h->height != h1->height ||
1433 h->mb_width != h1->mb_width ||
1434 h->mb_height != h1->mb_height ||
1435 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1436 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1437 h->sps.colorspace != h1->sps.colorspace)) {
1439 av_freep(&h->bipred_scratchpad);
1441 h->width = h1->width;
1442 h->height = h1->height;
1443 h->mb_height = h1->mb_height;
1444 h->mb_width = h1->mb_width;
1445 h->mb_num = h1->mb_num;
1446 h->mb_stride = h1->mb_stride;
1447 h->b_stride = h1->b_stride;
1449 if ((err = h264_slice_header_init(h, 1)) < 0) {
1450 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1453 context_reinitialized = 1;
1455 /* update linesize on resize. The decoder doesn't
1456 * necessarily call ff_h264_frame_start in the new thread */
1457 h->linesize = h1->linesize;
1458 h->uvlinesize = h1->uvlinesize;
1460 /* copy block_offset since frame_start may not be called */
1461 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1465 for (i = 0; i < MAX_SPS_COUNT; i++)
1466 av_freep(h->sps_buffers + i);
1468 for (i = 0; i < MAX_PPS_COUNT; i++)
1469 av_freep(h->pps_buffers + i);
1471 memcpy(h, h1, sizeof(*h1));
1472 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1473 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1474 memset(&h->er, 0, sizeof(h->er));
1475 memset(&h->me, 0, sizeof(h->me));
1476 h->context_initialized = 0;
1478 h->picture_range_start += MAX_PICTURE_COUNT;
1479 h->picture_range_end += MAX_PICTURE_COUNT;
1483 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1485 if (ff_h264_alloc_tables(h) < 0) {
1486 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1487 return AVERROR(ENOMEM);
1491 for (i = 0; i < 2; i++) {
1492 h->rbsp_buffer[i] = NULL;
1493 h->rbsp_buffer_size[i] = 0;
1495 h->bipred_scratchpad = NULL;
1496 h->edge_emu_buffer = NULL;
1498 h->thread_context[0] = h;
1500 h->dsp.clear_blocks(h->mb);
1501 h->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1502 h->context_initialized = 1;
1505 h->avctx->coded_height = h1->avctx->coded_height;
1506 h->avctx->coded_width = h1->avctx->coded_width;
1507 h->avctx->width = h1->avctx->width;
1508 h->avctx->height = h1->avctx->height;
1509 h->coded_picture_number = h1->coded_picture_number;
1510 h->first_field = h1->first_field;
1511 h->picture_structure = h1->picture_structure;
1512 h->qscale = h1->qscale;
1513 h->droppable = h1->droppable;
1514 h->data_partitioning = h1->data_partitioning;
1515 h->low_delay = h1->low_delay;
1517 memcpy(h->DPB, h1->DPB, h1->picture_count * sizeof(*h1->DPB));
1519 // reset s->picture[].f.extended_data to s->picture[].f.data
1520 for (i = 0; i < h->picture_count; i++)
1521 h->DPB[i].f.extended_data = h->DPB[i].f.data;
1523 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1524 h->cur_pic = h1->cur_pic;
1525 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1527 h->workaround_bugs = h1->workaround_bugs;
1528 h->low_delay = h1->low_delay;
1529 h->droppable = h1->droppable;
1531 /* frame_start may not be called for the next thread (if it's decoding
1532 * a bottom field) so this has to be allocated here */
1533 err = alloc_scratch_buffers(h, h1->linesize);
1537 // extradata/NAL handling
1538 h->is_avc = h1->is_avc;
1541 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1542 MAX_SPS_COUNT, sizeof(SPS));
1544 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1545 MAX_PPS_COUNT, sizeof(PPS));
1548 // Dequantization matrices
1549 // FIXME these are big - can they be only copied when PPS changes?
1550 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1552 for (i = 0; i < 6; i++)
1553 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1554 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1556 for (i = 0; i < 6; i++)
1557 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1558 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1560 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1563 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1566 copy_fields(h, h1, ref_count, list_count);
1567 copy_fields(h, h1, ref2frm, intra_gb);
1568 copy_fields(h, h1, short_ref, cabac_init_idc);
1570 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1571 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1572 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1573 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1575 h->last_slice_type = h1->last_slice_type;
1577 if (context_reinitialized)
1578 h264_set_parameter_from_sps(h);
1580 if (!h->cur_pic_ptr)
1583 if (!h->droppable) {
1584 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1585 h->prev_poc_msb = h->poc_msb;
1586 h->prev_poc_lsb = h->poc_lsb;
1588 h->prev_frame_num_offset = h->frame_num_offset;
1589 h->prev_frame_num = h->frame_num;
1590 h->outputed_poc = h->next_outputed_poc;
1595 int ff_h264_frame_start(H264Context *h)
1599 const int pixel_shift = h->pixel_shift;
1601 release_unused_pictures(h, 1);
1602 h->cur_pic_ptr = NULL;
1604 i = find_unused_picture(h);
1606 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1611 pic->f.reference = h->droppable ? 0 : h->picture_structure;
1612 pic->f.coded_picture_number = h->coded_picture_number++;
1613 pic->field_picture = h->picture_structure != PICT_FRAME;
1615 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1617 * See decode_nal_units().
1619 pic->f.key_frame = 0;
1620 pic->mmco_reset = 0;
1622 if ((ret = alloc_picture(h, pic)) < 0)
1625 h->cur_pic_ptr = pic;
1626 h->cur_pic = *h->cur_pic_ptr;
1627 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1629 ff_er_frame_start(&h->er);
1631 assert(h->linesize && h->uvlinesize);
1633 for (i = 0; i < 16; i++) {
1634 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1635 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1637 for (i = 0; i < 16; i++) {
1638 h->block_offset[16 + i] =
1639 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1640 h->block_offset[48 + 16 + i] =
1641 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1644 /* can't be in alloc_tables because linesize isn't known there.
1645 * FIXME: redo bipred weight to not require extra buffer? */
1646 for (i = 0; i < h->slice_context_count; i++)
1647 if (h->thread_context[i]) {
1648 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1653 /* Some macroblocks can be accessed before they're available in case
1654 * of lost slices, MBAFF or threading. */
1655 memset(h->slice_table, -1,
1656 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1658 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1659 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1661 /* We mark the current picture as non-reference after allocating it, so
1662 * that if we break out due to an error it can be released automatically
1663 * in the next ff_MPV_frame_start().
1664 * SVQ3 as well as most other codecs have only last/next/current and thus
1665 * get released even with set reference, besides SVQ3 and others do not
1666 * mark frames as reference later "naturally". */
1667 if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
1668 h->cur_pic_ptr->f.reference = 0;
1670 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1672 h->next_output_pic = NULL;
1674 assert(h->cur_pic_ptr->long_ref == 0);
1680 * Run setup operations that must be run after slice header decoding.
1681 * This includes finding the next displayed frame.
1683 * @param h h264 master context
1684 * @param setup_finished enough NALs have been read that we can call
1685 * ff_thread_finish_setup()
1687 static void decode_postinit(H264Context *h, int setup_finished)
1689 Picture *out = h->cur_pic_ptr;
1690 Picture *cur = h->cur_pic_ptr;
1691 int i, pics, out_of_order, out_idx;
1692 int invalid = 0, cnt = 0;
1694 h->cur_pic_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1695 h->cur_pic_ptr->f.pict_type = h->pict_type;
1697 if (h->next_output_pic)
1700 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1701 /* FIXME: if we have two PAFF fields in one packet, we can't start
1702 * the next thread here. If we have one field per packet, we can.
1703 * The check in decode_nal_units() is not good enough to find this
1704 * yet, so we assume the worst for now. */
1705 // if (setup_finished)
1706 // ff_thread_finish_setup(h->avctx);
1710 cur->f.interlaced_frame = 0;
1711 cur->f.repeat_pict = 0;
1713 /* Signal interlacing information externally. */
1714 /* Prioritize picture timing SEI information over used
1715 * decoding process if it exists. */
1717 if (h->sps.pic_struct_present_flag) {
1718 switch (h->sei_pic_struct) {
1719 case SEI_PIC_STRUCT_FRAME:
1721 case SEI_PIC_STRUCT_TOP_FIELD:
1722 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1723 cur->f.interlaced_frame = 1;
1725 case SEI_PIC_STRUCT_TOP_BOTTOM:
1726 case SEI_PIC_STRUCT_BOTTOM_TOP:
1727 if (FIELD_OR_MBAFF_PICTURE)
1728 cur->f.interlaced_frame = 1;
1730 // try to flag soft telecine progressive
1731 cur->f.interlaced_frame = h->prev_interlaced_frame;
1733 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1734 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1735 /* Signal the possibility of telecined film externally
1736 * (pic_struct 5,6). From these hints, let the applications
1737 * decide if they apply deinterlacing. */
1738 cur->f.repeat_pict = 1;
1740 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1741 cur->f.repeat_pict = 2;
1743 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1744 cur->f.repeat_pict = 4;
1748 if ((h->sei_ct_type & 3) &&
1749 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1750 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1752 /* Derive interlacing flag from used decoding process. */
1753 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1755 h->prev_interlaced_frame = cur->f.interlaced_frame;
1757 if (cur->field_poc[0] != cur->field_poc[1]) {
1758 /* Derive top_field_first from field pocs. */
1759 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1761 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1762 /* Use picture timing SEI information. Even if it is a
1763 * information of a past frame, better than nothing. */
1764 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1765 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1766 cur->f.top_field_first = 1;
1768 cur->f.top_field_first = 0;
1770 /* Most likely progressive */
1771 cur->f.top_field_first = 0;
1775 // FIXME do something with unavailable reference frames
1777 /* Sort B-frames into display order */
1779 if (h->sps.bitstream_restriction_flag &&
1780 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1781 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1785 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1786 !h->sps.bitstream_restriction_flag) {
1787 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1792 while (h->delayed_pic[pics])
1795 assert(pics <= MAX_DELAYED_PIC_COUNT);
1797 h->delayed_pic[pics++] = cur;
1798 if (cur->f.reference == 0)
1799 cur->f.reference = DELAYED_PIC_REF;
1801 /* Frame reordering. This code takes pictures from coding order and sorts
1802 * them by their incremental POC value into display order. It supports POC
1803 * gaps, MMCO reset codes and random resets.
1804 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1805 * and/or can be closed down with a MMCO reset code. In sequences where
1806 * there is no delay, we can't detect that (since the frame was already
1807 * output to the user), so we also set h->mmco_reset to detect the MMCO
1809 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
1810 * we increase the delay between input and output. All frames affected by
1811 * the lag (e.g. those that should have been output before another frame
1812 * that we already returned to the user) will be dropped. This is a bug
1813 * that we will fix later. */
1814 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1815 cnt += out->poc < h->last_pocs[i];
1816 invalid += out->poc == INT_MIN;
1818 if (!h->mmco_reset && !cur->f.key_frame &&
1819 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1822 h->delayed_pic[pics - 2]->mmco_reset = 2;
1824 if (h->mmco_reset || cur->f.key_frame) {
1825 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1826 h->last_pocs[i] = INT_MIN;
1828 invalid = MAX_DELAYED_PIC_COUNT;
1830 out = h->delayed_pic[0];
1832 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1833 h->delayed_pic[i] &&
1834 !h->delayed_pic[i - 1]->mmco_reset &&
1835 !h->delayed_pic[i]->f.key_frame;
1837 if (h->delayed_pic[i]->poc < out->poc) {
1838 out = h->delayed_pic[i];
1841 if (h->avctx->has_b_frames == 0 &&
1842 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
1843 h->next_outputed_poc = INT_MIN;
1844 out_of_order = !out->f.key_frame && !h->mmco_reset &&
1845 (out->poc < h->next_outputed_poc);
1847 if (h->sps.bitstream_restriction_flag &&
1848 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
1849 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1850 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1851 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1852 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
1855 } else if (h->low_delay &&
1856 ((h->next_outputed_poc != INT_MIN &&
1857 out->poc > h->next_outputed_poc + 2) ||
1858 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
1860 h->avctx->has_b_frames++;
1863 if (pics > h->avctx->has_b_frames) {
1864 out->f.reference &= ~DELAYED_PIC_REF;
1865 // for frame threading, the owner must be the second field's thread or
1866 // else the first thread can release the picture and reuse it unsafely
1868 for (i = out_idx; h->delayed_pic[i]; i++)
1869 h->delayed_pic[i] = h->delayed_pic[i + 1];
1871 memmove(h->last_pocs, &h->last_pocs[1],
1872 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1873 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1874 if (!out_of_order && pics > h->avctx->has_b_frames) {
1875 h->next_output_pic = out;
1876 if (out->mmco_reset) {
1878 h->next_outputed_poc = out->poc;
1879 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1881 h->next_outputed_poc = INT_MIN;
1884 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
1885 h->next_outputed_poc = INT_MIN;
1887 h->next_outputed_poc = out->poc;
1892 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
1896 ff_thread_finish_setup(h->avctx);
1899 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1900 uint8_t *src_cb, uint8_t *src_cr,
1901 int linesize, int uvlinesize,
1904 uint8_t *top_border;
1906 const int pixel_shift = h->pixel_shift;
1907 int chroma444 = CHROMA444;
1908 int chroma422 = CHROMA422;
1911 src_cb -= uvlinesize;
1912 src_cr -= uvlinesize;
1914 if (!simple && FRAME_MBAFF) {
1917 top_border = h->top_borders[0][h->mb_x];
1918 AV_COPY128(top_border, src_y + 15 * linesize);
1920 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1921 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
1924 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1925 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1926 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1927 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1929 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1930 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1932 } else if (chroma422) {
1934 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1935 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1937 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1938 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1942 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1943 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1945 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1946 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1951 } else if (MB_MBAFF) {
1957 top_border = h->top_borders[top_idx][h->mb_x];
1958 /* There are two lines saved, the line above the top macroblock
1959 * of a pair, and the line above the bottom macroblock. */
1960 AV_COPY128(top_border, src_y + 16 * linesize);
1962 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1964 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
1967 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1968 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1969 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1970 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1972 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1973 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1975 } else if (chroma422) {
1977 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1978 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1980 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1981 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
1985 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
1986 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
1988 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
1989 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
1995 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
1996 uint8_t *src_cb, uint8_t *src_cr,
1997 int linesize, int uvlinesize,
1998 int xchg, int chroma444,
1999 int simple, int pixel_shift)
2001 int deblock_topleft;
2004 uint8_t *top_border_m1;
2005 uint8_t *top_border;
2007 if (!simple && FRAME_MBAFF) {
2012 top_idx = MB_MBAFF ? 0 : 1;
2016 if (h->deblocking_filter == 2) {
2017 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2018 deblock_top = h->top_type;
2020 deblock_topleft = (h->mb_x > 0);
2021 deblock_top = (h->mb_y > !!MB_FIELD);
2024 src_y -= linesize + 1 + pixel_shift;
2025 src_cb -= uvlinesize + 1 + pixel_shift;
2026 src_cr -= uvlinesize + 1 + pixel_shift;
2028 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2029 top_border = h->top_borders[top_idx][h->mb_x];
2031 #define XCHG(a, b, xchg) \
2032 if (pixel_shift) { \
2034 AV_SWAP64(b + 0, a + 0); \
2035 AV_SWAP64(b + 8, a + 8); \
2045 if (deblock_topleft) {
2046 XCHG(top_border_m1 + (8 << pixel_shift),
2047 src_y - (7 << pixel_shift), 1);
2049 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2050 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2051 if (h->mb_x + 1 < h->mb_width) {
2052 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2053 src_y + (17 << pixel_shift), 1);
2056 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2058 if (deblock_topleft) {
2059 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2060 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2062 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2063 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2064 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2065 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2066 if (h->mb_x + 1 < h->mb_width) {
2067 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2068 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2072 if (deblock_topleft) {
2073 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2074 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2076 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2077 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2083 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2086 if (high_bit_depth) {
2087 return AV_RN32A(((int32_t *)mb) + index);
2089 return AV_RN16A(mb + index);
2092 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2093 int index, int value)
2095 if (high_bit_depth) {
2096 AV_WN32A(((int32_t *)mb) + index, value);
2098 AV_WN16A(mb + index, value);
2101 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2102 int mb_type, int is_h264,
2104 int transform_bypass,
2108 uint8_t *dest_y, int p)
2110 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2111 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2113 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2114 block_offset += 16 * p;
2115 if (IS_INTRA4x4(mb_type)) {
2116 if (IS_8x8DCT(mb_type)) {
2117 if (transform_bypass) {
2119 idct_add = h->dsp.add_pixels8;
2121 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2122 idct_add = h->h264dsp.h264_idct8_add;
2124 for (i = 0; i < 16; i += 4) {
2125 uint8_t *const ptr = dest_y + block_offset[i];
2126 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2127 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2128 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2130 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2131 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2132 (h->topright_samples_available << i) & 0x4000, linesize);
2134 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2135 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2137 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2142 if (transform_bypass) {
2144 idct_add = h->dsp.add_pixels4;
2146 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2147 idct_add = h->h264dsp.h264_idct_add;
2149 for (i = 0; i < 16; i++) {
2150 uint8_t *const ptr = dest_y + block_offset[i];
2151 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2153 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2154 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2159 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2160 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2161 assert(h->mb_y || linesize <= block_offset[i]);
2162 if (!topright_avail) {
2164 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2165 topright = (uint8_t *)&tr_high;
2167 tr = ptr[3 - linesize] * 0x01010101u;
2168 topright = (uint8_t *)&tr;
2171 topright = ptr + (4 << pixel_shift) - linesize;
2175 h->hpc.pred4x4[dir](ptr, topright, linesize);
2176 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2179 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2180 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2182 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2183 } else if (CONFIG_SVQ3_DECODER)
2184 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2190 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2192 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2193 if (!transform_bypass)
2194 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2196 h->dequant4_coeff[p][qscale][0]);
2198 static const uint8_t dc_mapping[16] = {
2199 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2200 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2201 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2202 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
2203 for (i = 0; i < 16; i++)
2204 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2205 pixel_shift, dc_mapping[i],
2206 dctcoef_get(h->mb_luma_dc[p],
2210 } else if (CONFIG_SVQ3_DECODER)
2211 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2212 h->mb_luma_dc[p], qscale);
2216 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2217 int is_h264, int simple,
2218 int transform_bypass,
2222 uint8_t *dest_y, int p)
2224 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2226 block_offset += 16 * p;
2227 if (!IS_INTRA4x4(mb_type)) {
2229 if (IS_INTRA16x16(mb_type)) {
2230 if (transform_bypass) {
2231 if (h->sps.profile_idc == 244 &&
2232 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2233 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2234 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2235 h->mb + (p * 256 << pixel_shift),
2238 for (i = 0; i < 16; i++)
2239 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2240 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2241 h->dsp.add_pixels4(dest_y + block_offset[i],
2242 h->mb + (i * 16 + p * 256 << pixel_shift),
2246 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2247 h->mb + (p * 256 << pixel_shift),
2249 h->non_zero_count_cache + p * 5 * 8);
2251 } else if (h->cbp & 15) {
2252 if (transform_bypass) {
2253 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2254 idct_add = IS_8x8DCT(mb_type) ? h->dsp.add_pixels8
2255 : h->dsp.add_pixels4;
2256 for (i = 0; i < 16; i += di)
2257 if (h->non_zero_count_cache[scan8[i + p * 16]])
2258 idct_add(dest_y + block_offset[i],
2259 h->mb + (i * 16 + p * 256 << pixel_shift),
2262 if (IS_8x8DCT(mb_type))
2263 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2264 h->mb + (p * 256 << pixel_shift),
2266 h->non_zero_count_cache + p * 5 * 8);
2268 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2269 h->mb + (p * 256 << pixel_shift),
2271 h->non_zero_count_cache + p * 5 * 8);
2274 } else if (CONFIG_SVQ3_DECODER) {
2275 for (i = 0; i < 16; i++)
2276 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2277 // FIXME benchmark weird rule, & below
2278 uint8_t *const ptr = dest_y + block_offset[i];
2279 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2280 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2288 #include "h264_mb_template.c"
2292 #include "h264_mb_template.c"
2296 #include "h264_mb_template.c"
2298 void ff_h264_hl_decode_mb(H264Context *h)
2300 const int mb_xy = h->mb_xy;
2301 const int mb_type = h->cur_pic.f.mb_type[mb_xy];
2302 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
2305 if (is_complex || h->pixel_shift)
2306 hl_decode_mb_444_complex(h);
2308 hl_decode_mb_444_simple_8(h);
2309 } else if (is_complex) {
2310 hl_decode_mb_complex(h);
2311 } else if (h->pixel_shift) {
2312 hl_decode_mb_simple_16(h);
2314 hl_decode_mb_simple_8(h);
2317 static int pred_weight_table(H264Context *h)
2320 int luma_def, chroma_def;
2323 h->use_weight_chroma = 0;
2324 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2325 if (h->sps.chroma_format_idc)
2326 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2327 luma_def = 1 << h->luma_log2_weight_denom;
2328 chroma_def = 1 << h->chroma_log2_weight_denom;
2330 for (list = 0; list < 2; list++) {
2331 h->luma_weight_flag[list] = 0;
2332 h->chroma_weight_flag[list] = 0;
2333 for (i = 0; i < h->ref_count[list]; i++) {
2334 int luma_weight_flag, chroma_weight_flag;
2336 luma_weight_flag = get_bits1(&h->gb);
2337 if (luma_weight_flag) {
2338 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2339 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2340 if (h->luma_weight[i][list][0] != luma_def ||
2341 h->luma_weight[i][list][1] != 0) {
2343 h->luma_weight_flag[list] = 1;
2346 h->luma_weight[i][list][0] = luma_def;
2347 h->luma_weight[i][list][1] = 0;
2350 if (h->sps.chroma_format_idc) {
2351 chroma_weight_flag = get_bits1(&h->gb);
2352 if (chroma_weight_flag) {
2354 for (j = 0; j < 2; j++) {
2355 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2356 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2357 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2358 h->chroma_weight[i][list][j][1] != 0) {
2359 h->use_weight_chroma = 1;
2360 h->chroma_weight_flag[list] = 1;
2365 for (j = 0; j < 2; j++) {
2366 h->chroma_weight[i][list][j][0] = chroma_def;
2367 h->chroma_weight[i][list][j][1] = 0;
2372 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2375 h->use_weight = h->use_weight || h->use_weight_chroma;
2380 * Initialize implicit_weight table.
2381 * @param field 0/1 initialize the weight for interlaced MBAFF
2382 * -1 initializes the rest
2384 static void implicit_weight_table(H264Context *h, int field)
2386 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2388 for (i = 0; i < 2; i++) {
2389 h->luma_weight_flag[i] = 0;
2390 h->chroma_weight_flag[i] = 0;
2394 if (h->picture_structure == PICT_FRAME) {
2395 cur_poc = h->cur_pic_ptr->poc;
2397 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2399 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2400 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2402 h->use_weight_chroma = 0;
2406 ref_count0 = h->ref_count[0];
2407 ref_count1 = h->ref_count[1];
2409 cur_poc = h->cur_pic_ptr->field_poc[field];
2411 ref_count0 = 16 + 2 * h->ref_count[0];
2412 ref_count1 = 16 + 2 * h->ref_count[1];
2416 h->use_weight_chroma = 2;
2417 h->luma_log2_weight_denom = 5;
2418 h->chroma_log2_weight_denom = 5;
2420 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2421 int poc0 = h->ref_list[0][ref0].poc;
2422 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2424 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2425 int poc1 = h->ref_list[1][ref1].poc;
2426 int td = av_clip(poc1 - poc0, -128, 127);
2428 int tb = av_clip(cur_poc - poc0, -128, 127);
2429 int tx = (16384 + (FFABS(td) >> 1)) / td;
2430 int dist_scale_factor = (tb * tx + 32) >> 8;
2431 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2432 w = 64 - dist_scale_factor;
2436 h->implicit_weight[ref0][ref1][0] =
2437 h->implicit_weight[ref0][ref1][1] = w;
2439 h->implicit_weight[ref0][ref1][field] = w;
2446 * instantaneous decoder refresh.
2448 static void idr(H264Context *h)
2450 ff_h264_remove_all_refs(h);
2451 h->prev_frame_num = 0;
2452 h->prev_frame_num_offset = 0;
2454 h->prev_poc_lsb = 0;
2457 /* forget old pics after a seek */
2458 static void flush_change(H264Context *h)
2461 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2462 h->last_pocs[i] = INT_MIN;
2463 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2464 h->prev_interlaced_frame = 1;
2467 h->cur_pic_ptr->f.reference = 0;
2469 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2470 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2471 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2472 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2473 ff_h264_reset_sei(h);
2476 /* forget old pics after a seek */
2477 static void flush_dpb(AVCodecContext *avctx)
2479 H264Context *h = avctx->priv_data;
2482 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2483 if (h->delayed_pic[i])
2484 h->delayed_pic[i]->f.reference = 0;
2485 h->delayed_pic[i] = NULL;
2490 for (i = 0; i < h->picture_count; i++) {
2491 if (h->DPB[i].f.data[0])
2492 free_frame_buffer(h, &h->DPB[i]);
2494 h->cur_pic_ptr = NULL;
2496 h->mb_x = h->mb_y = 0;
2498 h->parse_context.state = -1;
2499 h->parse_context.frame_start_found = 0;
2500 h->parse_context.overread = 0;
2501 h->parse_context.overread_index = 0;
2502 h->parse_context.index = 0;
2503 h->parse_context.last_index = 0;
2506 static int init_poc(H264Context *h)
2508 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2510 Picture *cur = h->cur_pic_ptr;
2512 h->frame_num_offset = h->prev_frame_num_offset;
2513 if (h->frame_num < h->prev_frame_num)
2514 h->frame_num_offset += max_frame_num;
2516 if (h->sps.poc_type == 0) {
2517 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2519 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2520 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2521 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2522 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2524 h->poc_msb = h->prev_poc_msb;
2526 field_poc[1] = h->poc_msb + h->poc_lsb;
2527 if (h->picture_structure == PICT_FRAME)
2528 field_poc[1] += h->delta_poc_bottom;
2529 } else if (h->sps.poc_type == 1) {
2530 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2533 if (h->sps.poc_cycle_length != 0)
2534 abs_frame_num = h->frame_num_offset + h->frame_num;
2538 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2541 expected_delta_per_poc_cycle = 0;
2542 for (i = 0; i < h->sps.poc_cycle_length; i++)
2543 // FIXME integrate during sps parse
2544 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2546 if (abs_frame_num > 0) {
2547 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2548 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2550 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2551 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2552 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2556 if (h->nal_ref_idc == 0)
2557 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2559 field_poc[0] = expectedpoc + h->delta_poc[0];
2560 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2562 if (h->picture_structure == PICT_FRAME)
2563 field_poc[1] += h->delta_poc[1];
2565 int poc = 2 * (h->frame_num_offset + h->frame_num);
2567 if (!h->nal_ref_idc)
2574 if (h->picture_structure != PICT_BOTTOM_FIELD)
2575 h->cur_pic_ptr->field_poc[0] = field_poc[0];
2576 if (h->picture_structure != PICT_TOP_FIELD)
2577 h->cur_pic_ptr->field_poc[1] = field_poc[1];
2578 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2584 * initialize scan tables
2586 static void init_scan_tables(H264Context *h)
2589 for (i = 0; i < 16; i++) {
2590 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2591 h->zigzag_scan[i] = T(zigzag_scan[i]);
2592 h->field_scan[i] = T(field_scan[i]);
2595 for (i = 0; i < 64; i++) {
2596 #define T(x) (x >> 3) | ((x & 7) << 3)
2597 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2598 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2599 h->field_scan8x8[i] = T(field_scan8x8[i]);
2600 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2603 if (h->sps.transform_bypass) { // FIXME same ugly
2604 h->zigzag_scan_q0 = zigzag_scan;
2605 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2606 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2607 h->field_scan_q0 = field_scan;
2608 h->field_scan8x8_q0 = field_scan8x8;
2609 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2611 h->zigzag_scan_q0 = h->zigzag_scan;
2612 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2613 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2614 h->field_scan_q0 = h->field_scan;
2615 h->field_scan8x8_q0 = h->field_scan8x8;
2616 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2620 static int field_end(H264Context *h, int in_setup)
2622 AVCodecContext *const avctx = h->avctx;
2626 if (!in_setup && !h->droppable)
2627 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
2628 h->picture_structure == PICT_BOTTOM_FIELD);
2630 if (CONFIG_H264_VDPAU_DECODER &&
2631 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2632 ff_vdpau_h264_set_reference_frames(h);
2634 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2635 if (!h->droppable) {
2636 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2637 h->prev_poc_msb = h->poc_msb;
2638 h->prev_poc_lsb = h->poc_lsb;
2640 h->prev_frame_num_offset = h->frame_num_offset;
2641 h->prev_frame_num = h->frame_num;
2642 h->outputed_poc = h->next_outputed_poc;
2645 if (avctx->hwaccel) {
2646 if (avctx->hwaccel->end_frame(avctx) < 0)
2647 av_log(avctx, AV_LOG_ERROR,
2648 "hardware accelerator failed to decode picture\n");
2651 if (CONFIG_H264_VDPAU_DECODER &&
2652 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2653 ff_vdpau_h264_picture_complete(h);
2656 * FIXME: Error handling code does not seem to support interlaced
2657 * when slices span multiple rows
2658 * The ff_er_add_slice calls don't work right for bottom
2659 * fields; they cause massive erroneous error concealing
2660 * Error marking covers both fields (top and bottom).
2661 * This causes a mismatched s->error_count
2662 * and a bad error table. Further, the error count goes to
2663 * INT_MAX when called for bottom field, because mb_y is
2664 * past end by one (callers fault) and resync_mb_y != 0
2665 * causes problems for the first MB line, too.
2667 if (!FIELD_PICTURE) {
2668 h->er.cur_pic = h->cur_pic_ptr;
2669 h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
2670 h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
2671 ff_er_frame_end(&h->er);
2674 /* redraw edges for the frame if decoding didn't complete */
2675 if (h->er.error_count &&
2676 !h->avctx->hwaccel &&
2677 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) &&
2678 h->cur_pic_ptr->f.reference &&
2679 !(h->flags & CODEC_FLAG_EMU_EDGE)) {
2680 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(h->avctx->pix_fmt);
2681 int hshift = desc->log2_chroma_w;
2682 int vshift = desc->log2_chroma_h;
2683 h->dsp.draw_edges(h->cur_pic.f.data[0], h->linesize,
2684 h->mb_width * 16, h->mb_height * 16,
2685 EDGE_WIDTH, EDGE_WIDTH,
2686 EDGE_TOP | EDGE_BOTTOM);
2687 h->dsp.draw_edges(h->cur_pic.f.data[1], h->uvlinesize,
2688 (h->mb_width * 16) >> hshift, (h->mb_height * 16) >> vshift,
2689 EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
2690 EDGE_TOP | EDGE_BOTTOM);
2691 h->dsp.draw_edges(h->cur_pic.f.data[2], h->uvlinesize,
2692 (h->mb_width * 16) >> hshift, (h->mb_height * 16) >> vshift,
2693 EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
2694 EDGE_TOP | EDGE_BOTTOM);
2698 h->current_slice = 0;
2704 * Replicate H264 "master" context to thread contexts.
2706 static int clone_slice(H264Context *dst, H264Context *src)
2708 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2709 dst->cur_pic_ptr = src->cur_pic_ptr;
2710 dst->cur_pic = src->cur_pic;
2711 dst->linesize = src->linesize;
2712 dst->uvlinesize = src->uvlinesize;
2713 dst->first_field = src->first_field;
2715 dst->prev_poc_msb = src->prev_poc_msb;
2716 dst->prev_poc_lsb = src->prev_poc_lsb;
2717 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2718 dst->prev_frame_num = src->prev_frame_num;
2719 dst->short_ref_count = src->short_ref_count;
2721 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2722 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2723 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2725 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2726 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2732 * Compute profile from profile_idc and constraint_set?_flags.
2736 * @return profile as defined by FF_PROFILE_H264_*
2738 int ff_h264_get_profile(SPS *sps)
2740 int profile = sps->profile_idc;
2742 switch (sps->profile_idc) {
2743 case FF_PROFILE_H264_BASELINE:
2744 // constraint_set1_flag set to 1
2745 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2747 case FF_PROFILE_H264_HIGH_10:
2748 case FF_PROFILE_H264_HIGH_422:
2749 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2750 // constraint_set3_flag set to 1
2751 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2758 static int h264_set_parameter_from_sps(H264Context *h)
2760 if (h->flags & CODEC_FLAG_LOW_DELAY ||
2761 (h->sps.bitstream_restriction_flag &&
2762 !h->sps.num_reorder_frames)) {
2763 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2764 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
2765 "Reenabling low delay requires a codec flush.\n");
2770 if (h->avctx->has_b_frames < 2)
2771 h->avctx->has_b_frames = !h->low_delay;
2773 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2774 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2775 if (h->avctx->codec &&
2776 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2777 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2778 av_log(h->avctx, AV_LOG_ERROR,
2779 "VDPAU decoding does not support video colorspace.\n");
2780 return AVERROR_INVALIDDATA;
2782 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
2783 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2784 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2785 h->pixel_shift = h->sps.bit_depth_luma > 8;
2787 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2788 h->sps.chroma_format_idc);
2789 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2790 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2791 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
2792 h->sps.chroma_format_idc);
2793 h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2794 ff_dsputil_init(&h->dsp, h->avctx);
2795 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
2797 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2798 h->sps.bit_depth_luma);
2799 return AVERROR_INVALIDDATA;
2805 static enum PixelFormat get_pixel_format(H264Context *h)
2807 switch (h->sps.bit_depth_luma) {
2810 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2811 return AV_PIX_FMT_GBRP9;
2813 return AV_PIX_FMT_YUV444P9;
2814 } else if (CHROMA422)
2815 return AV_PIX_FMT_YUV422P9;
2817 return AV_PIX_FMT_YUV420P9;
2821 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2822 return AV_PIX_FMT_GBRP10;
2824 return AV_PIX_FMT_YUV444P10;
2825 } else if (CHROMA422)
2826 return AV_PIX_FMT_YUV422P10;
2828 return AV_PIX_FMT_YUV420P10;
2832 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2833 return AV_PIX_FMT_GBRP;
2835 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2836 : AV_PIX_FMT_YUV444P;
2837 } else if (CHROMA422) {
2838 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2839 : AV_PIX_FMT_YUV422P;
2841 return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
2842 h->avctx->codec->pix_fmts :
2843 h->avctx->color_range == AVCOL_RANGE_JPEG ?
2844 hwaccel_pixfmt_list_h264_jpeg_420 :
2845 ff_hwaccel_pixfmt_list_420);
2849 av_log(h->avctx, AV_LOG_ERROR,
2850 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2851 return AVERROR_INVALIDDATA;
2855 static int h264_slice_header_init(H264Context *h, int reinit)
2857 int nb_slices = (HAVE_THREADS &&
2858 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
2859 h->avctx->thread_count : 1;
2862 avcodec_set_dimensions(h->avctx, h->width, h->height);
2863 h->avctx->sample_aspect_ratio = h->sps.sar;
2864 av_assert0(h->avctx->sample_aspect_ratio.den);
2865 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
2866 &h->chroma_x_shift, &h->chroma_y_shift);
2868 if (h->sps.timing_info_present_flag) {
2869 int64_t den = h->sps.time_scale;
2870 if (h->x264_build < 44U)
2872 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
2873 h->sps.num_units_in_tick, den, 1 << 30);
2876 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
2881 h->prev_interlaced_frame = 1;
2883 init_scan_tables(h);
2884 if (ff_h264_alloc_tables(h) < 0) {
2885 av_log(h->avctx, AV_LOG_ERROR,
2886 "Could not allocate memory for h264\n");
2887 return AVERROR(ENOMEM);
2890 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
2893 max_slices = FFMIN(MAX_THREADS, h->mb_height);
2895 max_slices = MAX_THREADS;
2896 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
2897 " reducing to %d\n", nb_slices, max_slices);
2898 nb_slices = max_slices;
2900 h->slice_context_count = nb_slices;
2902 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
2903 if (context_init(h) < 0) {
2904 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
2908 for (i = 1; i < h->slice_context_count; i++) {
2910 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
2911 c->avctx = h->avctx;
2914 c->h264dsp = h->h264dsp;
2915 c->h264qpel = h->h264qpel;
2916 c->h264chroma = h->h264chroma;
2919 c->pixel_shift = h->pixel_shift;
2920 c->width = h->width;
2921 c->height = h->height;
2922 c->linesize = h->linesize;
2923 c->uvlinesize = h->uvlinesize;
2924 c->chroma_x_shift = h->chroma_x_shift;
2925 c->chroma_y_shift = h->chroma_y_shift;
2926 c->qscale = h->qscale;
2927 c->droppable = h->droppable;
2928 c->data_partitioning = h->data_partitioning;
2929 c->low_delay = h->low_delay;
2930 c->mb_width = h->mb_width;
2931 c->mb_height = h->mb_height;
2932 c->mb_stride = h->mb_stride;
2933 c->mb_num = h->mb_num;
2934 c->flags = h->flags;
2935 c->workaround_bugs = h->workaround_bugs;
2936 c->pict_type = h->pict_type;
2938 init_scan_tables(c);
2939 clone_tables(c, h, i);
2940 c->context_initialized = 1;
2943 for (i = 0; i < h->slice_context_count; i++)
2944 if (context_init(h->thread_context[i]) < 0) {
2945 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
2950 h->context_initialized = 1;
2956 * Decode a slice header.
2957 * This will also call ff_MPV_common_init() and frame_start() as needed.
2959 * @param h h264context
2960 * @param h0 h264 master context (differs from 'h' when doing sliced based
2961 * parallel decoding)
2963 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2965 static int decode_slice_header(H264Context *h, H264Context *h0)
2967 unsigned int first_mb_in_slice;
2968 unsigned int pps_id;
2969 int num_ref_idx_active_override_flag, max_refs, ret;
2970 unsigned int slice_type, tmp, i, j;
2971 int default_ref_list_done = 0;
2972 int last_pic_structure, last_pic_droppable;
2973 int needs_reinit = 0;
2975 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
2976 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
2978 first_mb_in_slice = get_ue_golomb(&h->gb);
2980 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2981 if (h0->current_slice && FIELD_PICTURE) {
2985 h0->current_slice = 0;
2986 if (!h0->first_field) {
2987 if (h->cur_pic_ptr && !h->droppable &&
2988 h->cur_pic_ptr->owner2 == h) {
2989 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
2990 h->picture_structure == PICT_BOTTOM_FIELD);
2992 h->cur_pic_ptr = NULL;
2996 slice_type = get_ue_golomb_31(&h->gb);
2997 if (slice_type > 9) {
2998 av_log(h->avctx, AV_LOG_ERROR,
2999 "slice type too large (%d) at %d %d\n",
3000 h->slice_type, h->mb_x, h->mb_y);
3003 if (slice_type > 4) {
3005 h->slice_type_fixed = 1;
3007 h->slice_type_fixed = 0;
3009 slice_type = golomb_to_pict_type[slice_type];
3010 if (slice_type == AV_PICTURE_TYPE_I ||
3011 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3012 default_ref_list_done = 1;
3014 h->slice_type = slice_type;
3015 h->slice_type_nos = slice_type & 3;
3017 // to make a few old functions happy, it's wrong though
3018 h->pict_type = h->slice_type;
3020 pps_id = get_ue_golomb(&h->gb);
3021 if (pps_id >= MAX_PPS_COUNT) {
3022 av_log(h->avctx, AV_LOG_ERROR, "pps_id out of range\n");
3025 if (!h0->pps_buffers[pps_id]) {
3026 av_log(h->avctx, AV_LOG_ERROR,
3027 "non-existing PPS %u referenced\n",
3031 h->pps = *h0->pps_buffers[pps_id];
3033 if (!h0->sps_buffers[h->pps.sps_id]) {
3034 av_log(h->avctx, AV_LOG_ERROR,
3035 "non-existing SPS %u referenced\n",
3040 if (h->pps.sps_id != h->current_sps_id ||
3041 h0->sps_buffers[h->pps.sps_id]->new) {
3042 h0->sps_buffers[h->pps.sps_id]->new = 0;
3044 h->current_sps_id = h->pps.sps_id;
3045 h->sps = *h0->sps_buffers[h->pps.sps_id];
3047 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3048 h->chroma_format_idc != h->sps.chroma_format_idc) {
3049 h->bit_depth_luma = h->sps.bit_depth_luma;
3050 h->chroma_format_idc = h->sps.chroma_format_idc;
3053 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3057 h->avctx->profile = ff_h264_get_profile(&h->sps);
3058 h->avctx->level = h->sps.level_idc;
3059 h->avctx->refs = h->sps.ref_frame_count;
3061 if (h->mb_width != h->sps.mb_width ||
3062 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
3065 h->mb_width = h->sps.mb_width;
3066 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3067 h->mb_num = h->mb_width * h->mb_height;
3068 h->mb_stride = h->mb_width + 1;
3070 h->b_stride = h->mb_width * 4;
3072 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3074 h->width = 16 * h->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
3075 if (h->sps.frame_mbs_only_flag)
3076 h->height = 16 * h->mb_height - (1 << h->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> h->chroma_y_shift) - 1);
3078 h->height = 16 * h->mb_height - (2 << h->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> h->chroma_y_shift) - 1);
3080 if (FFALIGN(h->avctx->width, 16) == h->width &&
3081 FFALIGN(h->avctx->height, 16) == h->height) {
3082 h->width = h->avctx->width;
3083 h->height = h->avctx->height;
3086 if (h->sps.video_signal_type_present_flag) {
3087 h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
3089 if (h->sps.colour_description_present_flag) {
3090 if (h->avctx->colorspace != h->sps.colorspace)
3092 h->avctx->color_primaries = h->sps.color_primaries;
3093 h->avctx->color_trc = h->sps.color_trc;
3094 h->avctx->colorspace = h->sps.colorspace;
3098 if (h->context_initialized &&
3099 (h->width != h->avctx->width ||
3100 h->height != h->avctx->height ||
3104 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3105 "slice %d\n", h0->current_slice + 1);
3106 return AVERROR_INVALIDDATA;
3111 if ((ret = get_pixel_format(h)) < 0)
3113 h->avctx->pix_fmt = ret;
3115 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3116 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3118 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3119 av_log(h->avctx, AV_LOG_ERROR,
3120 "h264_slice_header_init() failed\n");
3124 if (!h->context_initialized) {
3126 av_log(h->avctx, AV_LOG_ERROR,
3127 "Cannot (re-)initialize context during parallel decoding.\n");
3131 if ((ret = get_pixel_format(h)) < 0)
3133 h->avctx->pix_fmt = ret;
3135 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3136 av_log(h->avctx, AV_LOG_ERROR,
3137 "h264_slice_header_init() failed\n");
3142 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3143 h->dequant_coeff_pps = pps_id;
3144 init_dequant_tables(h);
3147 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3150 h->mb_aff_frame = 0;
3151 last_pic_structure = h0->picture_structure;
3152 last_pic_droppable = h0->droppable;
3153 h->droppable = h->nal_ref_idc == 0;
3154 if (h->sps.frame_mbs_only_flag) {
3155 h->picture_structure = PICT_FRAME;
3157 if (get_bits1(&h->gb)) { // field_pic_flag
3158 h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
3160 h->picture_structure = PICT_FRAME;
3161 h->mb_aff_frame = h->sps.mb_aff;
3164 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3166 if (h0->current_slice != 0) {
3167 if (last_pic_structure != h->picture_structure ||
3168 last_pic_droppable != h->droppable) {
3169 av_log(h->avctx, AV_LOG_ERROR,
3170 "Changing field mode (%d -> %d) between slices is not allowed\n",
3171 last_pic_structure, h->picture_structure);
3172 h->picture_structure = last_pic_structure;
3173 h->droppable = last_pic_droppable;
3174 return AVERROR_INVALIDDATA;
3175 } else if (!h0->cur_pic_ptr) {
3176 av_log(h->avctx, AV_LOG_ERROR,
3177 "unset cur_pic_ptr on %d. slice\n",
3178 h0->current_slice + 1);
3179 return AVERROR_INVALIDDATA;
3182 /* Shorten frame num gaps so we don't have to allocate reference
3183 * frames just to throw them away */
3184 if (h->frame_num != h->prev_frame_num) {
3185 int unwrap_prev_frame_num = h->prev_frame_num;
3186 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3188 if (unwrap_prev_frame_num > h->frame_num)
3189 unwrap_prev_frame_num -= max_frame_num;
3191 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3192 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3193 if (unwrap_prev_frame_num < 0)
3194 unwrap_prev_frame_num += max_frame_num;
3196 h->prev_frame_num = unwrap_prev_frame_num;
3200 /* See if we have a decoded first field looking for a pair...
3201 * Here, we're using that to see if we should mark previously
3202 * decode frames as "finished".
3203 * We have to do that before the "dummy" in-between frame allocation,
3204 * since that can modify s->current_picture_ptr. */
3205 if (h0->first_field) {
3206 assert(h0->cur_pic_ptr);
3207 assert(h0->cur_pic_ptr->f.data[0]);
3208 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3210 /* Mark old field/frame as completed */
3211 if (!last_pic_droppable && h0->cur_pic_ptr->owner2 == h0) {
3212 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3213 last_pic_structure == PICT_BOTTOM_FIELD);
3216 /* figure out if we have a complementary field pair */
3217 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3218 /* Previous field is unmatched. Don't display it, but let it
3219 * remain for reference if marked as such. */
3220 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3221 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3222 last_pic_structure == PICT_TOP_FIELD);
3225 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3226 /* This and previous field were reference, but had
3227 * different frame_nums. Consider this field first in
3228 * pair. Throw away previous field except for reference
3230 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3231 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3232 last_pic_structure == PICT_TOP_FIELD);
3235 /* Second field in complementary pair */
3236 if (!((last_pic_structure == PICT_TOP_FIELD &&
3237 h->picture_structure == PICT_BOTTOM_FIELD) ||
3238 (last_pic_structure == PICT_BOTTOM_FIELD &&
3239 h->picture_structure == PICT_TOP_FIELD))) {
3240 av_log(h->avctx, AV_LOG_ERROR,
3241 "Invalid field mode combination %d/%d\n",
3242 last_pic_structure, h->picture_structure);
3243 h->picture_structure = last_pic_structure;
3244 h->droppable = last_pic_droppable;
3245 return AVERROR_INVALIDDATA;
3246 } else if (last_pic_droppable != h->droppable) {
3247 av_log(h->avctx, AV_LOG_ERROR,
3248 "Cannot combine reference and non-reference fields in the same frame\n");
3249 av_log_ask_for_sample(h->avctx, NULL);
3250 h->picture_structure = last_pic_structure;
3251 h->droppable = last_pic_droppable;
3252 return AVERROR_PATCHWELCOME;
3255 /* Take ownership of this buffer. Note that if another thread owned
3256 * the first field of this buffer, we're not operating on that pointer,
3257 * so the original thread is still responsible for reporting progress
3258 * on that first field (or if that was us, we just did that above).
3259 * By taking ownership, we assign responsibility to ourselves to
3260 * report progress on the second field. */
3261 h0->cur_pic_ptr->owner2 = h0;
3266 while (h->frame_num != h->prev_frame_num &&
3267 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3268 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3269 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3270 h->frame_num, h->prev_frame_num);
3271 if (ff_h264_frame_start(h) < 0)
3273 h->prev_frame_num++;
3274 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3275 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3276 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 0);
3277 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 1);
3278 if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
3279 h->avctx->err_recognition & AV_EF_EXPLODE)
3281 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3282 (h->avctx->err_recognition & AV_EF_EXPLODE))
3283 return AVERROR_INVALIDDATA;
3284 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3285 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3286 * about there being no actual duplicates.
3287 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3288 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3290 if (h->short_ref_count) {
3292 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3293 (const uint8_t **)prev->f.data, prev->f.linesize,
3294 h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
3295 h->short_ref[0]->poc = prev->poc + 2;
3297 h->short_ref[0]->frame_num = h->prev_frame_num;
3301 /* See if we have a decoded first field looking for a pair...
3302 * We're using that to see whether to continue decoding in that
3303 * frame, or to allocate a new one. */
3304 if (h0->first_field) {
3305 assert(h0->cur_pic_ptr);
3306 assert(h0->cur_pic_ptr->f.data[0]);
3307 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3309 /* figure out if we have a complementary field pair */
3310 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3311 /* Previous field is unmatched. Don't display it, but let it
3312 * remain for reference if marked as such. */
3313 h0->cur_pic_ptr = NULL;
3314 h0->first_field = FIELD_PICTURE;
3316 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3317 /* This and the previous field had different frame_nums.
3318 * Consider this field first in pair. Throw away previous
3319 * one except for reference purposes. */
3320 h0->first_field = 1;
3321 h0->cur_pic_ptr = NULL;
3323 /* Second field in complementary pair */
3324 h0->first_field = 0;
3328 /* Frame or first field in a potentially complementary pair */
3329 h0->first_field = FIELD_PICTURE;
3332 if (!FIELD_PICTURE || h0->first_field) {
3333 if (ff_h264_frame_start(h) < 0) {
3334 h0->first_field = 0;
3338 release_unused_pictures(h, 0);
3341 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3344 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3346 assert(h->mb_num == h->mb_width * h->mb_height);
3347 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= h->mb_num ||
3348 first_mb_in_slice >= h->mb_num) {
3349 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3352 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3353 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE;
3354 if (h->picture_structure == PICT_BOTTOM_FIELD)
3355 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3356 assert(h->mb_y < h->mb_height);
3358 if (h->picture_structure == PICT_FRAME) {
3359 h->curr_pic_num = h->frame_num;
3360 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3362 h->curr_pic_num = 2 * h->frame_num + 1;
3363 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3366 if (h->nal_unit_type == NAL_IDR_SLICE)
3367 get_ue_golomb(&h->gb); /* idr_pic_id */
3369 if (h->sps.poc_type == 0) {
3370 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3372 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3373 h->delta_poc_bottom = get_se_golomb(&h->gb);
3376 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3377 h->delta_poc[0] = get_se_golomb(&h->gb);
3379 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3380 h->delta_poc[1] = get_se_golomb(&h->gb);
3385 if (h->pps.redundant_pic_cnt_present)
3386 h->redundant_pic_count = get_ue_golomb(&h->gb);
3388 // set defaults, might be overridden a few lines later
3389 h->ref_count[0] = h->pps.ref_count[0];
3390 h->ref_count[1] = h->pps.ref_count[1];
3392 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3393 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3394 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3395 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3397 if (num_ref_idx_active_override_flag) {
3398 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3399 if (h->ref_count[0] < 1)