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 h264_hwaccel_pixfmt_list_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 const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
82 #if CONFIG_H264_DXVA2_HWACCEL
85 #if CONFIG_H264_VAAPI_HWACCEL
88 #if CONFIG_H264_VDA_HWACCEL
91 #if CONFIG_H264_VDPAU_HWACCEL
98 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
100 int mb_x, int mb_y, int mb_intra, int mb_skipped)
102 H264Context *h = opaque;
106 h->mb_xy = mb_x + mb_y * h->mb_stride;
107 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
109 /* FIXME: It is possible albeit uncommon that slice references
110 * differ between slices. We take the easy approach and ignore
111 * it for now. If this turns out to have any relevance in
112 * practice then correct remapping should be added. */
113 if (ref >= h->ref_count[0])
115 fill_rectangle(&h->cur_pic.f.ref_index[0][4 * h->mb_xy],
117 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
118 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
119 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
120 assert(!FRAME_MBAFF);
121 ff_h264_hl_decode_mb(h);
124 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
126 ff_draw_horiz_band(h->avctx, NULL, &h->cur_pic,
127 h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL,
128 y, height, h->picture_structure, h->first_field, 0,
129 h->low_delay, h->mb_height * 16, h->mb_width * 16);
132 static void free_frame_buffer(H264Context *h, Picture *pic)
134 ff_thread_release_buffer(h->avctx, &pic->f);
135 av_freep(&pic->f.hwaccel_picture_private);
138 static void free_picture(H264Context *h, Picture *pic)
143 free_frame_buffer(h, pic);
145 av_freep(&pic->qscale_table_base);
146 pic->f.qscale_table = NULL;
147 av_freep(&pic->mb_type_base);
148 pic->f.mb_type = NULL;
149 for (i = 0; i < 2; i++) {
150 av_freep(&pic->motion_val_base[i]);
151 av_freep(&pic->f.ref_index[i]);
152 pic->f.motion_val[i] = NULL;
156 static void release_unused_pictures(H264Context *h, int remove_current)
160 /* release non reference frames */
161 for (i = 0; i < h->picture_count; i++) {
162 if (h->DPB[i].f.data[0] && !h->DPB[i].f.reference &&
163 (!h->DPB[i].owner2 || h->DPB[i].owner2 == h) &&
164 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
165 free_frame_buffer(h, &h->DPB[i]);
170 static int alloc_scratch_buffers(H264Context *h, int linesize)
172 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
174 if (h->bipred_scratchpad)
177 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
178 // edge emu needs blocksize + filter length - 1
179 // (= 21x21 for h264)
180 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
181 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
183 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
184 av_freep(&h->bipred_scratchpad);
185 av_freep(&h->edge_emu_buffer);
186 av_freep(&h->me.scratchpad);
187 return AVERROR(ENOMEM);
190 h->me.temp = h->me.scratchpad;
195 static int alloc_picture(H264Context *h, Picture *pic)
197 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
198 const int mb_array_size = h->mb_stride * h->mb_height;
199 const int b4_stride = h->mb_width * 4 + 1;
200 const int b4_array_size = b4_stride * h->mb_height * 4;
203 av_assert0(!pic->f.data[0]);
205 if (h->avctx->hwaccel) {
206 const AVHWAccel *hwaccel = h->avctx->hwaccel;
207 av_assert0(!pic->f.hwaccel_picture_private);
208 if (hwaccel->priv_data_size) {
209 pic->f.hwaccel_picture_private = av_mallocz(hwaccel->priv_data_size);
210 if (!pic->f.hwaccel_picture_private)
211 return AVERROR(ENOMEM);
214 ret = ff_thread_get_buffer(h->avctx, &pic->f);
218 h->linesize = pic->f.linesize[0];
219 h->uvlinesize = pic->f.linesize[1];
221 if (pic->f.qscale_table == NULL) {
222 FF_ALLOCZ_OR_GOTO(h->avctx, pic->qscale_table_base,
223 (big_mb_num + h->mb_stride) * sizeof(uint8_t),
225 FF_ALLOCZ_OR_GOTO(h->avctx, pic->mb_type_base,
226 (big_mb_num + h->mb_stride) * sizeof(uint32_t),
228 pic->f.mb_type = pic->mb_type_base + 2 * h->mb_stride + 1;
229 pic->f.qscale_table = pic->qscale_table_base + 2 * h->mb_stride + 1;
231 for (i = 0; i < 2; i++) {
232 FF_ALLOCZ_OR_GOTO(h->avctx, pic->motion_val_base[i],
233 2 * (b4_array_size + 4) * sizeof(int16_t),
235 pic->f.motion_val[i] = pic->motion_val_base[i] + 4;
236 FF_ALLOCZ_OR_GOTO(h->avctx, pic->f.ref_index[i],
237 4 * mb_array_size * sizeof(uint8_t), fail)
239 pic->f.motion_subsample_log2 = 2;
241 pic->f.qstride = h->mb_stride;
248 free_frame_buffer(h, pic);
249 return (ret < 0) ? ret : AVERROR(ENOMEM);
252 static inline int pic_is_unused(H264Context *h, Picture *pic)
254 if (pic->f.data[0] == NULL)
256 if (pic->needs_realloc && !(pic->f.reference & DELAYED_PIC_REF))
257 if (!pic->owner2 || pic->owner2 == h)
262 static int find_unused_picture(H264Context *h)
266 for (i = h->picture_range_start; i < h->picture_range_end; i++) {
267 if (pic_is_unused(h, &h->DPB[i]))
270 if (i == h->picture_range_end)
271 return AVERROR_INVALIDDATA;
273 if (h->DPB[i].needs_realloc) {
274 h->DPB[i].needs_realloc = 0;
275 free_picture(h, &h->DPB[i]);
276 avcodec_get_frame_defaults(&h->DPB[i].f);
283 * Check if the top & left blocks are available if needed and
284 * change the dc mode so it only uses the available blocks.
286 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
288 static const int8_t top[12] = {
289 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
291 static const int8_t left[12] = {
292 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
296 if (!(h->top_samples_available & 0x8000)) {
297 for (i = 0; i < 4; i++) {
298 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
300 av_log(h->avctx, AV_LOG_ERROR,
301 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
302 status, h->mb_x, h->mb_y);
305 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
310 if ((h->left_samples_available & 0x8888) != 0x8888) {
311 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
312 for (i = 0; i < 4; i++)
313 if (!(h->left_samples_available & mask[i])) {
314 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
316 av_log(h->avctx, AV_LOG_ERROR,
317 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
318 status, h->mb_x, h->mb_y);
321 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
327 } // FIXME cleanup like ff_h264_check_intra_pred_mode
330 * Check if the top & left blocks are available if needed and
331 * change the dc mode so it only uses the available blocks.
333 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
335 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
336 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
339 av_log(h->avctx, AV_LOG_ERROR,
340 "out of range intra chroma pred mode at %d %d\n",
345 if (!(h->top_samples_available & 0x8000)) {
348 av_log(h->avctx, AV_LOG_ERROR,
349 "top block unavailable for requested intra mode at %d %d\n",
355 if ((h->left_samples_available & 0x8080) != 0x8080) {
357 if (is_chroma && (h->left_samples_available & 0x8080)) {
358 // mad cow disease mode, aka MBAFF + constrained_intra_pred
359 mode = ALZHEIMER_DC_L0T_PRED8x8 +
360 (!(h->left_samples_available & 0x8000)) +
361 2 * (mode == DC_128_PRED8x8);
364 av_log(h->avctx, AV_LOG_ERROR,
365 "left block unavailable for requested intra mode at %d %d\n",
374 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
375 int *dst_length, int *consumed, int length)
381 // src[0]&0x80; // forbidden bit
382 h->nal_ref_idc = src[0] >> 5;
383 h->nal_unit_type = src[0] & 0x1F;
388 #define STARTCODE_TEST \
389 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
390 if (src[i + 2] != 3) { \
391 /* startcode, so we must be past the end */ \
396 #if HAVE_FAST_UNALIGNED
397 #define FIND_FIRST_ZERO \
398 if (i > 0 && !src[i]) \
403 for (i = 0; i + 1 < length; i += 9) {
404 if (!((~AV_RN64A(src + i) &
405 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
406 0x8000800080008080ULL))
413 for (i = 0; i + 1 < length; i += 5) {
414 if (!((~AV_RN32A(src + i) &
415 (AV_RN32A(src + i) - 0x01000101U)) &
424 for (i = 0; i + 1 < length; i += 2) {
427 if (i > 0 && src[i - 1] == 0)
433 if (i >= length - 1) { // no escaped 0
434 *dst_length = length;
435 *consumed = length + 1; // +1 for the header
439 // use second escape buffer for inter data
440 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
441 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
442 length + FF_INPUT_BUFFER_PADDING_SIZE);
443 dst = h->rbsp_buffer[bufidx];
450 while (si + 2 < length) {
451 // remove escapes (very rare 1:2^22)
452 if (src[si + 2] > 3) {
453 dst[di++] = src[si++];
454 dst[di++] = src[si++];
455 } else if (src[si] == 0 && src[si + 1] == 0) {
456 if (src[si + 2] == 3) { // escape
461 } else // next start code
465 dst[di++] = src[si++];
468 dst[di++] = src[si++];
471 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
474 *consumed = si + 1; // +1 for the header
475 /* FIXME store exact number of bits in the getbitcontext
476 * (it is needed for decoding) */
481 * Identify the exact end of the bitstream
482 * @return the length of the trailing, or 0 if damaged
484 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
489 tprintf(h->avctx, "rbsp trailing %X\n", v);
491 for (r = 1; r < 9; r++) {
499 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
500 int height, int y_offset, int list)
502 int raw_my = h->mv_cache[list][scan8[n]][1];
503 int filter_height_up = (raw_my & 3) ? 2 : 0;
504 int filter_height_down = (raw_my & 3) ? 3 : 0;
505 int full_my = (raw_my >> 2) + y_offset;
506 int top = full_my - filter_height_up;
507 int bottom = full_my + filter_height_down + height;
509 return FFMAX(abs(top), bottom);
512 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
513 int height, int y_offset, int list0,
514 int list1, int *nrefs)
518 y_offset += 16 * (h->mb_y >> MB_FIELD);
521 int ref_n = h->ref_cache[0][scan8[n]];
522 Picture *ref = &h->ref_list[0][ref_n];
524 // Error resilience puts the current picture in the ref list.
525 // Don't try to wait on these as it will cause a deadlock.
526 // Fields can wait on each other, though.
527 if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
528 (ref->f.reference & 3) != h->picture_structure) {
529 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
530 if (refs[0][ref_n] < 0)
532 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
537 int ref_n = h->ref_cache[1][scan8[n]];
538 Picture *ref = &h->ref_list[1][ref_n];
540 if (ref->f.thread_opaque != h->cur_pic.f.thread_opaque ||
541 (ref->f.reference & 3) != h->picture_structure) {
542 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
543 if (refs[1][ref_n] < 0)
545 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
551 * Wait until all reference frames are available for MC operations.
553 * @param h the H264 context
555 static void await_references(H264Context *h)
557 const int mb_xy = h->mb_xy;
558 const int mb_type = h->cur_pic.f.mb_type[mb_xy];
560 int nrefs[2] = { 0 };
563 memset(refs, -1, sizeof(refs));
565 if (IS_16X16(mb_type)) {
566 get_lowest_part_y(h, refs, 0, 16, 0,
567 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
568 } else if (IS_16X8(mb_type)) {
569 get_lowest_part_y(h, refs, 0, 8, 0,
570 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
571 get_lowest_part_y(h, refs, 8, 8, 8,
572 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
573 } else if (IS_8X16(mb_type)) {
574 get_lowest_part_y(h, refs, 0, 16, 0,
575 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
576 get_lowest_part_y(h, refs, 4, 16, 0,
577 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
581 assert(IS_8X8(mb_type));
583 for (i = 0; i < 4; i++) {
584 const int sub_mb_type = h->sub_mb_type[i];
586 int y_offset = (i & 2) << 2;
588 if (IS_SUB_8X8(sub_mb_type)) {
589 get_lowest_part_y(h, refs, n, 8, y_offset,
590 IS_DIR(sub_mb_type, 0, 0),
591 IS_DIR(sub_mb_type, 0, 1),
593 } else if (IS_SUB_8X4(sub_mb_type)) {
594 get_lowest_part_y(h, refs, n, 4, y_offset,
595 IS_DIR(sub_mb_type, 0, 0),
596 IS_DIR(sub_mb_type, 0, 1),
598 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
599 IS_DIR(sub_mb_type, 0, 0),
600 IS_DIR(sub_mb_type, 0, 1),
602 } else if (IS_SUB_4X8(sub_mb_type)) {
603 get_lowest_part_y(h, refs, n, 8, y_offset,
604 IS_DIR(sub_mb_type, 0, 0),
605 IS_DIR(sub_mb_type, 0, 1),
607 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
608 IS_DIR(sub_mb_type, 0, 0),
609 IS_DIR(sub_mb_type, 0, 1),
613 assert(IS_SUB_4X4(sub_mb_type));
614 for (j = 0; j < 4; j++) {
615 int sub_y_offset = y_offset + 2 * (j & 2);
616 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
617 IS_DIR(sub_mb_type, 0, 0),
618 IS_DIR(sub_mb_type, 0, 1),
625 for (list = h->list_count - 1; list >= 0; list--)
626 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
627 int row = refs[list][ref];
629 Picture *ref_pic = &h->ref_list[list][ref];
630 int ref_field = ref_pic->f.reference - 1;
631 int ref_field_picture = ref_pic->field_picture;
632 int pic_height = 16 * h->mb_height >> ref_field_picture;
637 if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
638 ff_thread_await_progress(&ref_pic->f,
639 FFMIN((row >> 1) - !(row & 1),
642 ff_thread_await_progress(&ref_pic->f,
643 FFMIN((row >> 1), pic_height - 1),
645 } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
646 ff_thread_await_progress(&ref_pic->f,
647 FFMIN(row * 2 + ref_field,
650 } else if (FIELD_PICTURE) {
651 ff_thread_await_progress(&ref_pic->f,
652 FFMIN(row, pic_height - 1),
655 ff_thread_await_progress(&ref_pic->f,
656 FFMIN(row, pic_height - 1),
663 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
664 int n, int square, int height,
666 uint8_t *dest_y, uint8_t *dest_cb,
668 int src_x_offset, int src_y_offset,
669 qpel_mc_func *qpix_op,
670 h264_chroma_mc_func chroma_op,
671 int pixel_shift, int chroma_idc)
673 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
674 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
675 const int luma_xy = (mx & 3) + ((my & 3) << 2);
676 int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
677 uint8_t *src_y = pic->f.data[0] + offset;
678 uint8_t *src_cb, *src_cr;
680 int extra_height = 0;
682 const int full_mx = mx >> 2;
683 const int full_my = my >> 2;
684 const int pic_width = 16 * h->mb_width;
685 const int pic_height = 16 * h->mb_height >> MB_FIELD;
693 if (full_mx < 0 - extra_width ||
694 full_my < 0 - extra_height ||
695 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
696 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
697 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
698 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
700 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
701 full_my - 2, pic_width, pic_height);
702 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
706 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
708 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
710 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
713 if (chroma_idc == 3 /* yuv444 */) {
714 src_cb = pic->f.data[1] + offset;
716 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
717 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
719 16 + 5, 16 + 5 /*FIXME*/,
720 full_mx - 2, full_my - 2,
721 pic_width, pic_height);
722 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
724 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
726 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
728 src_cr = pic->f.data[2] + offset;
730 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
731 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
733 16 + 5, 16 + 5 /*FIXME*/,
734 full_mx - 2, full_my - 2,
735 pic_width, pic_height);
736 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
738 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
740 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
744 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
745 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
746 // chroma offset when predicting from a field of opposite parity
747 my += 2 * ((h->mb_y & 1) - (pic->f.reference - 1));
748 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
751 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
752 (my >> ysh) * h->mb_uvlinesize;
753 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
754 (my >> ysh) * h->mb_uvlinesize;
757 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
758 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
759 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
760 src_cb = h->edge_emu_buffer;
762 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
763 height >> (chroma_idc == 1 /* yuv420 */),
764 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
767 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
768 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
769 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
770 src_cr = h->edge_emu_buffer;
772 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
773 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
776 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
777 int height, int delta,
778 uint8_t *dest_y, uint8_t *dest_cb,
780 int x_offset, int y_offset,
781 qpel_mc_func *qpix_put,
782 h264_chroma_mc_func chroma_put,
783 qpel_mc_func *qpix_avg,
784 h264_chroma_mc_func chroma_avg,
785 int list0, int list1,
786 int pixel_shift, int chroma_idc)
788 qpel_mc_func *qpix_op = qpix_put;
789 h264_chroma_mc_func chroma_op = chroma_put;
791 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
792 if (chroma_idc == 3 /* yuv444 */) {
793 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
794 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
795 } else if (chroma_idc == 2 /* yuv422 */) {
796 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
797 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
798 } else { /* yuv420 */
799 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
800 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
802 x_offset += 8 * h->mb_x;
803 y_offset += 8 * (h->mb_y >> MB_FIELD);
806 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
807 mc_dir_part(h, ref, n, square, height, delta, 0,
808 dest_y, dest_cb, dest_cr, x_offset, y_offset,
809 qpix_op, chroma_op, pixel_shift, chroma_idc);
812 chroma_op = chroma_avg;
816 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
817 mc_dir_part(h, ref, n, square, height, delta, 1,
818 dest_y, dest_cb, dest_cr, x_offset, y_offset,
819 qpix_op, chroma_op, pixel_shift, chroma_idc);
823 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
824 int height, int delta,
825 uint8_t *dest_y, uint8_t *dest_cb,
827 int x_offset, int y_offset,
828 qpel_mc_func *qpix_put,
829 h264_chroma_mc_func chroma_put,
830 h264_weight_func luma_weight_op,
831 h264_weight_func chroma_weight_op,
832 h264_biweight_func luma_weight_avg,
833 h264_biweight_func chroma_weight_avg,
834 int list0, int list1,
835 int pixel_shift, int chroma_idc)
839 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
840 if (chroma_idc == 3 /* yuv444 */) {
841 chroma_height = height;
842 chroma_weight_avg = luma_weight_avg;
843 chroma_weight_op = luma_weight_op;
844 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
845 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
846 } else if (chroma_idc == 2 /* yuv422 */) {
847 chroma_height = height;
848 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
849 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
850 } else { /* yuv420 */
851 chroma_height = height >> 1;
852 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
853 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
855 x_offset += 8 * h->mb_x;
856 y_offset += 8 * (h->mb_y >> MB_FIELD);
858 if (list0 && list1) {
859 /* don't optimize for luma-only case, since B-frames usually
860 * use implicit weights => chroma too. */
861 uint8_t *tmp_cb = h->bipred_scratchpad;
862 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
863 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
864 int refn0 = h->ref_cache[0][scan8[n]];
865 int refn1 = h->ref_cache[1][scan8[n]];
867 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
868 dest_y, dest_cb, dest_cr,
869 x_offset, y_offset, qpix_put, chroma_put,
870 pixel_shift, chroma_idc);
871 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
872 tmp_y, tmp_cb, tmp_cr,
873 x_offset, y_offset, qpix_put, chroma_put,
874 pixel_shift, chroma_idc);
876 if (h->use_weight == 2) {
877 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
878 int weight1 = 64 - weight0;
879 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
880 height, 5, weight0, weight1, 0);
881 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
882 chroma_height, 5, weight0, weight1, 0);
883 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
884 chroma_height, 5, weight0, weight1, 0);
886 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
887 h->luma_log2_weight_denom,
888 h->luma_weight[refn0][0][0],
889 h->luma_weight[refn1][1][0],
890 h->luma_weight[refn0][0][1] +
891 h->luma_weight[refn1][1][1]);
892 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
893 h->chroma_log2_weight_denom,
894 h->chroma_weight[refn0][0][0][0],
895 h->chroma_weight[refn1][1][0][0],
896 h->chroma_weight[refn0][0][0][1] +
897 h->chroma_weight[refn1][1][0][1]);
898 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
899 h->chroma_log2_weight_denom,
900 h->chroma_weight[refn0][0][1][0],
901 h->chroma_weight[refn1][1][1][0],
902 h->chroma_weight[refn0][0][1][1] +
903 h->chroma_weight[refn1][1][1][1]);
906 int list = list1 ? 1 : 0;
907 int refn = h->ref_cache[list][scan8[n]];
908 Picture *ref = &h->ref_list[list][refn];
909 mc_dir_part(h, ref, n, square, height, delta, list,
910 dest_y, dest_cb, dest_cr, x_offset, y_offset,
911 qpix_put, chroma_put, pixel_shift, chroma_idc);
913 luma_weight_op(dest_y, h->mb_linesize, height,
914 h->luma_log2_weight_denom,
915 h->luma_weight[refn][list][0],
916 h->luma_weight[refn][list][1]);
917 if (h->use_weight_chroma) {
918 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
919 h->chroma_log2_weight_denom,
920 h->chroma_weight[refn][list][0][0],
921 h->chroma_weight[refn][list][0][1]);
922 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
923 h->chroma_log2_weight_denom,
924 h->chroma_weight[refn][list][1][0],
925 h->chroma_weight[refn][list][1][1]);
930 static av_always_inline void prefetch_motion(H264Context *h, int list,
931 int pixel_shift, int chroma_idc)
933 /* fetch pixels for estimated mv 4 macroblocks ahead
934 * optimized for 64byte cache lines */
935 const int refn = h->ref_cache[list][scan8[0]];
937 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
938 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
939 uint8_t **src = h->ref_list[list][refn].f.data;
940 int off = (mx << pixel_shift) +
941 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
943 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
944 if (chroma_idc == 3 /* yuv444 */) {
945 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
946 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
948 off = ((mx >> 1) << pixel_shift) +
949 ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
951 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
956 static void free_tables(H264Context *h, int free_rbsp)
961 av_freep(&h->intra4x4_pred_mode);
962 av_freep(&h->chroma_pred_mode_table);
963 av_freep(&h->cbp_table);
964 av_freep(&h->mvd_table[0]);
965 av_freep(&h->mvd_table[1]);
966 av_freep(&h->direct_table);
967 av_freep(&h->non_zero_count);
968 av_freep(&h->slice_table_base);
969 h->slice_table = NULL;
970 av_freep(&h->list_counts);
972 av_freep(&h->mb2b_xy);
973 av_freep(&h->mb2br_xy);
976 for (i = 0; i < h->picture_count && !h->avctx->internal->is_copy; i++)
977 free_picture(h, &h->DPB[i]);
979 h->picture_count = 0;
981 for (i = 0; i < h->picture_count; i++)
982 h->DPB[i].needs_realloc = 1;
985 h->cur_pic_ptr = NULL;
987 for (i = 0; i < MAX_THREADS; i++) {
988 hx = h->thread_context[i];
991 av_freep(&hx->top_borders[1]);
992 av_freep(&hx->top_borders[0]);
993 av_freep(&hx->bipred_scratchpad);
994 av_freep(&hx->edge_emu_buffer);
995 av_freep(&hx->dc_val_base);
996 av_freep(&hx->me.scratchpad);
997 av_freep(&hx->er.mb_index2xy);
998 av_freep(&hx->er.error_status_table);
999 av_freep(&hx->er.er_temp_buffer);
1000 av_freep(&hx->er.mbintra_table);
1001 av_freep(&hx->er.mbskip_table);
1004 av_freep(&hx->rbsp_buffer[1]);
1005 av_freep(&hx->rbsp_buffer[0]);
1006 hx->rbsp_buffer_size[0] = 0;
1007 hx->rbsp_buffer_size[1] = 0;
1010 av_freep(&h->thread_context[i]);
1014 static void init_dequant8_coeff_table(H264Context *h)
1017 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1019 for (i = 0; i < 6; i++) {
1020 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1021 for (j = 0; j < i; j++)
1022 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1023 64 * sizeof(uint8_t))) {
1024 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1030 for (q = 0; q < max_qp + 1; q++) {
1031 int shift = div6[q];
1033 for (x = 0; x < 64; x++)
1034 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1035 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1036 h->pps.scaling_matrix8[i][x]) << shift;
1041 static void init_dequant4_coeff_table(H264Context *h)
1044 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1045 for (i = 0; i < 6; i++) {
1046 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1047 for (j = 0; j < i; j++)
1048 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1049 16 * sizeof(uint8_t))) {
1050 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1056 for (q = 0; q < max_qp + 1; q++) {
1057 int shift = div6[q] + 2;
1059 for (x = 0; x < 16; x++)
1060 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1061 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1062 h->pps.scaling_matrix4[i][x]) << shift;
1067 static void init_dequant_tables(H264Context *h)
1070 init_dequant4_coeff_table(h);
1071 if (h->pps.transform_8x8_mode)
1072 init_dequant8_coeff_table(h);
1073 if (h->sps.transform_bypass) {
1074 for (i = 0; i < 6; i++)
1075 for (x = 0; x < 16; x++)
1076 h->dequant4_coeff[i][0][x] = 1 << 6;
1077 if (h->pps.transform_8x8_mode)
1078 for (i = 0; i < 6; i++)
1079 for (x = 0; x < 64; x++)
1080 h->dequant8_coeff[i][0][x] = 1 << 6;
1084 int ff_h264_alloc_tables(H264Context *h)
1086 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1087 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
1090 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1091 row_mb_num * 8 * sizeof(uint8_t), fail)
1092 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1093 big_mb_num * 48 * sizeof(uint8_t), fail)
1094 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1095 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1096 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1097 big_mb_num * sizeof(uint16_t), fail)
1098 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1099 big_mb_num * sizeof(uint8_t), fail)
1100 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1101 16 * row_mb_num * sizeof(uint8_t), fail);
1102 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1103 16 * row_mb_num * sizeof(uint8_t), fail);
1104 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1105 4 * big_mb_num * sizeof(uint8_t), fail);
1106 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1107 big_mb_num * sizeof(uint8_t), fail)
1109 memset(h->slice_table_base, -1,
1110 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1111 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1113 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1114 big_mb_num * sizeof(uint32_t), fail);
1115 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1116 big_mb_num * sizeof(uint32_t), fail);
1117 for (y = 0; y < h->mb_height; y++)
1118 for (x = 0; x < h->mb_width; x++) {
1119 const int mb_xy = x + y * h->mb_stride;
1120 const int b_xy = 4 * x + 4 * y * h->b_stride;
1122 h->mb2b_xy[mb_xy] = b_xy;
1123 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1126 if (!h->dequant4_coeff[0])
1127 init_dequant_tables(h);
1130 h->picture_count = MAX_PICTURE_COUNT * FFMAX(1, h->avctx->thread_count);
1131 h->DPB = av_mallocz_array(h->picture_count, sizeof(*h->DPB));
1133 return AVERROR(ENOMEM);
1134 for (i = 0; i < h->picture_count; i++)
1135 avcodec_get_frame_defaults(&h->DPB[i].f);
1136 avcodec_get_frame_defaults(&h->cur_pic.f);
1147 * Mimic alloc_tables(), but for every context thread.
1149 static void clone_tables(H264Context *dst, H264Context *src, int i)
1151 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1152 dst->non_zero_count = src->non_zero_count;
1153 dst->slice_table = src->slice_table;
1154 dst->cbp_table = src->cbp_table;
1155 dst->mb2b_xy = src->mb2b_xy;
1156 dst->mb2br_xy = src->mb2br_xy;
1157 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1158 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1159 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1160 dst->direct_table = src->direct_table;
1161 dst->list_counts = src->list_counts;
1162 dst->DPB = src->DPB;
1163 dst->cur_pic_ptr = src->cur_pic_ptr;
1164 dst->cur_pic = src->cur_pic;
1165 dst->bipred_scratchpad = NULL;
1166 dst->edge_emu_buffer = NULL;
1167 dst->me.scratchpad = NULL;
1168 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1169 src->sps.chroma_format_idc);
1174 * Allocate buffers which are not shared amongst multiple threads.
1176 static int context_init(H264Context *h)
1178 ERContext *er = &h->er;
1179 int mb_array_size = h->mb_height * h->mb_stride;
1180 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1181 int c_size = h->mb_stride * (h->mb_height + 1);
1182 int yc_size = y_size + 2 * c_size;
1185 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1186 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1187 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1188 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1190 h->ref_cache[0][scan8[5] + 1] =
1191 h->ref_cache[0][scan8[7] + 1] =
1192 h->ref_cache[0][scan8[13] + 1] =
1193 h->ref_cache[1][scan8[5] + 1] =
1194 h->ref_cache[1][scan8[7] + 1] =
1195 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1198 er->avctx = h->avctx;
1200 er->decode_mb = h264_er_decode_mb;
1202 er->quarter_sample = 1;
1204 er->mb_num = h->mb_num;
1205 er->mb_width = h->mb_width;
1206 er->mb_height = h->mb_height;
1207 er->mb_stride = h->mb_stride;
1208 er->b8_stride = h->mb_width * 2 + 1;
1210 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1211 fail); // error ressilience code looks cleaner with this
1212 for (y = 0; y < h->mb_height; y++)
1213 for (x = 0; x < h->mb_width; x++)
1214 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1216 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1217 h->mb_stride + h->mb_width;
1219 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1220 mb_array_size * sizeof(uint8_t), fail);
1222 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1223 memset(er->mbintra_table, 1, mb_array_size);
1225 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1227 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1230 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1231 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1232 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1233 er->dc_val[2] = er->dc_val[1] + c_size;
1234 for (i = 0; i < yc_size; i++)
1235 h->dc_val_base[i] = 1024;
1240 return -1; // free_tables will clean up for us
1243 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1244 int parse_extradata);
1246 static av_cold void common_init(H264Context *h)
1249 h->width = h->avctx->width;
1250 h->height = h->avctx->height;
1252 h->bit_depth_luma = 8;
1253 h->chroma_format_idc = 1;
1255 ff_h264dsp_init(&h->h264dsp, 8, 1);
1256 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1257 ff_h264qpel_init(&h->h264qpel, 8);
1258 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1260 h->dequant_coeff_pps = -1;
1262 /* needed so that IDCT permutation is known early */
1263 ff_dsputil_init(&h->dsp, h->avctx);
1264 ff_videodsp_init(&h->vdsp, 8);
1266 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1267 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1270 int ff_h264_decode_extradata(H264Context *h)
1272 AVCodecContext *avctx = h->avctx;
1274 if (avctx->extradata[0] == 1) {
1275 int i, cnt, nalsize;
1276 unsigned char *p = avctx->extradata;
1280 if (avctx->extradata_size < 7) {
1281 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1284 /* sps and pps in the avcC always have length coded with 2 bytes,
1285 * so put a fake nal_length_size = 2 while parsing them */
1286 h->nal_length_size = 2;
1287 // Decode sps from avcC
1288 cnt = *(p + 5) & 0x1f; // Number of sps
1290 for (i = 0; i < cnt; i++) {
1291 nalsize = AV_RB16(p) + 2;
1292 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1294 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1295 av_log(avctx, AV_LOG_ERROR,
1296 "Decoding sps %d from avcC failed\n", i);
1301 // Decode pps from avcC
1302 cnt = *(p++); // Number of pps
1303 for (i = 0; i < cnt; i++) {
1304 nalsize = AV_RB16(p) + 2;
1305 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1307 if (decode_nal_units(h, p, nalsize, 1) < 0) {
1308 av_log(avctx, AV_LOG_ERROR,
1309 "Decoding pps %d from avcC failed\n", i);
1314 // Now store right nal length size, that will be used to parse all other nals
1315 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1318 if (decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1) < 0)
1324 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1326 H264Context *h = avctx->priv_data;
1332 h->picture_structure = PICT_FRAME;
1333 h->picture_range_start = 0;
1334 h->picture_range_end = MAX_PICTURE_COUNT;
1335 h->slice_context_count = 1;
1336 h->workaround_bugs = avctx->workaround_bugs;
1337 h->flags = avctx->flags;
1340 // s->decode_mb = ff_h263_decode_mb;
1341 if (!avctx->has_b_frames)
1344 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1346 ff_h264_decode_init_vlc();
1349 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1351 h->thread_context[0] = h;
1352 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1353 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1354 h->last_pocs[i] = INT_MIN;
1355 h->prev_poc_msb = 1 << 16;
1357 ff_h264_reset_sei(h);
1358 if (avctx->codec_id == AV_CODEC_ID_H264) {
1359 if (avctx->ticks_per_frame == 1)
1360 h->avctx->time_base.den *= 2;
1361 avctx->ticks_per_frame = 2;
1364 if (avctx->extradata_size > 0 && avctx->extradata &&
1365 ff_h264_decode_extradata(h))
1368 if (h->sps.bitstream_restriction_flag &&
1369 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1370 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1377 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1378 #undef REBASE_PICTURE
1379 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1380 ((pic && pic >= old_ctx->DPB && \
1381 pic < old_ctx->DPB + old_ctx->picture_count) ? \
1382 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1384 static void copy_picture_range(Picture **to, Picture **from, int count,
1385 H264Context *new_base,
1386 H264Context *old_base)
1390 for (i = 0; i < count; i++) {
1391 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1392 IN_RANGE(from[i], old_base->DPB,
1393 sizeof(Picture) * old_base->picture_count) ||
1395 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1399 static void copy_parameter_set(void **to, void **from, int count, int size)
1403 for (i = 0; i < count; i++) {
1404 if (to[i] && !from[i])
1406 else if (from[i] && !to[i])
1407 to[i] = av_malloc(size);
1410 memcpy(to[i], from[i], size);
1414 static int decode_init_thread_copy(AVCodecContext *avctx)
1416 H264Context *h = avctx->priv_data;
1418 if (!avctx->internal->is_copy)
1420 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1421 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1423 h->context_initialized = 0;
1428 #define copy_fields(to, from, start_field, end_field) \
1429 memcpy(&to->start_field, &from->start_field, \
1430 (char *)&to->end_field - (char *)&to->start_field)
1432 static int h264_slice_header_init(H264Context *, int);
1434 static int h264_set_parameter_from_sps(H264Context *h);
1436 static int decode_update_thread_context(AVCodecContext *dst,
1437 const AVCodecContext *src)
1439 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1440 int inited = h->context_initialized, err = 0;
1441 int context_reinitialized = 0;
1444 if (dst == src || !h1->context_initialized)
1448 (h->width != h1->width ||
1449 h->height != h1->height ||
1450 h->mb_width != h1->mb_width ||
1451 h->mb_height != h1->mb_height ||
1452 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1453 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1454 h->sps.colorspace != h1->sps.colorspace)) {
1456 av_freep(&h->bipred_scratchpad);
1458 h->width = h1->width;
1459 h->height = h1->height;
1460 h->mb_height = h1->mb_height;
1461 h->mb_width = h1->mb_width;
1462 h->mb_num = h1->mb_num;
1463 h->mb_stride = h1->mb_stride;
1464 h->b_stride = h1->b_stride;
1466 if ((err = h264_slice_header_init(h, 1)) < 0) {
1467 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1470 context_reinitialized = 1;
1472 /* update linesize on resize. The decoder doesn't
1473 * necessarily call ff_h264_frame_start in the new thread */
1474 h->linesize = h1->linesize;
1475 h->uvlinesize = h1->uvlinesize;
1477 /* copy block_offset since frame_start may not be called */
1478 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1482 for (i = 0; i < MAX_SPS_COUNT; i++)
1483 av_freep(h->sps_buffers + i);
1485 for (i = 0; i < MAX_PPS_COUNT; i++)
1486 av_freep(h->pps_buffers + i);
1488 memcpy(h, h1, sizeof(*h1));
1489 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1490 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1491 memset(&h->er, 0, sizeof(h->er));
1492 memset(&h->me, 0, sizeof(h->me));
1493 h->context_initialized = 0;
1495 h->picture_range_start += MAX_PICTURE_COUNT;
1496 h->picture_range_end += MAX_PICTURE_COUNT;
1500 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1502 if (ff_h264_alloc_tables(h) < 0) {
1503 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1504 return AVERROR(ENOMEM);
1508 for (i = 0; i < 2; i++) {
1509 h->rbsp_buffer[i] = NULL;
1510 h->rbsp_buffer_size[i] = 0;
1512 h->bipred_scratchpad = NULL;
1513 h->edge_emu_buffer = NULL;
1515 h->thread_context[0] = h;
1517 h->dsp.clear_blocks(h->mb);
1518 h->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
1519 h->context_initialized = 1;
1522 h->avctx->coded_height = h1->avctx->coded_height;
1523 h->avctx->coded_width = h1->avctx->coded_width;
1524 h->avctx->width = h1->avctx->width;
1525 h->avctx->height = h1->avctx->height;
1526 h->coded_picture_number = h1->coded_picture_number;
1527 h->first_field = h1->first_field;
1528 h->picture_structure = h1->picture_structure;
1529 h->qscale = h1->qscale;
1530 h->droppable = h1->droppable;
1531 h->data_partitioning = h1->data_partitioning;
1532 h->low_delay = h1->low_delay;
1534 memcpy(h->DPB, h1->DPB, h1->picture_count * sizeof(*h1->DPB));
1536 // reset s->picture[].f.extended_data to s->picture[].f.data
1537 for (i = 0; i < h->picture_count; i++)
1538 h->DPB[i].f.extended_data = h->DPB[i].f.data;
1540 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1541 h->cur_pic = h1->cur_pic;
1542 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1544 h->workaround_bugs = h1->workaround_bugs;
1545 h->low_delay = h1->low_delay;
1546 h->droppable = h1->droppable;
1548 /* frame_start may not be called for the next thread (if it's decoding
1549 * a bottom field) so this has to be allocated here */
1550 err = alloc_scratch_buffers(h, h1->linesize);
1554 // extradata/NAL handling
1555 h->is_avc = h1->is_avc;
1558 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1559 MAX_SPS_COUNT, sizeof(SPS));
1561 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1562 MAX_PPS_COUNT, sizeof(PPS));
1565 // Dequantization matrices
1566 // FIXME these are big - can they be only copied when PPS changes?
1567 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1569 for (i = 0; i < 6; i++)
1570 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1571 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1573 for (i = 0; i < 6; i++)
1574 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1575 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1577 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1580 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1583 copy_fields(h, h1, short_ref, cabac_init_idc);
1585 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1586 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1587 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1588 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1590 h->last_slice_type = h1->last_slice_type;
1592 if (context_reinitialized)
1593 h264_set_parameter_from_sps(h);
1595 if (!h->cur_pic_ptr)
1598 if (!h->droppable) {
1599 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1600 h->prev_poc_msb = h->poc_msb;
1601 h->prev_poc_lsb = h->poc_lsb;
1603 h->prev_frame_num_offset = h->frame_num_offset;
1604 h->prev_frame_num = h->frame_num;
1605 h->outputed_poc = h->next_outputed_poc;
1610 int ff_h264_frame_start(H264Context *h)
1614 const int pixel_shift = h->pixel_shift;
1616 release_unused_pictures(h, 1);
1617 h->cur_pic_ptr = NULL;
1619 i = find_unused_picture(h);
1621 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1626 pic->f.reference = h->droppable ? 0 : h->picture_structure;
1627 pic->f.coded_picture_number = h->coded_picture_number++;
1628 pic->field_picture = h->picture_structure != PICT_FRAME;
1630 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1632 * See decode_nal_units().
1634 pic->f.key_frame = 0;
1635 pic->mmco_reset = 0;
1637 if ((ret = alloc_picture(h, pic)) < 0)
1640 h->cur_pic_ptr = pic;
1641 h->cur_pic = *h->cur_pic_ptr;
1642 h->cur_pic.f.extended_data = h->cur_pic.f.data;
1644 ff_er_frame_start(&h->er);
1646 assert(h->linesize && h->uvlinesize);
1648 for (i = 0; i < 16; i++) {
1649 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1650 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1652 for (i = 0; i < 16; i++) {
1653 h->block_offset[16 + i] =
1654 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1655 h->block_offset[48 + 16 + i] =
1656 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1659 /* can't be in alloc_tables because linesize isn't known there.
1660 * FIXME: redo bipred weight to not require extra buffer? */
1661 for (i = 0; i < h->slice_context_count; i++)
1662 if (h->thread_context[i]) {
1663 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1668 /* Some macroblocks can be accessed before they're available in case
1669 * of lost slices, MBAFF or threading. */
1670 memset(h->slice_table, -1,
1671 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1673 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1674 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1676 /* We mark the current picture as non-reference after allocating it, so
1677 * that if we break out due to an error it can be released automatically
1678 * in the next ff_MPV_frame_start().
1679 * SVQ3 as well as most other codecs have only last/next/current and thus
1680 * get released even with set reference, besides SVQ3 and others do not
1681 * mark frames as reference later "naturally". */
1682 if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
1683 h->cur_pic_ptr->f.reference = 0;
1685 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1687 h->next_output_pic = NULL;
1689 assert(h->cur_pic_ptr->long_ref == 0);
1695 * Run setup operations that must be run after slice header decoding.
1696 * This includes finding the next displayed frame.
1698 * @param h h264 master context
1699 * @param setup_finished enough NALs have been read that we can call
1700 * ff_thread_finish_setup()
1702 static void decode_postinit(H264Context *h, int setup_finished)
1704 Picture *out = h->cur_pic_ptr;
1705 Picture *cur = h->cur_pic_ptr;
1706 int i, pics, out_of_order, out_idx;
1707 int invalid = 0, cnt = 0;
1709 h->cur_pic_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
1710 h->cur_pic_ptr->f.pict_type = h->pict_type;
1712 if (h->next_output_pic)
1715 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1716 /* FIXME: if we have two PAFF fields in one packet, we can't start
1717 * the next thread here. If we have one field per packet, we can.
1718 * The check in decode_nal_units() is not good enough to find this
1719 * yet, so we assume the worst for now. */
1720 // if (setup_finished)
1721 // ff_thread_finish_setup(h->avctx);
1725 cur->f.interlaced_frame = 0;
1726 cur->f.repeat_pict = 0;
1728 /* Signal interlacing information externally. */
1729 /* Prioritize picture timing SEI information over used
1730 * decoding process if it exists. */
1732 if (h->sps.pic_struct_present_flag) {
1733 switch (h->sei_pic_struct) {
1734 case SEI_PIC_STRUCT_FRAME:
1736 case SEI_PIC_STRUCT_TOP_FIELD:
1737 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1738 cur->f.interlaced_frame = 1;
1740 case SEI_PIC_STRUCT_TOP_BOTTOM:
1741 case SEI_PIC_STRUCT_BOTTOM_TOP:
1742 if (FIELD_OR_MBAFF_PICTURE)
1743 cur->f.interlaced_frame = 1;
1745 // try to flag soft telecine progressive
1746 cur->f.interlaced_frame = h->prev_interlaced_frame;
1748 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1749 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1750 /* Signal the possibility of telecined film externally
1751 * (pic_struct 5,6). From these hints, let the applications
1752 * decide if they apply deinterlacing. */
1753 cur->f.repeat_pict = 1;
1755 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1756 cur->f.repeat_pict = 2;
1758 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1759 cur->f.repeat_pict = 4;
1763 if ((h->sei_ct_type & 3) &&
1764 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1765 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1767 /* Derive interlacing flag from used decoding process. */
1768 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
1770 h->prev_interlaced_frame = cur->f.interlaced_frame;
1772 if (cur->field_poc[0] != cur->field_poc[1]) {
1773 /* Derive top_field_first from field pocs. */
1774 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
1776 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
1777 /* Use picture timing SEI information. Even if it is a
1778 * information of a past frame, better than nothing. */
1779 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1780 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1781 cur->f.top_field_first = 1;
1783 cur->f.top_field_first = 0;
1785 /* Most likely progressive */
1786 cur->f.top_field_first = 0;
1790 // FIXME do something with unavailable reference frames
1792 /* Sort B-frames into display order */
1794 if (h->sps.bitstream_restriction_flag &&
1795 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1796 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1800 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
1801 !h->sps.bitstream_restriction_flag) {
1802 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
1807 while (h->delayed_pic[pics])
1810 assert(pics <= MAX_DELAYED_PIC_COUNT);
1812 h->delayed_pic[pics++] = cur;
1813 if (cur->f.reference == 0)
1814 cur->f.reference = DELAYED_PIC_REF;
1816 /* Frame reordering. This code takes pictures from coding order and sorts
1817 * them by their incremental POC value into display order. It supports POC
1818 * gaps, MMCO reset codes and random resets.
1819 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1820 * and/or can be closed down with a MMCO reset code. In sequences where
1821 * there is no delay, we can't detect that (since the frame was already
1822 * output to the user), so we also set h->mmco_reset to detect the MMCO
1824 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
1825 * we increase the delay between input and output. All frames affected by
1826 * the lag (e.g. those that should have been output before another frame
1827 * that we already returned to the user) will be dropped. This is a bug
1828 * that we will fix later. */
1829 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1830 cnt += out->poc < h->last_pocs[i];
1831 invalid += out->poc == INT_MIN;
1833 if (!h->mmco_reset && !cur->f.key_frame &&
1834 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1837 h->delayed_pic[pics - 2]->mmco_reset = 2;
1839 if (h->mmco_reset || cur->f.key_frame) {
1840 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1841 h->last_pocs[i] = INT_MIN;
1843 invalid = MAX_DELAYED_PIC_COUNT;
1845 out = h->delayed_pic[0];
1847 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1848 h->delayed_pic[i] &&
1849 !h->delayed_pic[i - 1]->mmco_reset &&
1850 !h->delayed_pic[i]->f.key_frame;
1852 if (h->delayed_pic[i]->poc < out->poc) {
1853 out = h->delayed_pic[i];
1856 if (h->avctx->has_b_frames == 0 &&
1857 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
1858 h->next_outputed_poc = INT_MIN;
1859 out_of_order = !out->f.key_frame && !h->mmco_reset &&
1860 (out->poc < h->next_outputed_poc);
1862 if (h->sps.bitstream_restriction_flag &&
1863 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
1864 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1865 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1866 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1867 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
1870 } else if (h->low_delay &&
1871 ((h->next_outputed_poc != INT_MIN &&
1872 out->poc > h->next_outputed_poc + 2) ||
1873 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
1875 h->avctx->has_b_frames++;
1878 if (pics > h->avctx->has_b_frames) {
1879 out->f.reference &= ~DELAYED_PIC_REF;
1880 // for frame threading, the owner must be the second field's thread or
1881 // else the first thread can release the picture and reuse it unsafely
1883 for (i = out_idx; h->delayed_pic[i]; i++)
1884 h->delayed_pic[i] = h->delayed_pic[i + 1];
1886 memmove(h->last_pocs, &h->last_pocs[1],
1887 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1888 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1889 if (!out_of_order && pics > h->avctx->has_b_frames) {
1890 h->next_output_pic = out;
1891 if (out->mmco_reset) {
1893 h->next_outputed_poc = out->poc;
1894 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1896 h->next_outputed_poc = INT_MIN;
1899 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
1900 h->next_outputed_poc = INT_MIN;
1902 h->next_outputed_poc = out->poc;
1907 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
1911 ff_thread_finish_setup(h->avctx);
1914 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
1915 uint8_t *src_cb, uint8_t *src_cr,
1916 int linesize, int uvlinesize,
1919 uint8_t *top_border;
1921 const int pixel_shift = h->pixel_shift;
1922 int chroma444 = CHROMA444;
1923 int chroma422 = CHROMA422;
1926 src_cb -= uvlinesize;
1927 src_cr -= uvlinesize;
1929 if (!simple && FRAME_MBAFF) {
1932 top_border = h->top_borders[0][h->mb_x];
1933 AV_COPY128(top_border, src_y + 15 * linesize);
1935 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
1936 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
1939 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1940 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
1941 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
1942 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
1944 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
1945 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
1947 } else if (chroma422) {
1949 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
1950 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
1952 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
1953 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
1957 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
1958 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
1960 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
1961 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
1966 } else if (MB_MBAFF) {
1972 top_border = h->top_borders[top_idx][h->mb_x];
1973 /* There are two lines saved, the line above the top macroblock
1974 * of a pair, and the line above the bottom macroblock. */
1975 AV_COPY128(top_border, src_y + 16 * linesize);
1977 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
1979 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
1982 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
1983 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
1984 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
1985 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
1987 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
1988 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
1990 } else if (chroma422) {
1992 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
1993 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
1995 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
1996 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2000 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2001 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2003 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2004 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2010 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2011 uint8_t *src_cb, uint8_t *src_cr,
2012 int linesize, int uvlinesize,
2013 int xchg, int chroma444,
2014 int simple, int pixel_shift)
2016 int deblock_topleft;
2019 uint8_t *top_border_m1;
2020 uint8_t *top_border;
2022 if (!simple && FRAME_MBAFF) {
2027 top_idx = MB_MBAFF ? 0 : 1;
2031 if (h->deblocking_filter == 2) {
2032 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2033 deblock_top = h->top_type;
2035 deblock_topleft = (h->mb_x > 0);
2036 deblock_top = (h->mb_y > !!MB_FIELD);
2039 src_y -= linesize + 1 + pixel_shift;
2040 src_cb -= uvlinesize + 1 + pixel_shift;
2041 src_cr -= uvlinesize + 1 + pixel_shift;
2043 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2044 top_border = h->top_borders[top_idx][h->mb_x];
2046 #define XCHG(a, b, xchg) \
2047 if (pixel_shift) { \
2049 AV_SWAP64(b + 0, a + 0); \
2050 AV_SWAP64(b + 8, a + 8); \
2060 if (deblock_topleft) {
2061 XCHG(top_border_m1 + (8 << pixel_shift),
2062 src_y - (7 << pixel_shift), 1);
2064 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2065 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2066 if (h->mb_x + 1 < h->mb_width) {
2067 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2068 src_y + (17 << pixel_shift), 1);
2071 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2073 if (deblock_topleft) {
2074 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2075 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2077 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2078 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2079 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2080 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2081 if (h->mb_x + 1 < h->mb_width) {
2082 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2083 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2087 if (deblock_topleft) {
2088 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2089 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2091 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2092 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2098 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2101 if (high_bit_depth) {
2102 return AV_RN32A(((int32_t *)mb) + index);
2104 return AV_RN16A(mb + index);
2107 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2108 int index, int value)
2110 if (high_bit_depth) {
2111 AV_WN32A(((int32_t *)mb) + index, value);
2113 AV_WN16A(mb + index, value);
2116 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2117 int mb_type, int is_h264,
2119 int transform_bypass,
2123 uint8_t *dest_y, int p)
2125 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2126 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2128 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2129 block_offset += 16 * p;
2130 if (IS_INTRA4x4(mb_type)) {
2131 if (IS_8x8DCT(mb_type)) {
2132 if (transform_bypass) {
2134 idct_add = h->h264dsp.h264_add_pixels8;
2136 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2137 idct_add = h->h264dsp.h264_idct8_add;
2139 for (i = 0; i < 16; i += 4) {
2140 uint8_t *const ptr = dest_y + block_offset[i];
2141 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2142 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2143 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2145 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2146 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2147 (h->topright_samples_available << i) & 0x4000, linesize);
2149 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2150 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2152 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2157 if (transform_bypass) {
2159 idct_add = h->h264dsp.h264_add_pixels4;
2161 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2162 idct_add = h->h264dsp.h264_idct_add;
2164 for (i = 0; i < 16; i++) {
2165 uint8_t *const ptr = dest_y + block_offset[i];
2166 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2168 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2169 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2174 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2175 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2176 assert(h->mb_y || linesize <= block_offset[i]);
2177 if (!topright_avail) {
2179 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2180 topright = (uint8_t *)&tr_high;
2182 tr = ptr[3 - linesize] * 0x01010101u;
2183 topright = (uint8_t *)&tr;
2186 topright = ptr + (4 << pixel_shift) - linesize;
2190 h->hpc.pred4x4[dir](ptr, topright, linesize);
2191 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2194 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2195 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2197 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2198 } else if (CONFIG_SVQ3_DECODER)
2199 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2205 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2207 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2208 if (!transform_bypass)
2209 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2211 h->dequant4_coeff[p][qscale][0]);
2213 static const uint8_t dc_mapping[16] = {
2214 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2215 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2216 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2217 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
2218 for (i = 0; i < 16; i++)
2219 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2220 pixel_shift, dc_mapping[i],
2221 dctcoef_get(h->mb_luma_dc[p],
2225 } else if (CONFIG_SVQ3_DECODER)
2226 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2227 h->mb_luma_dc[p], qscale);
2231 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2232 int is_h264, int simple,
2233 int transform_bypass,
2237 uint8_t *dest_y, int p)
2239 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2241 block_offset += 16 * p;
2242 if (!IS_INTRA4x4(mb_type)) {
2244 if (IS_INTRA16x16(mb_type)) {
2245 if (transform_bypass) {
2246 if (h->sps.profile_idc == 244 &&
2247 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2248 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2249 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2250 h->mb + (p * 256 << pixel_shift),
2253 for (i = 0; i < 16; i++)
2254 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2255 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2256 h->h264dsp.h264_add_pixels4(dest_y + block_offset[i],
2257 h->mb + (i * 16 + p * 256 << pixel_shift),
2261 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2262 h->mb + (p * 256 << pixel_shift),
2264 h->non_zero_count_cache + p * 5 * 8);
2266 } else if (h->cbp & 15) {
2267 if (transform_bypass) {
2268 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2269 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8
2270 : h->h264dsp.h264_add_pixels4;
2271 for (i = 0; i < 16; i += di)
2272 if (h->non_zero_count_cache[scan8[i + p * 16]])
2273 idct_add(dest_y + block_offset[i],
2274 h->mb + (i * 16 + p * 256 << pixel_shift),
2277 if (IS_8x8DCT(mb_type))
2278 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2279 h->mb + (p * 256 << pixel_shift),
2281 h->non_zero_count_cache + p * 5 * 8);
2283 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2284 h->mb + (p * 256 << pixel_shift),
2286 h->non_zero_count_cache + p * 5 * 8);
2289 } else if (CONFIG_SVQ3_DECODER) {
2290 for (i = 0; i < 16; i++)
2291 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2292 // FIXME benchmark weird rule, & below
2293 uint8_t *const ptr = dest_y + block_offset[i];
2294 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2295 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2303 #include "h264_mb_template.c"
2307 #include "h264_mb_template.c"
2311 #include "h264_mb_template.c"
2313 void ff_h264_hl_decode_mb(H264Context *h)
2315 const int mb_xy = h->mb_xy;
2316 const int mb_type = h->cur_pic.f.mb_type[mb_xy];
2317 int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
2320 if (is_complex || h->pixel_shift)
2321 hl_decode_mb_444_complex(h);
2323 hl_decode_mb_444_simple_8(h);
2324 } else if (is_complex) {
2325 hl_decode_mb_complex(h);
2326 } else if (h->pixel_shift) {
2327 hl_decode_mb_simple_16(h);
2329 hl_decode_mb_simple_8(h);
2332 static int pred_weight_table(H264Context *h)
2335 int luma_def, chroma_def;
2338 h->use_weight_chroma = 0;
2339 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2340 if (h->sps.chroma_format_idc)
2341 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2342 luma_def = 1 << h->luma_log2_weight_denom;
2343 chroma_def = 1 << h->chroma_log2_weight_denom;
2345 for (list = 0; list < 2; list++) {
2346 h->luma_weight_flag[list] = 0;
2347 h->chroma_weight_flag[list] = 0;
2348 for (i = 0; i < h->ref_count[list]; i++) {
2349 int luma_weight_flag, chroma_weight_flag;
2351 luma_weight_flag = get_bits1(&h->gb);
2352 if (luma_weight_flag) {
2353 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2354 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2355 if (h->luma_weight[i][list][0] != luma_def ||
2356 h->luma_weight[i][list][1] != 0) {
2358 h->luma_weight_flag[list] = 1;
2361 h->luma_weight[i][list][0] = luma_def;
2362 h->luma_weight[i][list][1] = 0;
2365 if (h->sps.chroma_format_idc) {
2366 chroma_weight_flag = get_bits1(&h->gb);
2367 if (chroma_weight_flag) {
2369 for (j = 0; j < 2; j++) {
2370 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2371 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2372 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2373 h->chroma_weight[i][list][j][1] != 0) {
2374 h->use_weight_chroma = 1;
2375 h->chroma_weight_flag[list] = 1;
2380 for (j = 0; j < 2; j++) {
2381 h->chroma_weight[i][list][j][0] = chroma_def;
2382 h->chroma_weight[i][list][j][1] = 0;
2387 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2390 h->use_weight = h->use_weight || h->use_weight_chroma;
2395 * Initialize implicit_weight table.
2396 * @param field 0/1 initialize the weight for interlaced MBAFF
2397 * -1 initializes the rest
2399 static void implicit_weight_table(H264Context *h, int field)
2401 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2403 for (i = 0; i < 2; i++) {
2404 h->luma_weight_flag[i] = 0;
2405 h->chroma_weight_flag[i] = 0;
2409 if (h->picture_structure == PICT_FRAME) {
2410 cur_poc = h->cur_pic_ptr->poc;
2412 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2414 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
2415 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2417 h->use_weight_chroma = 0;
2421 ref_count0 = h->ref_count[0];
2422 ref_count1 = h->ref_count[1];
2424 cur_poc = h->cur_pic_ptr->field_poc[field];
2426 ref_count0 = 16 + 2 * h->ref_count[0];
2427 ref_count1 = 16 + 2 * h->ref_count[1];
2431 h->use_weight_chroma = 2;
2432 h->luma_log2_weight_denom = 5;
2433 h->chroma_log2_weight_denom = 5;
2435 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2436 int poc0 = h->ref_list[0][ref0].poc;
2437 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2439 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2440 int poc1 = h->ref_list[1][ref1].poc;
2441 int td = av_clip(poc1 - poc0, -128, 127);
2443 int tb = av_clip(cur_poc - poc0, -128, 127);
2444 int tx = (16384 + (FFABS(td) >> 1)) / td;
2445 int dist_scale_factor = (tb * tx + 32) >> 8;
2446 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2447 w = 64 - dist_scale_factor;
2451 h->implicit_weight[ref0][ref1][0] =
2452 h->implicit_weight[ref0][ref1][1] = w;
2454 h->implicit_weight[ref0][ref1][field] = w;
2461 * instantaneous decoder refresh.
2463 static void idr(H264Context *h)
2465 ff_h264_remove_all_refs(h);
2466 h->prev_frame_num = 0;
2467 h->prev_frame_num_offset = 0;
2469 h->prev_poc_lsb = 0;
2472 /* forget old pics after a seek */
2473 static void flush_change(H264Context *h)
2476 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2477 h->last_pocs[i] = INT_MIN;
2478 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2479 h->prev_interlaced_frame = 1;
2482 h->cur_pic_ptr->f.reference = 0;
2484 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2485 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2486 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2487 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2488 ff_h264_reset_sei(h);
2491 /* forget old pics after a seek */
2492 static void flush_dpb(AVCodecContext *avctx)
2494 H264Context *h = avctx->priv_data;
2497 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2498 if (h->delayed_pic[i])
2499 h->delayed_pic[i]->f.reference = 0;
2500 h->delayed_pic[i] = NULL;
2505 for (i = 0; i < h->picture_count; i++) {
2506 if (h->DPB[i].f.data[0])
2507 free_frame_buffer(h, &h->DPB[i]);
2509 h->cur_pic_ptr = NULL;
2511 h->mb_x = h->mb_y = 0;
2513 h->parse_context.state = -1;
2514 h->parse_context.frame_start_found = 0;
2515 h->parse_context.overread = 0;
2516 h->parse_context.overread_index = 0;
2517 h->parse_context.index = 0;
2518 h->parse_context.last_index = 0;
2521 static int init_poc(H264Context *h)
2523 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2525 Picture *cur = h->cur_pic_ptr;
2527 h->frame_num_offset = h->prev_frame_num_offset;
2528 if (h->frame_num < h->prev_frame_num)
2529 h->frame_num_offset += max_frame_num;
2531 if (h->sps.poc_type == 0) {
2532 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2534 if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2535 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2536 else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2537 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2539 h->poc_msb = h->prev_poc_msb;
2541 field_poc[1] = h->poc_msb + h->poc_lsb;
2542 if (h->picture_structure == PICT_FRAME)
2543 field_poc[1] += h->delta_poc_bottom;
2544 } else if (h->sps.poc_type == 1) {
2545 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2548 if (h->sps.poc_cycle_length != 0)
2549 abs_frame_num = h->frame_num_offset + h->frame_num;
2553 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2556 expected_delta_per_poc_cycle = 0;
2557 for (i = 0; i < h->sps.poc_cycle_length; i++)
2558 // FIXME integrate during sps parse
2559 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2561 if (abs_frame_num > 0) {
2562 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2563 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2565 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2566 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2567 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2571 if (h->nal_ref_idc == 0)
2572 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2574 field_poc[0] = expectedpoc + h->delta_poc[0];
2575 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2577 if (h->picture_structure == PICT_FRAME)
2578 field_poc[1] += h->delta_poc[1];
2580 int poc = 2 * (h->frame_num_offset + h->frame_num);
2582 if (!h->nal_ref_idc)
2589 if (h->picture_structure != PICT_BOTTOM_FIELD)
2590 h->cur_pic_ptr->field_poc[0] = field_poc[0];
2591 if (h->picture_structure != PICT_TOP_FIELD)
2592 h->cur_pic_ptr->field_poc[1] = field_poc[1];
2593 cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
2599 * initialize scan tables
2601 static void init_scan_tables(H264Context *h)
2604 for (i = 0; i < 16; i++) {
2605 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2606 h->zigzag_scan[i] = T(zigzag_scan[i]);
2607 h->field_scan[i] = T(field_scan[i]);
2610 for (i = 0; i < 64; i++) {
2611 #define T(x) (x >> 3) | ((x & 7) << 3)
2612 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2613 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2614 h->field_scan8x8[i] = T(field_scan8x8[i]);
2615 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2618 if (h->sps.transform_bypass) { // FIXME same ugly
2619 h->zigzag_scan_q0 = zigzag_scan;
2620 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2621 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2622 h->field_scan_q0 = field_scan;
2623 h->field_scan8x8_q0 = field_scan8x8;
2624 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2626 h->zigzag_scan_q0 = h->zigzag_scan;
2627 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2628 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2629 h->field_scan_q0 = h->field_scan;
2630 h->field_scan8x8_q0 = h->field_scan8x8;
2631 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2635 static int field_end(H264Context *h, int in_setup)
2637 AVCodecContext *const avctx = h->avctx;
2641 if (!in_setup && !h->droppable)
2642 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
2643 h->picture_structure == PICT_BOTTOM_FIELD);
2645 if (CONFIG_H264_VDPAU_DECODER &&
2646 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2647 ff_vdpau_h264_set_reference_frames(h);
2649 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2650 if (!h->droppable) {
2651 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2652 h->prev_poc_msb = h->poc_msb;
2653 h->prev_poc_lsb = h->poc_lsb;
2655 h->prev_frame_num_offset = h->frame_num_offset;
2656 h->prev_frame_num = h->frame_num;
2657 h->outputed_poc = h->next_outputed_poc;
2660 if (avctx->hwaccel) {
2661 if (avctx->hwaccel->end_frame(avctx) < 0)
2662 av_log(avctx, AV_LOG_ERROR,
2663 "hardware accelerator failed to decode picture\n");
2666 if (CONFIG_H264_VDPAU_DECODER &&
2667 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2668 ff_vdpau_h264_picture_complete(h);
2671 * FIXME: Error handling code does not seem to support interlaced
2672 * when slices span multiple rows
2673 * The ff_er_add_slice calls don't work right for bottom
2674 * fields; they cause massive erroneous error concealing
2675 * Error marking covers both fields (top and bottom).
2676 * This causes a mismatched s->error_count
2677 * and a bad error table. Further, the error count goes to
2678 * INT_MAX when called for bottom field, because mb_y is
2679 * past end by one (callers fault) and resync_mb_y != 0
2680 * causes problems for the first MB line, too.
2682 if (!FIELD_PICTURE) {
2683 h->er.cur_pic = h->cur_pic_ptr;
2684 h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
2685 h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
2686 ff_er_frame_end(&h->er);
2690 h->current_slice = 0;
2696 * Replicate H264 "master" context to thread contexts.
2698 static int clone_slice(H264Context *dst, H264Context *src)
2700 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2701 dst->cur_pic_ptr = src->cur_pic_ptr;
2702 dst->cur_pic = src->cur_pic;
2703 dst->linesize = src->linesize;
2704 dst->uvlinesize = src->uvlinesize;
2705 dst->first_field = src->first_field;
2707 dst->prev_poc_msb = src->prev_poc_msb;
2708 dst->prev_poc_lsb = src->prev_poc_lsb;
2709 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2710 dst->prev_frame_num = src->prev_frame_num;
2711 dst->short_ref_count = src->short_ref_count;
2713 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2714 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2715 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2717 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2718 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2724 * Compute profile from profile_idc and constraint_set?_flags.
2728 * @return profile as defined by FF_PROFILE_H264_*
2730 int ff_h264_get_profile(SPS *sps)
2732 int profile = sps->profile_idc;
2734 switch (sps->profile_idc) {
2735 case FF_PROFILE_H264_BASELINE:
2736 // constraint_set1_flag set to 1
2737 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2739 case FF_PROFILE_H264_HIGH_10:
2740 case FF_PROFILE_H264_HIGH_422:
2741 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2742 // constraint_set3_flag set to 1
2743 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2750 static int h264_set_parameter_from_sps(H264Context *h)
2752 if (h->flags & CODEC_FLAG_LOW_DELAY ||
2753 (h->sps.bitstream_restriction_flag &&
2754 !h->sps.num_reorder_frames)) {
2755 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2756 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
2757 "Reenabling low delay requires a codec flush.\n");
2762 if (h->avctx->has_b_frames < 2)
2763 h->avctx->has_b_frames = !h->low_delay;
2765 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
2766 av_log_missing_feature(h->avctx,
2767 "Different bit depth between chroma and luma", 1);
2768 return AVERROR_PATCHWELCOME;
2771 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2772 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2773 if (h->avctx->codec &&
2774 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
2775 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
2776 av_log(h->avctx, AV_LOG_ERROR,
2777 "VDPAU decoding does not support video colorspace.\n");
2778 return AVERROR_INVALIDDATA;
2780 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
2781 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2782 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2783 h->pixel_shift = h->sps.bit_depth_luma > 8;
2785 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2786 h->sps.chroma_format_idc);
2787 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2788 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
2789 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
2790 h->sps.chroma_format_idc);
2791 h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
2792 ff_dsputil_init(&h->dsp, h->avctx);
2793 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
2795 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
2796 h->sps.bit_depth_luma);
2797 return AVERROR_INVALIDDATA;
2803 static enum PixelFormat get_pixel_format(H264Context *h)
2805 switch (h->sps.bit_depth_luma) {
2808 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2809 return AV_PIX_FMT_GBRP9;
2811 return AV_PIX_FMT_YUV444P9;
2812 } else if (CHROMA422)
2813 return AV_PIX_FMT_YUV422P9;
2815 return AV_PIX_FMT_YUV420P9;
2819 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2820 return AV_PIX_FMT_GBRP10;
2822 return AV_PIX_FMT_YUV444P10;
2823 } else if (CHROMA422)
2824 return AV_PIX_FMT_YUV422P10;
2826 return AV_PIX_FMT_YUV420P10;
2830 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
2831 return AV_PIX_FMT_GBRP;
2833 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
2834 : AV_PIX_FMT_YUV444P;
2835 } else if (CHROMA422) {
2836 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
2837 : AV_PIX_FMT_YUV422P;
2839 return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
2840 h->avctx->codec->pix_fmts :
2841 h->avctx->color_range == AVCOL_RANGE_JPEG ?
2842 h264_hwaccel_pixfmt_list_jpeg_420 :
2843 h264_hwaccel_pixfmt_list_420);
2847 av_log(h->avctx, AV_LOG_ERROR,
2848 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
2849 return AVERROR_INVALIDDATA;
2853 static int h264_slice_header_init(H264Context *h, int reinit)
2855 int nb_slices = (HAVE_THREADS &&
2856 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
2857 h->avctx->thread_count : 1;
2860 avcodec_set_dimensions(h->avctx, h->width, h->height);
2861 h->avctx->sample_aspect_ratio = h->sps.sar;
2862 av_assert0(h->avctx->sample_aspect_ratio.den);
2863 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
2864 &h->chroma_x_shift, &h->chroma_y_shift);
2866 if (h->sps.timing_info_present_flag) {
2867 int64_t den = h->sps.time_scale;
2868 if (h->x264_build < 44U)
2870 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
2871 h->sps.num_units_in_tick, den, 1 << 30);
2874 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
2879 h->prev_interlaced_frame = 1;
2881 init_scan_tables(h);
2882 if (ff_h264_alloc_tables(h) < 0) {
2883 av_log(h->avctx, AV_LOG_ERROR,
2884 "Could not allocate memory for h264\n");
2885 return AVERROR(ENOMEM);
2888 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
2891 max_slices = FFMIN(MAX_THREADS, h->mb_height);
2893 max_slices = MAX_THREADS;
2894 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
2895 " reducing to %d\n", nb_slices, max_slices);
2896 nb_slices = max_slices;
2898 h->slice_context_count = nb_slices;
2900 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
2901 if (context_init(h) < 0) {
2902 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
2906 for (i = 1; i < h->slice_context_count; i++) {
2908 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
2909 c->avctx = h->avctx;
2912 c->h264dsp = h->h264dsp;
2913 c->h264qpel = h->h264qpel;
2914 c->h264chroma = h->h264chroma;
2917 c->pixel_shift = h->pixel_shift;
2918 c->width = h->width;
2919 c->height = h->height;
2920 c->linesize = h->linesize;
2921 c->uvlinesize = h->uvlinesize;
2922 c->chroma_x_shift = h->chroma_x_shift;
2923 c->chroma_y_shift = h->chroma_y_shift;
2924 c->qscale = h->qscale;
2925 c->droppable = h->droppable;
2926 c->data_partitioning = h->data_partitioning;
2927 c->low_delay = h->low_delay;
2928 c->mb_width = h->mb_width;
2929 c->mb_height = h->mb_height;
2930 c->mb_stride = h->mb_stride;
2931 c->mb_num = h->mb_num;
2932 c->flags = h->flags;
2933 c->workaround_bugs = h->workaround_bugs;
2934 c->pict_type = h->pict_type;
2936 init_scan_tables(c);
2937 clone_tables(c, h, i);
2938 c->context_initialized = 1;
2941 for (i = 0; i < h->slice_context_count; i++)
2942 if (context_init(h->thread_context[i]) < 0) {
2943 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
2948 h->context_initialized = 1;
2954 * Decode a slice header.
2955 * This will also call ff_MPV_common_init() and frame_start() as needed.
2957 * @param h h264context
2958 * @param h0 h264 master context (differs from 'h' when doing sliced based
2959 * parallel decoding)
2961 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
2963 static int decode_slice_header(H264Context *h, H264Context *h0)
2965 unsigned int first_mb_in_slice;
2966 unsigned int pps_id;
2967 int num_ref_idx_active_override_flag, max_refs, ret;
2968 unsigned int slice_type, tmp, i, j;
2969 int default_ref_list_done = 0;
2970 int last_pic_structure, last_pic_droppable;
2971 int needs_reinit = 0;
2973 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
2974 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
2976 first_mb_in_slice = get_ue_golomb(&h->gb);
2978 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
2979 if (h0->current_slice && FIELD_PICTURE) {
2983 h0->current_slice = 0;
2984 if (!h0->first_field) {
2985 if (h->cur_pic_ptr && !h->droppable &&
2986 h->cur_pic_ptr->owner2 == h) {
2987 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
2988 h->picture_structure == PICT_BOTTOM_FIELD);
2990 h->cur_pic_ptr = NULL;
2994 slice_type = get_ue_golomb_31(&h->gb);
2995 if (slice_type > 9) {
2996 av_log(h->avctx, AV_LOG_ERROR,
2997 "slice type too large (%d) at %d %d\n",
2998 h->slice_type, h->mb_x, h->mb_y);
3001 if (slice_type > 4) {
3003 h->slice_type_fixed = 1;
3005 h->slice_type_fixed = 0;
3007 slice_type = golomb_to_pict_type[slice_type];
3008 if (slice_type == AV_PICTURE_TYPE_I ||
3009 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3010 default_ref_list_done = 1;
3012 h->slice_type = slice_type;
3013 h->slice_type_nos = slice_type & 3;
3015 // to make a few old functions happy, it's wrong though
3016 h->pict_type = h->slice_type;
3018 pps_id = get_ue_golomb(&h->gb);
3019 if (pps_id >= MAX_PPS_COUNT) {
3020 av_log(h->avctx, AV_LOG_ERROR, "pps_id out of range\n");
3023 if (!h0->pps_buffers[pps_id]) {
3024 av_log(h->avctx, AV_LOG_ERROR,
3025 "non-existing PPS %u referenced\n",
3029 h->pps = *h0->pps_buffers[pps_id];
3031 if (!h0->sps_buffers[h->pps.sps_id]) {
3032 av_log(h->avctx, AV_LOG_ERROR,
3033 "non-existing SPS %u referenced\n",
3038 if (h->pps.sps_id != h->current_sps_id ||
3039 h0->sps_buffers[h->pps.sps_id]->new) {
3040 h0->sps_buffers[h->pps.sps_id]->new = 0;
3042 h->current_sps_id = h->pps.sps_id;
3043 h->sps = *h0->sps_buffers[h->pps.sps_id];
3045 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3046 h->chroma_format_idc != h->sps.chroma_format_idc) {
3047 h->bit_depth_luma = h->sps.bit_depth_luma;
3048 h->chroma_format_idc = h->sps.chroma_format_idc;
3051 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3055 h->avctx->profile = ff_h264_get_profile(&h->sps);
3056 h->avctx->level = h->sps.level_idc;
3057 h->avctx->refs = h->sps.ref_frame_count;
3059 if (h->mb_width != h->sps.mb_width ||
3060 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
3063 h->mb_width = h->sps.mb_width;
3064 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3065 h->mb_num = h->mb_width * h->mb_height;
3066 h->mb_stride = h->mb_width + 1;
3068 h->b_stride = h->mb_width * 4;
3070 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3072 h->width = 16 * h->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
3073 if (h->sps.frame_mbs_only_flag)
3074 h->height = 16 * h->mb_height - (1 << h->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> h->chroma_y_shift) - 1);
3076 h->height = 16 * h->mb_height - (2 << h->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> h->chroma_y_shift) - 1);
3078 if (FFALIGN(h->avctx->width, 16) == h->width &&
3079 FFALIGN(h->avctx->height, 16) == h->height) {
3080 h->width = h->avctx->width;
3081 h->height = h->avctx->height;
3084 if (h->sps.video_signal_type_present_flag) {
3085 h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
3087 if (h->sps.colour_description_present_flag) {
3088 if (h->avctx->colorspace != h->sps.colorspace)
3090 h->avctx->color_primaries = h->sps.color_primaries;
3091 h->avctx->color_trc = h->sps.color_trc;
3092 h->avctx->colorspace = h->sps.colorspace;
3096 if (h->context_initialized &&
3097 (h->width != h->avctx->width ||
3098 h->height != h->avctx->height ||
3102 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3103 "slice %d\n", h0->current_slice + 1);
3104 return AVERROR_INVALIDDATA;
3109 if ((ret = get_pixel_format(h)) < 0)
3111 h->avctx->pix_fmt = ret;
3113 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3114 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3116 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3117 av_log(h->avctx, AV_LOG_ERROR,
3118 "h264_slice_header_init() failed\n");
3122 if (!h->context_initialized) {
3124 av_log(h->avctx, AV_LOG_ERROR,
3125 "Cannot (re-)initialize context during parallel decoding.\n");
3129 if ((ret = get_pixel_format(h)) < 0)
3131 h->avctx->pix_fmt = ret;
3133 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3134 av_log(h->avctx, AV_LOG_ERROR,
3135 "h264_slice_header_init() failed\n");
3140 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3141 h->dequant_coeff_pps = pps_id;
3142 init_dequant_tables(h);
3145 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3148 h->mb_aff_frame = 0;
3149 last_pic_structure = h0->picture_structure;
3150 last_pic_droppable = h0->droppable;
3151 h->droppable = h->nal_ref_idc == 0;
3152 if (h->sps.frame_mbs_only_flag) {
3153 h->picture_structure = PICT_FRAME;
3155 if (get_bits1(&h->gb)) { // field_pic_flag
3156 h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
3158 h->picture_structure = PICT_FRAME;
3159 h->mb_aff_frame = h->sps.mb_aff;
3162 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3164 if (h0->current_slice != 0) {
3165 if (last_pic_structure != h->picture_structure ||
3166 last_pic_droppable != h->droppable) {
3167 av_log(h->avctx, AV_LOG_ERROR,
3168 "Changing field mode (%d -> %d) between slices is not allowed\n",
3169 last_pic_structure, h->picture_structure);
3170 h->picture_structure = last_pic_structure;
3171 h->droppable = last_pic_droppable;
3172 return AVERROR_INVALIDDATA;
3173 } else if (!h0->cur_pic_ptr) {
3174 av_log(h->avctx, AV_LOG_ERROR,
3175 "unset cur_pic_ptr on %d. slice\n",
3176 h0->current_slice + 1);
3177 return AVERROR_INVALIDDATA;
3180 /* Shorten frame num gaps so we don't have to allocate reference
3181 * frames just to throw them away */
3182 if (h->frame_num != h->prev_frame_num) {
3183 int unwrap_prev_frame_num = h->prev_frame_num;
3184 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3186 if (unwrap_prev_frame_num > h->frame_num)
3187 unwrap_prev_frame_num -= max_frame_num;
3189 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3190 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3191 if (unwrap_prev_frame_num < 0)
3192 unwrap_prev_frame_num += max_frame_num;
3194 h->prev_frame_num = unwrap_prev_frame_num;
3198 /* See if we have a decoded first field looking for a pair...
3199 * Here, we're using that to see if we should mark previously
3200 * decode frames as "finished".
3201 * We have to do that before the "dummy" in-between frame allocation,
3202 * since that can modify s->current_picture_ptr. */
3203 if (h0->first_field) {
3204 assert(h0->cur_pic_ptr);
3205 assert(h0->cur_pic_ptr->f.data[0]);
3206 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3208 /* Mark old field/frame as completed */
3209 if (!last_pic_droppable && h0->cur_pic_ptr->owner2 == h0) {
3210 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3211 last_pic_structure == PICT_BOTTOM_FIELD);
3214 /* figure out if we have a complementary field pair */
3215 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3216 /* Previous field is unmatched. Don't display it, but let it
3217 * remain for reference if marked as such. */
3218 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3219 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3220 last_pic_structure == PICT_TOP_FIELD);
3223 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3224 /* This and previous field were reference, but had
3225 * different frame_nums. Consider this field first in
3226 * pair. Throw away previous field except for reference
3228 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3229 ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
3230 last_pic_structure == PICT_TOP_FIELD);
3233 /* Second field in complementary pair */
3234 if (!((last_pic_structure == PICT_TOP_FIELD &&
3235 h->picture_structure == PICT_BOTTOM_FIELD) ||
3236 (last_pic_structure == PICT_BOTTOM_FIELD &&
3237 h->picture_structure == PICT_TOP_FIELD))) {
3238 av_log(h->avctx, AV_LOG_ERROR,
3239 "Invalid field mode combination %d/%d\n",
3240 last_pic_structure, h->picture_structure);
3241 h->picture_structure = last_pic_structure;
3242 h->droppable = last_pic_droppable;
3243 return AVERROR_INVALIDDATA;
3244 } else if (last_pic_droppable != h->droppable) {
3245 av_log(h->avctx, AV_LOG_ERROR,
3246 "Cannot combine reference and non-reference fields in the same frame\n");
3247 av_log_ask_for_sample(h->avctx, NULL);
3248 h->picture_structure = last_pic_structure;
3249 h->droppable = last_pic_droppable;
3250 return AVERROR_PATCHWELCOME;
3253 /* Take ownership of this buffer. Note that if another thread owned
3254 * the first field of this buffer, we're not operating on that pointer,
3255 * so the original thread is still responsible for reporting progress
3256 * on that first field (or if that was us, we just did that above).
3257 * By taking ownership, we assign responsibility to ourselves to
3258 * report progress on the second field. */
3259 h0->cur_pic_ptr->owner2 = h0;
3264 while (h->frame_num != h->prev_frame_num &&
3265 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3266 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3267 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3268 h->frame_num, h->prev_frame_num);
3269 if (ff_h264_frame_start(h) < 0)
3271 h->prev_frame_num++;
3272 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3273 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3274 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 0);
3275 ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 1);
3276 if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
3277 h->avctx->err_recognition & AV_EF_EXPLODE)
3279 if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
3280 (h->avctx->err_recognition & AV_EF_EXPLODE))
3281 return AVERROR_INVALIDDATA;
3282 /* Error concealment: if a ref is missing, copy the previous ref in its place.
3283 * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
3284 * about there being no actual duplicates.
3285 * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
3286 * concealing a lost frame, this probably isn't noticeable by comparison, but it should
3288 if (h->short_ref_count) {
3290 av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
3291 (const uint8_t **)prev->f.data, prev->f.linesize,
3292 h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
3293 h->short_ref[0]->poc = prev->poc + 2;
3295 h->short_ref[0]->frame_num = h->prev_frame_num;
3299 /* See if we have a decoded first field looking for a pair...
3300 * We're using that to see whether to continue decoding in that
3301 * frame, or to allocate a new one. */
3302 if (h0->first_field) {
3303 assert(h0->cur_pic_ptr);
3304 assert(h0->cur_pic_ptr->f.data[0]);
3305 assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
3307 /* figure out if we have a complementary field pair */
3308 if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
3309 /* Previous field is unmatched. Don't display it, but let it
3310 * remain for reference if marked as such. */
3311 h0->cur_pic_ptr = NULL;
3312 h0->first_field = FIELD_PICTURE;
3314 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3315 /* This and the previous field had different frame_nums.
3316 * Consider this field first in pair. Throw away previous
3317 * one except for reference purposes. */
3318 h0->first_field = 1;
3319 h0->cur_pic_ptr = NULL;
3321 /* Second field in complementary pair */
3322 h0->first_field = 0;
3326 /* Frame or first field in a potentially complementary pair */
3327 h0->first_field = FIELD_PICTURE;
3330 if (!FIELD_PICTURE || h0->first_field) {
3331 if (ff_h264_frame_start(h) < 0) {
3332 h0->first_field = 0;
3336 release_unused_pictures(h, 0);
3339 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3342 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3344 assert(h->mb_num == h->mb_width * h->mb_height);
3345 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= h->mb_num ||
3346 first_mb_in_slice >= h->mb_num) {
3347 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3350 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3351 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE;
3352 if (h->picture_structure == PICT_BOTTOM_FIELD)
3353 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3354 assert(h->mb_y < h->mb_height);
3356 if (h->picture_structure == PICT_FRAME) {
3357 h->curr_pic_num = h->frame_num;
3358 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3360 h->curr_pic_num = 2 * h->frame_num + 1;
3361 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3364 if (h->nal_unit_type == NAL_IDR_SLICE)
3365 get_ue_golomb(&h->gb); /* idr_pic_id */
3367 if (h->sps.poc_type == 0) {
3368 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3370 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3371 h->delta_poc_bottom = get_se_golomb(&h->gb);
3374 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3375 h->delta_poc[0] = get_se_golomb(&h->gb);
3377 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3378 h->delta_poc[1] = get_se_golomb(&h->gb);
3383 if (h->pps.redundant_pic_cnt_present)
3384 h->redundant_pic_count = get_ue_golomb(&h->gb);
3386 // set defaults, might be overridden a few lines later
3387 h->ref_count[0] = h->pps.ref_count[0];
3388 h->ref_count[1] = h->pps.ref_count[1];
3390 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3391 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3392 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3393 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3395 if (num_ref_idx_active_override_flag) {
3396 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3397 if (h->ref_count[0] < 1)
3398 return AVERROR_INVALIDDATA;
3399 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3400 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3401 if (h->ref_count[1] < 1)
3402 return AVERROR_INVALIDDATA;
3406 if (h->slice_type_nos == AV_PICTURE_TYPE_B)