2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/avassert.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/opt.h"
35 #include "cabac_functions.h"
37 #include "error_resilience.h"
39 #include "mpegvideo.h"
42 #include "h264chroma.h"
43 #include "h264_mvpred.h"
46 #include "rectangle.h"
49 #include "vdpau_internal.h"
53 static void flush_change(H264Context *h);
55 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
57 static const uint8_t rem6[QP_MAX_NUM + 1] = {
58 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
59 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
60 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
61 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
65 static const uint8_t div6[QP_MAX_NUM + 1] = {
66 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
67 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
68 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
69 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
73 static const uint8_t field_scan[16+1] = {
74 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
75 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
76 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
77 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
80 static const uint8_t field_scan8x8[64+1] = {
81 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
82 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
83 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
84 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
85 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
86 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
87 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
88 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
89 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
90 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
91 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
92 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
93 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
94 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
95 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
96 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
99 static const uint8_t field_scan8x8_cavlc[64+1] = {
100 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
101 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
102 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
103 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
104 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
105 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
106 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
107 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
108 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
109 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
110 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
111 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
112 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
113 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
114 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
115 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
118 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
119 static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
120 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
121 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
122 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
123 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
124 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
125 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
126 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
127 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
128 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
129 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
130 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
131 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
132 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
133 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
134 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
135 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
138 static const uint8_t dequant4_coeff_init[6][3] = {
147 static const uint8_t dequant8_coeff_init_scan[16] = {
148 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
151 static const uint8_t dequant8_coeff_init[6][6] = {
152 { 20, 18, 32, 19, 25, 24 },
153 { 22, 19, 35, 21, 28, 26 },
154 { 26, 23, 42, 24, 33, 31 },
155 { 28, 25, 45, 26, 35, 33 },
156 { 32, 28, 51, 30, 40, 38 },
157 { 36, 32, 58, 34, 46, 43 },
160 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
161 #if CONFIG_H264_DXVA2_HWACCEL
162 AV_PIX_FMT_DXVA2_VLD,
164 #if CONFIG_H264_VAAPI_HWACCEL
165 AV_PIX_FMT_VAAPI_VLD,
167 #if CONFIG_H264_VDA_HWACCEL
170 #if CONFIG_H264_VDPAU_HWACCEL
177 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
178 #if CONFIG_H264_DXVA2_HWACCEL
179 AV_PIX_FMT_DXVA2_VLD,
181 #if CONFIG_H264_VAAPI_HWACCEL
182 AV_PIX_FMT_VAAPI_VLD,
184 #if CONFIG_H264_VDA_HWACCEL
187 #if CONFIG_H264_VDPAU_HWACCEL
194 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
196 H264Context *h = avctx->priv_data;
197 return h ? h->sps.num_reorder_frames : 0;
200 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
202 int mb_x, int mb_y, int mb_intra, int mb_skipped)
204 H264Context *h = opaque;
208 h->mb_xy = mb_x + mb_y * h->mb_stride;
209 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
210 av_assert1(ref >= 0);
211 /* FIXME: It is possible albeit uncommon that slice references
212 * differ between slices. We take the easy approach and ignore
213 * it for now. If this turns out to have any relevance in
214 * practice then correct remapping should be added. */
215 if (ref >= h->ref_count[0])
217 if (!h->ref_list[0][ref].f.data[0]) {
218 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
221 if ((h->ref_list[0][ref].reference&3) != 3) {
222 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
225 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
227 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
228 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
229 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
231 h->mb_field_decoding_flag = 0;
232 ff_h264_hl_decode_mb(h);
235 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
237 AVCodecContext *avctx = h->avctx;
238 Picture *cur = &h->cur_pic;
239 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
240 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
241 int vshift = desc->log2_chroma_h;
242 const int field_pic = h->picture_structure != PICT_FRAME;
248 height = FFMIN(height, avctx->height - y);
250 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
253 if (avctx->draw_horiz_band) {
255 int offset[AV_NUM_DATA_POINTERS];
258 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
259 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
266 offset[0] = y * src->linesize[0];
268 offset[2] = (y >> vshift) * src->linesize[1];
269 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
274 avctx->draw_horiz_band(avctx, src, offset,
275 y, h->picture_structure, height);
279 static void unref_picture(H264Context *h, Picture *pic)
281 int off = offsetof(Picture, tf) + sizeof(pic->tf);
287 ff_thread_release_buffer(h->avctx, &pic->tf);
288 av_buffer_unref(&pic->hwaccel_priv_buf);
290 av_buffer_unref(&pic->qscale_table_buf);
291 av_buffer_unref(&pic->mb_type_buf);
292 for (i = 0; i < 2; i++) {
293 av_buffer_unref(&pic->motion_val_buf[i]);
294 av_buffer_unref(&pic->ref_index_buf[i]);
297 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
300 static void release_unused_pictures(H264Context *h, int remove_current)
304 /* release non reference frames */
305 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
306 if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&
307 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
308 unref_picture(h, &h->DPB[i]);
313 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
317 av_assert0(!dst->f.buf[0]);
318 av_assert0(src->f.buf[0]);
322 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
326 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
327 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
328 if (!dst->qscale_table_buf || !dst->mb_type_buf)
330 dst->qscale_table = src->qscale_table;
331 dst->mb_type = src->mb_type;
333 for (i = 0; i < 2; i++) {
334 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
335 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
336 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
338 dst->motion_val[i] = src->motion_val[i];
339 dst->ref_index[i] = src->ref_index[i];
342 if (src->hwaccel_picture_private) {
343 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
344 if (!dst->hwaccel_priv_buf)
346 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
349 for (i = 0; i < 2; i++)
350 dst->field_poc[i] = src->field_poc[i];
352 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
353 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
356 dst->frame_num = src->frame_num;
357 dst->mmco_reset = src->mmco_reset;
358 dst->pic_id = src->pic_id;
359 dst->long_ref = src->long_ref;
360 dst->mbaff = src->mbaff;
361 dst->field_picture = src->field_picture;
362 dst->needs_realloc = src->needs_realloc;
363 dst->reference = src->reference;
364 dst->sync = src->sync;
365 dst->crop = src->crop;
366 dst->crop_left = src->crop_left;
367 dst->crop_top = src->crop_top;
371 unref_picture(h, dst);
375 static int alloc_scratch_buffers(H264Context *h, int linesize)
377 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
379 if (h->bipred_scratchpad)
382 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
383 // edge emu needs blocksize + filter length - 1
384 // (= 21x21 for h264)
385 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
386 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
388 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
389 av_freep(&h->bipred_scratchpad);
390 av_freep(&h->edge_emu_buffer);
391 av_freep(&h->me.scratchpad);
392 return AVERROR(ENOMEM);
395 h->me.temp = h->me.scratchpad;
400 static int init_table_pools(H264Context *h)
402 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
403 const int mb_array_size = h->mb_stride * h->mb_height;
404 const int b4_stride = h->mb_width * 4 + 1;
405 const int b4_array_size = b4_stride * h->mb_height * 4;
407 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
409 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
410 sizeof(uint32_t), av_buffer_allocz);
411 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
412 sizeof(int16_t), av_buffer_allocz);
413 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
415 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
416 !h->ref_index_pool) {
417 av_buffer_pool_uninit(&h->qscale_table_pool);
418 av_buffer_pool_uninit(&h->mb_type_pool);
419 av_buffer_pool_uninit(&h->motion_val_pool);
420 av_buffer_pool_uninit(&h->ref_index_pool);
421 return AVERROR(ENOMEM);
427 static int alloc_picture(H264Context *h, Picture *pic)
431 av_assert0(!pic->f.data[0]);
434 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
435 AV_GET_BUFFER_FLAG_REF : 0);
439 h->linesize = pic->f.linesize[0];
440 h->uvlinesize = pic->f.linesize[1];
441 pic->crop = h->sps.crop;
442 pic->crop_top = h->sps.crop_top;
443 pic->crop_left= h->sps.crop_left;
445 if (h->avctx->hwaccel) {
446 const AVHWAccel *hwaccel = h->avctx->hwaccel;
447 av_assert0(!pic->hwaccel_picture_private);
448 if (hwaccel->priv_data_size) {
449 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
450 if (!pic->hwaccel_priv_buf)
451 return AVERROR(ENOMEM);
452 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
456 if (!h->qscale_table_pool) {
457 ret = init_table_pools(h);
462 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
463 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
464 if (!pic->qscale_table_buf || !pic->mb_type_buf)
467 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
468 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
470 for (i = 0; i < 2; i++) {
471 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
472 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
473 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
476 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
477 pic->ref_index[i] = pic->ref_index_buf[i]->data;
482 unref_picture(h, pic);
483 return (ret < 0) ? ret : AVERROR(ENOMEM);
486 static inline int pic_is_unused(H264Context *h, Picture *pic)
488 if (pic->f.data[0] == NULL)
490 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
495 static int find_unused_picture(H264Context *h)
499 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
500 if (pic_is_unused(h, &h->DPB[i]))
503 if (i == MAX_PICTURE_COUNT)
504 return AVERROR_INVALIDDATA;
506 if (h->DPB[i].needs_realloc) {
507 h->DPB[i].needs_realloc = 0;
508 unref_picture(h, &h->DPB[i]);
515 * Check if the top & left blocks are available if needed and
516 * change the dc mode so it only uses the available blocks.
518 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
520 static const int8_t top[12] = {
521 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
523 static const int8_t left[12] = {
524 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
528 if (!(h->top_samples_available & 0x8000)) {
529 for (i = 0; i < 4; i++) {
530 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
532 av_log(h->avctx, AV_LOG_ERROR,
533 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
534 status, h->mb_x, h->mb_y);
535 return AVERROR_INVALIDDATA;
537 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
542 if ((h->left_samples_available & 0x8888) != 0x8888) {
543 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
544 for (i = 0; i < 4; i++)
545 if (!(h->left_samples_available & mask[i])) {
546 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
548 av_log(h->avctx, AV_LOG_ERROR,
549 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
550 status, h->mb_x, h->mb_y);
551 return AVERROR_INVALIDDATA;
553 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
559 } // FIXME cleanup like ff_h264_check_intra_pred_mode
562 * Check if the top & left blocks are available if needed and
563 * change the dc mode so it only uses the available blocks.
565 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
567 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
568 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
571 av_log(h->avctx, AV_LOG_ERROR,
572 "out of range intra chroma pred mode at %d %d\n",
574 return AVERROR_INVALIDDATA;
577 if (!(h->top_samples_available & 0x8000)) {
580 av_log(h->avctx, AV_LOG_ERROR,
581 "top block unavailable for requested intra mode at %d %d\n",
583 return AVERROR_INVALIDDATA;
587 if ((h->left_samples_available & 0x8080) != 0x8080) {
589 if (is_chroma && (h->left_samples_available & 0x8080)) {
590 // mad cow disease mode, aka MBAFF + constrained_intra_pred
591 mode = ALZHEIMER_DC_L0T_PRED8x8 +
592 (!(h->left_samples_available & 0x8000)) +
593 2 * (mode == DC_128_PRED8x8);
596 av_log(h->avctx, AV_LOG_ERROR,
597 "left block unavailable for requested intra mode at %d %d\n",
599 return AVERROR_INVALIDDATA;
606 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
607 int *dst_length, int *consumed, int length)
613 // src[0]&0x80; // forbidden bit
614 h->nal_ref_idc = src[0] >> 5;
615 h->nal_unit_type = src[0] & 0x1F;
620 #define STARTCODE_TEST \
621 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
622 if (src[i + 2] != 3) { \
623 /* startcode, so we must be past the end */ \
629 #if HAVE_FAST_UNALIGNED
630 #define FIND_FIRST_ZERO \
631 if (i > 0 && !src[i]) \
637 for (i = 0; i + 1 < length; i += 9) {
638 if (!((~AV_RN64A(src + i) &
639 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
640 0x8000800080008080ULL))
647 for (i = 0; i + 1 < length; i += 5) {
648 if (!((~AV_RN32A(src + i) &
649 (AV_RN32A(src + i) - 0x01000101U)) &
658 for (i = 0; i + 1 < length; i += 2) {
661 if (i > 0 && src[i - 1] == 0)
667 // use second escape buffer for inter data
668 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
670 si = h->rbsp_buffer_size[bufidx];
671 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
672 dst = h->rbsp_buffer[bufidx];
677 if(i>=length-1){ //no escaped 0
679 *consumed= length+1; //+1 for the header
680 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
683 memcpy(dst, src, length);
690 while (si + 2 < length) {
691 // remove escapes (very rare 1:2^22)
692 if (src[si + 2] > 3) {
693 dst[di++] = src[si++];
694 dst[di++] = src[si++];
695 } else if (src[si] == 0 && src[si + 1] == 0) {
696 if (src[si + 2] == 3) { // escape
701 } else // next start code
705 dst[di++] = src[si++];
708 dst[di++] = src[si++];
711 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
714 *consumed = si + 1; // +1 for the header
715 /* FIXME store exact number of bits in the getbitcontext
716 * (it is needed for decoding) */
721 * Identify the exact end of the bitstream
722 * @return the length of the trailing, or 0 if damaged
724 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
729 tprintf(h->avctx, "rbsp trailing %X\n", v);
731 for (r = 1; r < 9; r++) {
739 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
740 int height, int y_offset, int list)
742 int raw_my = h->mv_cache[list][scan8[n]][1];
743 int filter_height_down = (raw_my & 3) ? 3 : 0;
744 int full_my = (raw_my >> 2) + y_offset;
745 int bottom = full_my + filter_height_down + height;
747 av_assert2(height >= 0);
749 return FFMAX(0, bottom);
752 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
753 int height, int y_offset, int list0,
754 int list1, int *nrefs)
758 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
761 int ref_n = h->ref_cache[0][scan8[n]];
762 Picture *ref = &h->ref_list[0][ref_n];
764 // Error resilience puts the current picture in the ref list.
765 // Don't try to wait on these as it will cause a deadlock.
766 // Fields can wait on each other, though.
767 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
768 (ref->reference & 3) != h->picture_structure) {
769 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
770 if (refs[0][ref_n] < 0)
772 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
777 int ref_n = h->ref_cache[1][scan8[n]];
778 Picture *ref = &h->ref_list[1][ref_n];
780 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
781 (ref->reference & 3) != h->picture_structure) {
782 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
783 if (refs[1][ref_n] < 0)
785 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
791 * Wait until all reference frames are available for MC operations.
793 * @param h the H264 context
795 static void await_references(H264Context *h)
797 const int mb_xy = h->mb_xy;
798 const int mb_type = h->cur_pic.mb_type[mb_xy];
800 int nrefs[2] = { 0 };
803 memset(refs, -1, sizeof(refs));
805 if (IS_16X16(mb_type)) {
806 get_lowest_part_y(h, refs, 0, 16, 0,
807 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
808 } else if (IS_16X8(mb_type)) {
809 get_lowest_part_y(h, refs, 0, 8, 0,
810 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
811 get_lowest_part_y(h, refs, 8, 8, 8,
812 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
813 } else if (IS_8X16(mb_type)) {
814 get_lowest_part_y(h, refs, 0, 16, 0,
815 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
816 get_lowest_part_y(h, refs, 4, 16, 0,
817 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
821 av_assert2(IS_8X8(mb_type));
823 for (i = 0; i < 4; i++) {
824 const int sub_mb_type = h->sub_mb_type[i];
826 int y_offset = (i & 2) << 2;
828 if (IS_SUB_8X8(sub_mb_type)) {
829 get_lowest_part_y(h, refs, n, 8, y_offset,
830 IS_DIR(sub_mb_type, 0, 0),
831 IS_DIR(sub_mb_type, 0, 1),
833 } else if (IS_SUB_8X4(sub_mb_type)) {
834 get_lowest_part_y(h, refs, n, 4, y_offset,
835 IS_DIR(sub_mb_type, 0, 0),
836 IS_DIR(sub_mb_type, 0, 1),
838 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
839 IS_DIR(sub_mb_type, 0, 0),
840 IS_DIR(sub_mb_type, 0, 1),
842 } else if (IS_SUB_4X8(sub_mb_type)) {
843 get_lowest_part_y(h, refs, n, 8, y_offset,
844 IS_DIR(sub_mb_type, 0, 0),
845 IS_DIR(sub_mb_type, 0, 1),
847 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
848 IS_DIR(sub_mb_type, 0, 0),
849 IS_DIR(sub_mb_type, 0, 1),
853 av_assert2(IS_SUB_4X4(sub_mb_type));
854 for (j = 0; j < 4; j++) {
855 int sub_y_offset = y_offset + 2 * (j & 2);
856 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
857 IS_DIR(sub_mb_type, 0, 0),
858 IS_DIR(sub_mb_type, 0, 1),
865 for (list = h->list_count - 1; list >= 0; list--)
866 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
867 int row = refs[list][ref];
869 Picture *ref_pic = &h->ref_list[list][ref];
870 int ref_field = ref_pic->reference - 1;
871 int ref_field_picture = ref_pic->field_picture;
872 int pic_height = 16 * h->mb_height >> ref_field_picture;
877 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
878 ff_thread_await_progress(&ref_pic->tf,
879 FFMIN((row >> 1) - !(row & 1),
882 ff_thread_await_progress(&ref_pic->tf,
883 FFMIN((row >> 1), pic_height - 1),
885 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
886 ff_thread_await_progress(&ref_pic->tf,
887 FFMIN(row * 2 + ref_field,
890 } else if (FIELD_PICTURE(h)) {
891 ff_thread_await_progress(&ref_pic->tf,
892 FFMIN(row, pic_height - 1),
895 ff_thread_await_progress(&ref_pic->tf,
896 FFMIN(row, pic_height - 1),
903 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
904 int n, int square, int height,
906 uint8_t *dest_y, uint8_t *dest_cb,
908 int src_x_offset, int src_y_offset,
909 qpel_mc_func *qpix_op,
910 h264_chroma_mc_func chroma_op,
911 int pixel_shift, int chroma_idc)
913 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
914 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
915 const int luma_xy = (mx & 3) + ((my & 3) << 2);
916 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
917 uint8_t *src_y = pic->f.data[0] + offset;
918 uint8_t *src_cb, *src_cr;
920 int extra_height = 0;
922 const int full_mx = mx >> 2;
923 const int full_my = my >> 2;
924 const int pic_width = 16 * h->mb_width;
925 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
933 if (full_mx < 0 - extra_width ||
934 full_my < 0 - extra_height ||
935 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
936 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
937 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize,
938 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
940 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
941 full_my - 2, pic_width, pic_height);
942 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
946 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
948 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
950 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
953 if (chroma_idc == 3 /* yuv444 */) {
954 src_cb = pic->f.data[1] + offset;
956 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize,
957 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
959 16 + 5, 16 + 5 /*FIXME*/,
960 full_mx - 2, full_my - 2,
961 pic_width, pic_height);
962 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
964 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
966 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
968 src_cr = pic->f.data[2] + offset;
970 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize,
971 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
973 16 + 5, 16 + 5 /*FIXME*/,
974 full_mx - 2, full_my - 2,
975 pic_width, pic_height);
976 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
978 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
980 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
984 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
985 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
986 // chroma offset when predicting from a field of opposite parity
987 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
988 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
991 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
992 (my >> ysh) * h->mb_uvlinesize;
993 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
994 (my >> ysh) * h->mb_uvlinesize;
997 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_uvlinesize, src_cb, h->mb_uvlinesize,
998 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
999 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1000 src_cb = h->edge_emu_buffer;
1002 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
1003 height >> (chroma_idc == 1 /* yuv420 */),
1004 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1007 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_uvlinesize, src_cr, h->mb_uvlinesize,
1008 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1009 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1010 src_cr = h->edge_emu_buffer;
1012 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
1013 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1016 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
1017 int height, int delta,
1018 uint8_t *dest_y, uint8_t *dest_cb,
1020 int x_offset, int y_offset,
1021 qpel_mc_func *qpix_put,
1022 h264_chroma_mc_func chroma_put,
1023 qpel_mc_func *qpix_avg,
1024 h264_chroma_mc_func chroma_avg,
1025 int list0, int list1,
1026 int pixel_shift, int chroma_idc)
1028 qpel_mc_func *qpix_op = qpix_put;
1029 h264_chroma_mc_func chroma_op = chroma_put;
1031 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1032 if (chroma_idc == 3 /* yuv444 */) {
1033 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1034 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1035 } else if (chroma_idc == 2 /* yuv422 */) {
1036 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1037 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1038 } else { /* yuv420 */
1039 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1040 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1042 x_offset += 8 * h->mb_x;
1043 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1046 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1047 mc_dir_part(h, ref, n, square, height, delta, 0,
1048 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1049 qpix_op, chroma_op, pixel_shift, chroma_idc);
1052 chroma_op = chroma_avg;
1056 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1057 mc_dir_part(h, ref, n, square, height, delta, 1,
1058 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1059 qpix_op, chroma_op, pixel_shift, chroma_idc);
1063 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1064 int height, int delta,
1065 uint8_t *dest_y, uint8_t *dest_cb,
1067 int x_offset, int y_offset,
1068 qpel_mc_func *qpix_put,
1069 h264_chroma_mc_func chroma_put,
1070 h264_weight_func luma_weight_op,
1071 h264_weight_func chroma_weight_op,
1072 h264_biweight_func luma_weight_avg,
1073 h264_biweight_func chroma_weight_avg,
1074 int list0, int list1,
1075 int pixel_shift, int chroma_idc)
1079 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1080 if (chroma_idc == 3 /* yuv444 */) {
1081 chroma_height = height;
1082 chroma_weight_avg = luma_weight_avg;
1083 chroma_weight_op = luma_weight_op;
1084 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1085 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1086 } else if (chroma_idc == 2 /* yuv422 */) {
1087 chroma_height = height;
1088 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1089 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1090 } else { /* yuv420 */
1091 chroma_height = height >> 1;
1092 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1093 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1095 x_offset += 8 * h->mb_x;
1096 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1098 if (list0 && list1) {
1099 /* don't optimize for luma-only case, since B-frames usually
1100 * use implicit weights => chroma too. */
1101 uint8_t *tmp_cb = h->bipred_scratchpad;
1102 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1103 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1104 int refn0 = h->ref_cache[0][scan8[n]];
1105 int refn1 = h->ref_cache[1][scan8[n]];
1107 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1108 dest_y, dest_cb, dest_cr,
1109 x_offset, y_offset, qpix_put, chroma_put,
1110 pixel_shift, chroma_idc);
1111 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1112 tmp_y, tmp_cb, tmp_cr,
1113 x_offset, y_offset, qpix_put, chroma_put,
1114 pixel_shift, chroma_idc);
1116 if (h->use_weight == 2) {
1117 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1118 int weight1 = 64 - weight0;
1119 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1120 height, 5, weight0, weight1, 0);
1121 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1122 chroma_height, 5, weight0, weight1, 0);
1123 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1124 chroma_height, 5, weight0, weight1, 0);
1126 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1127 h->luma_log2_weight_denom,
1128 h->luma_weight[refn0][0][0],
1129 h->luma_weight[refn1][1][0],
1130 h->luma_weight[refn0][0][1] +
1131 h->luma_weight[refn1][1][1]);
1132 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1133 h->chroma_log2_weight_denom,
1134 h->chroma_weight[refn0][0][0][0],
1135 h->chroma_weight[refn1][1][0][0],
1136 h->chroma_weight[refn0][0][0][1] +
1137 h->chroma_weight[refn1][1][0][1]);
1138 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1139 h->chroma_log2_weight_denom,
1140 h->chroma_weight[refn0][0][1][0],
1141 h->chroma_weight[refn1][1][1][0],
1142 h->chroma_weight[refn0][0][1][1] +
1143 h->chroma_weight[refn1][1][1][1]);
1146 int list = list1 ? 1 : 0;
1147 int refn = h->ref_cache[list][scan8[n]];
1148 Picture *ref = &h->ref_list[list][refn];
1149 mc_dir_part(h, ref, n, square, height, delta, list,
1150 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1151 qpix_put, chroma_put, pixel_shift, chroma_idc);
1153 luma_weight_op(dest_y, h->mb_linesize, height,
1154 h->luma_log2_weight_denom,
1155 h->luma_weight[refn][list][0],
1156 h->luma_weight[refn][list][1]);
1157 if (h->use_weight_chroma) {
1158 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1159 h->chroma_log2_weight_denom,
1160 h->chroma_weight[refn][list][0][0],
1161 h->chroma_weight[refn][list][0][1]);
1162 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1163 h->chroma_log2_weight_denom,
1164 h->chroma_weight[refn][list][1][0],
1165 h->chroma_weight[refn][list][1][1]);
1170 static av_always_inline void prefetch_motion(H264Context *h, int list,
1171 int pixel_shift, int chroma_idc)
1173 /* fetch pixels for estimated mv 4 macroblocks ahead
1174 * optimized for 64byte cache lines */
1175 const int refn = h->ref_cache[list][scan8[0]];
1177 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1178 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1179 uint8_t **src = h->ref_list[list][refn].f.data;
1180 int off = (mx << pixel_shift) +
1181 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1182 (64 << pixel_shift);
1183 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1184 if (chroma_idc == 3 /* yuv444 */) {
1185 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1186 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1188 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
1189 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1194 static void free_tables(H264Context *h, int free_rbsp)
1199 av_freep(&h->intra4x4_pred_mode);
1200 av_freep(&h->chroma_pred_mode_table);
1201 av_freep(&h->cbp_table);
1202 av_freep(&h->mvd_table[0]);
1203 av_freep(&h->mvd_table[1]);
1204 av_freep(&h->direct_table);
1205 av_freep(&h->non_zero_count);
1206 av_freep(&h->slice_table_base);
1207 h->slice_table = NULL;
1208 av_freep(&h->list_counts);
1210 av_freep(&h->mb2b_xy);
1211 av_freep(&h->mb2br_xy);
1213 for (i = 0; i < 3; i++)
1214 av_freep(&h->visualization_buffer[i]);
1216 av_buffer_pool_uninit(&h->qscale_table_pool);
1217 av_buffer_pool_uninit(&h->mb_type_pool);
1218 av_buffer_pool_uninit(&h->motion_val_pool);
1219 av_buffer_pool_uninit(&h->ref_index_pool);
1221 if (free_rbsp && h->DPB) {
1222 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1223 unref_picture(h, &h->DPB[i]);
1225 } else if (h->DPB) {
1226 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1227 h->DPB[i].needs_realloc = 1;
1230 h->cur_pic_ptr = NULL;
1232 for (i = 0; i < MAX_THREADS; i++) {
1233 hx = h->thread_context[i];
1236 av_freep(&hx->top_borders[1]);
1237 av_freep(&hx->top_borders[0]);
1238 av_freep(&hx->bipred_scratchpad);
1239 av_freep(&hx->edge_emu_buffer);
1240 av_freep(&hx->dc_val_base);
1241 av_freep(&hx->me.scratchpad);
1242 av_freep(&hx->er.mb_index2xy);
1243 av_freep(&hx->er.error_status_table);
1244 av_freep(&hx->er.er_temp_buffer);
1245 av_freep(&hx->er.mbintra_table);
1246 av_freep(&hx->er.mbskip_table);
1249 av_freep(&hx->rbsp_buffer[1]);
1250 av_freep(&hx->rbsp_buffer[0]);
1251 hx->rbsp_buffer_size[0] = 0;
1252 hx->rbsp_buffer_size[1] = 0;
1255 av_freep(&h->thread_context[i]);
1259 static void init_dequant8_coeff_table(H264Context *h)
1262 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1264 for (i = 0; i < 6; i++) {
1265 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1266 for (j = 0; j < i; j++)
1267 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1268 64 * sizeof(uint8_t))) {
1269 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1275 for (q = 0; q < max_qp + 1; q++) {
1276 int shift = div6[q];
1278 for (x = 0; x < 64; x++)
1279 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1280 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1281 h->pps.scaling_matrix8[i][x]) << shift;
1286 static void init_dequant4_coeff_table(H264Context *h)
1289 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1290 for (i = 0; i < 6; i++) {
1291 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1292 for (j = 0; j < i; j++)
1293 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1294 16 * sizeof(uint8_t))) {
1295 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1301 for (q = 0; q < max_qp + 1; q++) {
1302 int shift = div6[q] + 2;
1304 for (x = 0; x < 16; x++)
1305 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1306 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1307 h->pps.scaling_matrix4[i][x]) << shift;
1312 static void init_dequant_tables(H264Context *h)
1315 init_dequant4_coeff_table(h);
1316 if (h->pps.transform_8x8_mode)
1317 init_dequant8_coeff_table(h);
1318 if (h->sps.transform_bypass) {
1319 for (i = 0; i < 6; i++)
1320 for (x = 0; x < 16; x++)
1321 h->dequant4_coeff[i][0][x] = 1 << 6;
1322 if (h->pps.transform_8x8_mode)
1323 for (i = 0; i < 6; i++)
1324 for (x = 0; x < 64; x++)
1325 h->dequant8_coeff[i][0][x] = 1 << 6;
1329 int ff_h264_alloc_tables(H264Context *h)
1331 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1332 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1335 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1336 row_mb_num * 8 * sizeof(uint8_t), fail)
1337 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1338 big_mb_num * 48 * sizeof(uint8_t), fail)
1339 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1340 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1341 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1342 big_mb_num * sizeof(uint16_t), fail)
1343 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1344 big_mb_num * sizeof(uint8_t), fail)
1345 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1346 16 * row_mb_num * sizeof(uint8_t), fail);
1347 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1348 16 * row_mb_num * sizeof(uint8_t), fail);
1349 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1350 4 * big_mb_num * sizeof(uint8_t), fail);
1351 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1352 big_mb_num * sizeof(uint8_t), fail)
1354 memset(h->slice_table_base, -1,
1355 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1356 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1358 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1359 big_mb_num * sizeof(uint32_t), fail);
1360 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1361 big_mb_num * sizeof(uint32_t), fail);
1362 for (y = 0; y < h->mb_height; y++)
1363 for (x = 0; x < h->mb_width; x++) {
1364 const int mb_xy = x + y * h->mb_stride;
1365 const int b_xy = 4 * x + 4 * y * h->b_stride;
1367 h->mb2b_xy[mb_xy] = b_xy;
1368 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1371 if (!h->dequant4_coeff[0])
1372 init_dequant_tables(h);
1375 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1377 return AVERROR(ENOMEM);
1378 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1379 avcodec_get_frame_defaults(&h->DPB[i].f);
1380 avcodec_get_frame_defaults(&h->cur_pic.f);
1387 return AVERROR(ENOMEM);
1391 * Mimic alloc_tables(), but for every context thread.
1393 static void clone_tables(H264Context *dst, H264Context *src, int i)
1395 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1396 dst->non_zero_count = src->non_zero_count;
1397 dst->slice_table = src->slice_table;
1398 dst->cbp_table = src->cbp_table;
1399 dst->mb2b_xy = src->mb2b_xy;
1400 dst->mb2br_xy = src->mb2br_xy;
1401 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1402 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1403 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1404 dst->direct_table = src->direct_table;
1405 dst->list_counts = src->list_counts;
1406 dst->DPB = src->DPB;
1407 dst->cur_pic_ptr = src->cur_pic_ptr;
1408 dst->cur_pic = src->cur_pic;
1409 dst->bipred_scratchpad = NULL;
1410 dst->edge_emu_buffer = NULL;
1411 dst->me.scratchpad = NULL;
1412 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1413 src->sps.chroma_format_idc);
1418 * Allocate buffers which are not shared amongst multiple threads.
1420 static int context_init(H264Context *h)
1422 ERContext *er = &h->er;
1423 int mb_array_size = h->mb_height * h->mb_stride;
1424 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1425 int c_size = h->mb_stride * (h->mb_height + 1);
1426 int yc_size = y_size + 2 * c_size;
1429 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1430 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1431 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1432 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1434 h->ref_cache[0][scan8[5] + 1] =
1435 h->ref_cache[0][scan8[7] + 1] =
1436 h->ref_cache[0][scan8[13] + 1] =
1437 h->ref_cache[1][scan8[5] + 1] =
1438 h->ref_cache[1][scan8[7] + 1] =
1439 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1441 if (CONFIG_ERROR_RESILIENCE) {
1443 er->avctx = h->avctx;
1445 er->decode_mb = h264_er_decode_mb;
1447 er->quarter_sample = 1;
1449 er->mb_num = h->mb_num;
1450 er->mb_width = h->mb_width;
1451 er->mb_height = h->mb_height;
1452 er->mb_stride = h->mb_stride;
1453 er->b8_stride = h->mb_width * 2 + 1;
1455 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1456 fail); // error ressilience code looks cleaner with this
1457 for (y = 0; y < h->mb_height; y++)
1458 for (x = 0; x < h->mb_width; x++)
1459 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1461 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1462 h->mb_stride + h->mb_width;
1464 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1465 mb_array_size * sizeof(uint8_t), fail);
1467 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1468 memset(er->mbintra_table, 1, mb_array_size);
1470 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1472 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1475 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1476 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1477 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1478 er->dc_val[2] = er->dc_val[1] + c_size;
1479 for (i = 0; i < yc_size; i++)
1480 h->dc_val_base[i] = 1024;
1486 return AVERROR(ENOMEM); // free_tables will clean up for us
1489 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1490 int parse_extradata);
1492 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1494 AVCodecContext *avctx = h->avctx;
1497 if (!buf || size <= 0)
1501 int i, cnt, nalsize;
1502 const unsigned char *p = buf;
1507 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1508 return AVERROR_INVALIDDATA;
1510 /* sps and pps in the avcC always have length coded with 2 bytes,
1511 * so put a fake nal_length_size = 2 while parsing them */
1512 h->nal_length_size = 2;
1513 // Decode sps from avcC
1514 cnt = *(p + 5) & 0x1f; // Number of sps
1516 for (i = 0; i < cnt; i++) {
1517 nalsize = AV_RB16(p) + 2;
1518 if(nalsize > size - (p-buf))
1519 return AVERROR_INVALIDDATA;
1520 ret = decode_nal_units(h, p, nalsize, 1);
1522 av_log(avctx, AV_LOG_ERROR,
1523 "Decoding sps %d from avcC failed\n", i);
1528 // Decode pps from avcC
1529 cnt = *(p++); // Number of pps
1530 for (i = 0; i < cnt; i++) {
1531 nalsize = AV_RB16(p) + 2;
1532 if(nalsize > size - (p-buf))
1533 return AVERROR_INVALIDDATA;
1534 ret = decode_nal_units(h, p, nalsize, 1);
1536 av_log(avctx, AV_LOG_ERROR,
1537 "Decoding pps %d from avcC failed\n", i);
1542 // Now store right nal length size, that will be used to parse all other nals
1543 h->nal_length_size = (buf[4] & 0x03) + 1;
1546 ret = decode_nal_units(h, buf, size, 1);
1553 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1555 H264Context *h = avctx->priv_data;
1561 h->bit_depth_luma = 8;
1562 h->chroma_format_idc = 1;
1564 h->avctx->bits_per_raw_sample = 8;
1565 h->cur_chroma_format_idc = 1;
1567 ff_h264dsp_init(&h->h264dsp, 8, 1);
1568 av_assert0(h->sps.bit_depth_chroma == 0);
1569 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1570 ff_h264qpel_init(&h->h264qpel, 8);
1571 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1573 h->dequant_coeff_pps = -1;
1574 h->current_sps_id = -1;
1576 /* needed so that IDCT permutation is known early */
1577 if (CONFIG_ERROR_RESILIENCE)
1578 ff_dsputil_init(&h->dsp, h->avctx);
1579 ff_videodsp_init(&h->vdsp, 8);
1581 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1582 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1584 h->picture_structure = PICT_FRAME;
1585 h->slice_context_count = 1;
1586 h->workaround_bugs = avctx->workaround_bugs;
1587 h->flags = avctx->flags;
1590 // s->decode_mb = ff_h263_decode_mb;
1591 if (!avctx->has_b_frames)
1594 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1596 ff_h264_decode_init_vlc();
1598 ff_init_cabac_states();
1601 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1603 h->thread_context[0] = h;
1604 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1605 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1606 h->last_pocs[i] = INT_MIN;
1607 h->prev_poc_msb = 1 << 16;
1608 h->prev_frame_num = -1;
1610 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
1611 ff_h264_reset_sei(h);
1612 if (avctx->codec_id == AV_CODEC_ID_H264) {
1613 if (avctx->ticks_per_frame == 1) {
1614 if(h->avctx->time_base.den < INT_MAX/2) {
1615 h->avctx->time_base.den *= 2;
1617 h->avctx->time_base.num /= 2;
1619 avctx->ticks_per_frame = 2;
1622 if (avctx->extradata_size > 0 && avctx->extradata) {
1623 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
1625 ff_h264_free_context(h);
1630 if (h->sps.bitstream_restriction_flag &&
1631 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1632 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1636 avctx->internal->allocate_progress = 1;
1643 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1644 #undef REBASE_PICTURE
1645 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1646 ((pic && pic >= old_ctx->DPB && \
1647 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1648 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1650 static void copy_picture_range(Picture **to, Picture **from, int count,
1651 H264Context *new_base,
1652 H264Context *old_base)
1656 for (i = 0; i < count; i++) {
1657 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1658 IN_RANGE(from[i], old_base->DPB,
1659 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1661 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1665 static void copy_parameter_set(void **to, void **from, int count, int size)
1669 for (i = 0; i < count; i++) {
1670 if (to[i] && !from[i])
1672 else if (from[i] && !to[i])
1673 to[i] = av_malloc(size);
1676 memcpy(to[i], from[i], size);
1680 static int decode_init_thread_copy(AVCodecContext *avctx)
1682 H264Context *h = avctx->priv_data;
1684 if (!avctx->internal->is_copy)
1686 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1687 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1689 h->rbsp_buffer[0] = NULL;
1690 h->rbsp_buffer[1] = NULL;
1691 h->rbsp_buffer_size[0] = 0;
1692 h->rbsp_buffer_size[1] = 0;
1693 h->context_initialized = 0;
1698 #define copy_fields(to, from, start_field, end_field) \
1699 memcpy(&to->start_field, &from->start_field, \
1700 (char *)&to->end_field - (char *)&to->start_field)
1702 static int h264_slice_header_init(H264Context *, int);
1704 static int h264_set_parameter_from_sps(H264Context *h);
1706 static int decode_update_thread_context(AVCodecContext *dst,
1707 const AVCodecContext *src)
1709 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1710 int inited = h->context_initialized, err = 0;
1711 int context_reinitialized = 0;
1718 (h->width != h1->width ||
1719 h->height != h1->height ||
1720 h->mb_width != h1->mb_width ||
1721 h->mb_height != h1->mb_height ||
1722 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1723 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1724 h->sps.colorspace != h1->sps.colorspace)) {
1726 /* set bits_per_raw_sample to the previous value. the check for changed
1727 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1728 * the current value */
1729 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1731 av_freep(&h->bipred_scratchpad);
1733 h->width = h1->width;
1734 h->height = h1->height;
1735 h->mb_height = h1->mb_height;
1736 h->mb_width = h1->mb_width;
1737 h->mb_num = h1->mb_num;
1738 h->mb_stride = h1->mb_stride;
1739 h->b_stride = h1->b_stride;
1741 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1742 MAX_SPS_COUNT, sizeof(SPS));
1744 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1745 MAX_PPS_COUNT, sizeof(PPS));
1748 if ((err = h264_slice_header_init(h, 1)) < 0) {
1749 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1752 context_reinitialized = 1;
1755 h264_set_parameter_from_sps(h);
1756 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1757 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1760 /* update linesize on resize for h264. The h264 decoder doesn't
1761 * necessarily call ff_MPV_frame_start in the new thread */
1762 h->linesize = h1->linesize;
1763 h->uvlinesize = h1->uvlinesize;
1765 /* copy block_offset since frame_start may not be called */
1766 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1769 for (i = 0; i < MAX_SPS_COUNT; i++)
1770 av_freep(h->sps_buffers + i);
1772 for (i = 0; i < MAX_PPS_COUNT; i++)
1773 av_freep(h->pps_buffers + i);
1775 av_freep(&h->rbsp_buffer[0]);
1776 av_freep(&h->rbsp_buffer[1]);
1777 memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1778 memcpy(&h->cabac, &h1->cabac,
1779 sizeof(H264Context) - offsetof(H264Context, cabac));
1780 av_assert0((void*)&h->cabac == &h->mb_padding + 1);
1782 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1783 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1785 memset(&h->er, 0, sizeof(h->er));
1786 memset(&h->me, 0, sizeof(h->me));
1787 memset(&h->mb, 0, sizeof(h->mb));
1788 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1789 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1793 h->qscale_table_pool = NULL;
1794 h->mb_type_pool = NULL;
1795 h->ref_index_pool = NULL;
1796 h->motion_val_pool = NULL;
1797 for (i = 0; i < 2; i++) {
1798 h->rbsp_buffer[i] = NULL;
1799 h->rbsp_buffer_size[i] = 0;
1802 if (h1->context_initialized) {
1803 h->context_initialized = 0;
1805 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1806 avcodec_get_frame_defaults(&h->cur_pic.f);
1807 h->cur_pic.tf.f = &h->cur_pic.f;
1809 ret = ff_h264_alloc_tables(h);
1811 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1814 ret = context_init(h);
1816 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1821 h->bipred_scratchpad = NULL;
1822 h->edge_emu_buffer = NULL;
1824 h->thread_context[0] = h;
1825 h->context_initialized = h1->context_initialized;
1828 h->avctx->coded_height = h1->avctx->coded_height;
1829 h->avctx->coded_width = h1->avctx->coded_width;
1830 h->avctx->width = h1->avctx->width;
1831 h->avctx->height = h1->avctx->height;
1832 h->coded_picture_number = h1->coded_picture_number;
1833 h->first_field = h1->first_field;
1834 h->picture_structure = h1->picture_structure;
1835 h->qscale = h1->qscale;
1836 h->droppable = h1->droppable;
1837 h->data_partitioning = h1->data_partitioning;
1838 h->low_delay = h1->low_delay;
1840 for (i = 0; h->DPB && i < MAX_PICTURE_COUNT; i++) {
1841 unref_picture(h, &h->DPB[i]);
1842 if (h1->DPB[i].f.data[0] &&
1843 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1847 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1848 unref_picture(h, &h->cur_pic);
1849 if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1852 h->workaround_bugs = h1->workaround_bugs;
1853 h->low_delay = h1->low_delay;
1854 h->droppable = h1->droppable;
1856 // extradata/NAL handling
1857 h->is_avc = h1->is_avc;
1860 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1861 MAX_SPS_COUNT, sizeof(SPS));
1863 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1864 MAX_PPS_COUNT, sizeof(PPS));
1867 // Dequantization matrices
1868 // FIXME these are big - can they be only copied when PPS changes?
1869 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1871 for (i = 0; i < 6; i++)
1872 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1873 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1875 for (i = 0; i < 6; i++)
1876 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1877 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1879 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1882 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1885 copy_fields(h, h1, short_ref, cabac_init_idc);
1887 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1888 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1889 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1890 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1894 if (context_reinitialized)
1895 h264_set_parameter_from_sps(h);
1897 if (!h->cur_pic_ptr)
1900 if (!h->droppable) {
1901 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1902 h->prev_poc_msb = h->poc_msb;
1903 h->prev_poc_lsb = h->poc_lsb;
1905 h->prev_frame_num_offset = h->frame_num_offset;
1906 h->prev_frame_num = h->frame_num;
1907 h->outputed_poc = h->next_outputed_poc;
1912 static int h264_frame_start(H264Context *h)
1916 const int pixel_shift = h->pixel_shift;
1918 1<<(h->sps.bit_depth_luma-1),
1919 1<<(h->sps.bit_depth_chroma-1),
1920 1<<(h->sps.bit_depth_chroma-1),
1924 if (!ff_thread_can_start_frame(h->avctx)) {
1925 av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1929 release_unused_pictures(h, 1);
1930 h->cur_pic_ptr = NULL;
1932 i = find_unused_picture(h);
1934 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1939 pic->reference = h->droppable ? 0 : h->picture_structure;
1940 pic->f.coded_picture_number = h->coded_picture_number++;
1941 pic->field_picture = h->picture_structure != PICT_FRAME;
1944 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1946 * See decode_nal_units().
1948 pic->f.key_frame = 0;
1950 pic->mmco_reset = 0;
1952 if ((ret = alloc_picture(h, pic)) < 0)
1954 if(!h->sync && !h->avctx->hwaccel &&
1955 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1956 avpriv_color_frame(&pic->f, c);
1958 h->cur_pic_ptr = pic;
1959 unref_picture(h, &h->cur_pic);
1960 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1963 if (CONFIG_ERROR_RESILIENCE) {
1964 ff_er_frame_start(&h->er);
1966 h->er.next_pic = NULL;
1969 assert(h->linesize && h->uvlinesize);
1971 for (i = 0; i < 16; i++) {
1972 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1973 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1975 for (i = 0; i < 16; i++) {
1976 h->block_offset[16 + i] =
1977 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1978 h->block_offset[48 + 16 + i] =
1979 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1982 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1983 // h->cur_pic.reference /* || h->contains_intra */ || 1;
1985 /* We mark the current picture as non-reference after allocating it, so
1986 * that if we break out due to an error it can be released automatically
1987 * in the next ff_MPV_frame_start().
1989 h->cur_pic_ptr->reference = 0;
1991 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1993 h->next_output_pic = NULL;
1995 assert(h->cur_pic_ptr->long_ref == 0);
2001 * Run setup operations that must be run after slice header decoding.
2002 * This includes finding the next displayed frame.
2004 * @param h h264 master context
2005 * @param setup_finished enough NALs have been read that we can call
2006 * ff_thread_finish_setup()
2008 static void decode_postinit(H264Context *h, int setup_finished)
2010 Picture *out = h->cur_pic_ptr;
2011 Picture *cur = h->cur_pic_ptr;
2012 int i, pics, out_of_order, out_idx;
2014 h->cur_pic_ptr->f.pict_type = h->pict_type;
2016 if (h->next_output_pic)
2019 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
2020 /* FIXME: if we have two PAFF fields in one packet, we can't start
2021 * the next thread here. If we have one field per packet, we can.
2022 * The check in decode_nal_units() is not good enough to find this
2023 * yet, so we assume the worst for now. */
2024 // if (setup_finished)
2025 // ff_thread_finish_setup(h->avctx);
2029 cur->f.interlaced_frame = 0;
2030 cur->f.repeat_pict = 0;
2032 /* Signal interlacing information externally. */
2033 /* Prioritize picture timing SEI information over used
2034 * decoding process if it exists. */
2036 if (h->sps.pic_struct_present_flag) {
2037 switch (h->sei_pic_struct) {
2038 case SEI_PIC_STRUCT_FRAME:
2040 case SEI_PIC_STRUCT_TOP_FIELD:
2041 case SEI_PIC_STRUCT_BOTTOM_FIELD:
2042 cur->f.interlaced_frame = 1;
2044 case SEI_PIC_STRUCT_TOP_BOTTOM:
2045 case SEI_PIC_STRUCT_BOTTOM_TOP:
2046 if (FIELD_OR_MBAFF_PICTURE(h))
2047 cur->f.interlaced_frame = 1;
2049 // try to flag soft telecine progressive
2050 cur->f.interlaced_frame = h->prev_interlaced_frame;
2052 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
2053 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
2054 /* Signal the possibility of telecined film externally
2055 * (pic_struct 5,6). From these hints, let the applications
2056 * decide if they apply deinterlacing. */
2057 cur->f.repeat_pict = 1;
2059 case SEI_PIC_STRUCT_FRAME_DOUBLING:
2060 cur->f.repeat_pict = 2;
2062 case SEI_PIC_STRUCT_FRAME_TRIPLING:
2063 cur->f.repeat_pict = 4;
2067 if ((h->sei_ct_type & 3) &&
2068 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2069 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2071 /* Derive interlacing flag from used decoding process. */
2072 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2074 h->prev_interlaced_frame = cur->f.interlaced_frame;
2076 if (cur->field_poc[0] != cur->field_poc[1]) {
2077 /* Derive top_field_first from field pocs. */
2078 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2080 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2081 /* Use picture timing SEI information. Even if it is a
2082 * information of a past frame, better than nothing. */
2083 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2084 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2085 cur->f.top_field_first = 1;
2087 cur->f.top_field_first = 0;
2089 /* Most likely progressive */
2090 cur->f.top_field_first = 0;
2094 cur->mmco_reset = h->mmco_reset;
2096 // FIXME do something with unavailable reference frames
2098 /* Sort B-frames into display order */
2100 if (h->sps.bitstream_restriction_flag &&
2101 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2102 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2106 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2107 !h->sps.bitstream_restriction_flag) {
2108 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2112 for (i = 0; 1; i++) {
2113 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2115 h->last_pocs[i-1] = cur->poc;
2118 h->last_pocs[i-1]= h->last_pocs[i];
2121 out_of_order = MAX_DELAYED_PIC_COUNT - i;
2122 if( cur->f.pict_type == AV_PICTURE_TYPE_B
2123 || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
2124 out_of_order = FFMAX(out_of_order, 1);
2125 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2126 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2127 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2128 h->last_pocs[i] = INT_MIN;
2129 h->last_pocs[0] = cur->poc;
2130 cur->mmco_reset = 1;
2131 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2132 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2133 h->avctx->has_b_frames = out_of_order;
2138 while (h->delayed_pic[pics])
2141 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
2143 h->delayed_pic[pics++] = cur;
2144 if (cur->reference == 0)
2145 cur->reference = DELAYED_PIC_REF;
2147 out = h->delayed_pic[0];
2149 for (i = 1; h->delayed_pic[i] &&
2150 !h->delayed_pic[i]->f.key_frame &&
2151 !h->delayed_pic[i]->mmco_reset;
2153 if (h->delayed_pic[i]->poc < out->poc) {
2154 out = h->delayed_pic[i];
2157 if (h->avctx->has_b_frames == 0 &&
2158 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2159 h->next_outputed_poc = INT_MIN;
2160 out_of_order = out->poc < h->next_outputed_poc;
2162 if (out_of_order || pics > h->avctx->has_b_frames) {
2163 out->reference &= ~DELAYED_PIC_REF;
2164 // for frame threading, the owner must be the second field's thread or
2165 // else the first thread can release the picture and reuse it unsafely
2166 for (i = out_idx; h->delayed_pic[i]; i++)
2167 h->delayed_pic[i] = h->delayed_pic[i + 1];
2169 if (!out_of_order && pics > h->avctx->has_b_frames) {
2170 h->next_output_pic = out;
2171 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2172 h->next_outputed_poc = INT_MIN;
2174 h->next_outputed_poc = out->poc;
2176 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2179 if (h->next_output_pic && h->next_output_pic->sync) {
2183 if (setup_finished && !h->avctx->hwaccel)
2184 ff_thread_finish_setup(h->avctx);
2187 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2188 uint8_t *src_cb, uint8_t *src_cr,
2189 int linesize, int uvlinesize,
2192 uint8_t *top_border;
2194 const int pixel_shift = h->pixel_shift;
2195 int chroma444 = CHROMA444(h);
2196 int chroma422 = CHROMA422(h);
2199 src_cb -= uvlinesize;
2200 src_cr -= uvlinesize;
2202 if (!simple && FRAME_MBAFF(h)) {
2205 top_border = h->top_borders[0][h->mb_x];
2206 AV_COPY128(top_border, src_y + 15 * linesize);
2208 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2209 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2212 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2213 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2214 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2215 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2217 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2218 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2220 } else if (chroma422) {
2222 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2223 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2225 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2226 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2230 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2231 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2233 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2234 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2239 } else if (MB_MBAFF(h)) {
2245 top_border = h->top_borders[top_idx][h->mb_x];
2246 /* There are two lines saved, the line above the top macroblock
2247 * of a pair, and the line above the bottom macroblock. */
2248 AV_COPY128(top_border, src_y + 16 * linesize);
2250 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2252 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2255 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2256 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2257 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2258 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2260 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2261 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2263 } else if (chroma422) {
2265 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2266 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2268 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2269 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2273 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2274 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2276 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2277 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2283 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2284 uint8_t *src_cb, uint8_t *src_cr,
2285 int linesize, int uvlinesize,
2286 int xchg, int chroma444,
2287 int simple, int pixel_shift)
2289 int deblock_topleft;
2292 uint8_t *top_border_m1;
2293 uint8_t *top_border;
2295 if (!simple && FRAME_MBAFF(h)) {
2300 top_idx = MB_MBAFF(h) ? 0 : 1;
2304 if (h->deblocking_filter == 2) {
2305 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2306 deblock_top = h->top_type;
2308 deblock_topleft = (h->mb_x > 0);
2309 deblock_top = (h->mb_y > !!MB_FIELD(h));
2312 src_y -= linesize + 1 + pixel_shift;
2313 src_cb -= uvlinesize + 1 + pixel_shift;
2314 src_cr -= uvlinesize + 1 + pixel_shift;
2316 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2317 top_border = h->top_borders[top_idx][h->mb_x];
2319 #define XCHG(a, b, xchg) \
2320 if (pixel_shift) { \
2322 AV_SWAP64(b + 0, a + 0); \
2323 AV_SWAP64(b + 8, a + 8); \
2333 if (deblock_topleft) {
2334 XCHG(top_border_m1 + (8 << pixel_shift),
2335 src_y - (7 << pixel_shift), 1);
2337 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2338 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2339 if (h->mb_x + 1 < h->mb_width) {
2340 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2341 src_y + (17 << pixel_shift), 1);
2343 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2345 if (deblock_topleft) {
2346 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2347 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2349 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2350 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2351 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2352 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2353 if (h->mb_x + 1 < h->mb_width) {
2354 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2355 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2358 if (deblock_topleft) {
2359 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2360 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2362 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2363 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2369 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2372 if (high_bit_depth) {
2373 return AV_RN32A(((int32_t *)mb) + index);
2375 return AV_RN16A(mb + index);
2378 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2379 int index, int value)
2381 if (high_bit_depth) {
2382 AV_WN32A(((int32_t *)mb) + index, value);
2384 AV_WN16A(mb + index, value);
2387 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2388 int mb_type, int is_h264,
2390 int transform_bypass,
2394 uint8_t *dest_y, int p)
2396 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2397 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2399 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2400 block_offset += 16 * p;
2401 if (IS_INTRA4x4(mb_type)) {
2402 if (IS_8x8DCT(mb_type)) {
2403 if (transform_bypass) {
2405 idct_add = h->h264dsp.h264_add_pixels8_clear;
2407 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2408 idct_add = h->h264dsp.h264_idct8_add;
2410 for (i = 0; i < 16; i += 4) {
2411 uint8_t *const ptr = dest_y + block_offset[i];
2412 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2413 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2414 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2416 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2417 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2418 (h->topright_samples_available << i) & 0x4000, linesize);
2420 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2421 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2423 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2428 if (transform_bypass) {
2430 idct_add = h->h264dsp.h264_add_pixels4_clear;
2432 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2433 idct_add = h->h264dsp.h264_idct_add;
2435 for (i = 0; i < 16; i++) {
2436 uint8_t *const ptr = dest_y + block_offset[i];
2437 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2439 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2440 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2445 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2446 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2447 av_assert2(h->mb_y || linesize <= block_offset[i]);
2448 if (!topright_avail) {
2450 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2451 topright = (uint8_t *)&tr_high;
2453 tr = ptr[3 - linesize] * 0x01010101u;
2454 topright = (uint8_t *)&tr;
2457 topright = ptr + (4 << pixel_shift) - linesize;
2461 h->hpc.pred4x4[dir](ptr, topright, linesize);
2462 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2465 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2466 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2468 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2469 } else if (CONFIG_SVQ3_DECODER)
2470 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2476 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2478 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2479 if (!transform_bypass)
2480 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2482 h->dequant4_coeff[p][qscale][0]);
2484 static const uint8_t dc_mapping[16] = {
2485 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2486 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2487 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2488 10 * 16, 11 * 16, 14 * 16, 15 * 16
2490 for (i = 0; i < 16; i++)
2491 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2492 pixel_shift, dc_mapping[i],
2493 dctcoef_get(h->mb_luma_dc[p],
2497 } else if (CONFIG_SVQ3_DECODER)
2498 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2499 h->mb_luma_dc[p], qscale);
2503 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2504 int is_h264, int simple,
2505 int transform_bypass,
2509 uint8_t *dest_y, int p)
2511 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2513 block_offset += 16 * p;
2514 if (!IS_INTRA4x4(mb_type)) {
2516 if (IS_INTRA16x16(mb_type)) {
2517 if (transform_bypass) {
2518 if (h->sps.profile_idc == 244 &&
2519 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2520 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2521 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2522 h->mb + (p * 256 << pixel_shift),
2525 for (i = 0; i < 16; i++)
2526 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2527 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2528 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2529 h->mb + (i * 16 + p * 256 << pixel_shift),
2533 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2534 h->mb + (p * 256 << pixel_shift),
2536 h->non_zero_count_cache + p * 5 * 8);
2538 } else if (h->cbp & 15) {
2539 if (transform_bypass) {
2540 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2541 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2542 : h->h264dsp.h264_add_pixels4_clear;
2543 for (i = 0; i < 16; i += di)
2544 if (h->non_zero_count_cache[scan8[i + p * 16]])
2545 idct_add(dest_y + block_offset[i],
2546 h->mb + (i * 16 + p * 256 << pixel_shift),
2549 if (IS_8x8DCT(mb_type))
2550 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2551 h->mb + (p * 256 << pixel_shift),
2553 h->non_zero_count_cache + p * 5 * 8);
2555 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2556 h->mb + (p * 256 << pixel_shift),
2558 h->non_zero_count_cache + p * 5 * 8);
2561 } else if (CONFIG_SVQ3_DECODER) {
2562 for (i = 0; i < 16; i++)
2563 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2564 // FIXME benchmark weird rule, & below
2565 uint8_t *const ptr = dest_y + block_offset[i];
2566 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2567 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2575 #include "h264_mb_template.c"
2579 #include "h264_mb_template.c"
2583 #include "h264_mb_template.c"
2585 void ff_h264_hl_decode_mb(H264Context *h)
2587 const int mb_xy = h->mb_xy;
2588 const int mb_type = h->cur_pic.mb_type[mb_xy];
2589 int is_complex = CONFIG_SMALL || h->is_complex ||
2590 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2593 if (is_complex || h->pixel_shift)
2594 hl_decode_mb_444_complex(h);
2596 hl_decode_mb_444_simple_8(h);
2597 } else if (is_complex) {
2598 hl_decode_mb_complex(h);
2599 } else if (h->pixel_shift) {
2600 hl_decode_mb_simple_16(h);
2602 hl_decode_mb_simple_8(h);
2605 int ff_pred_weight_table(H264Context *h)
2608 int luma_def, chroma_def;
2611 h->use_weight_chroma = 0;
2612 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2613 if (h->sps.chroma_format_idc)
2614 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2615 luma_def = 1 << h->luma_log2_weight_denom;
2616 chroma_def = 1 << h->chroma_log2_weight_denom;
2618 for (list = 0; list < 2; list++) {
2619 h->luma_weight_flag[list] = 0;
2620 h->chroma_weight_flag[list] = 0;
2621 for (i = 0; i < h->ref_count[list]; i++) {
2622 int luma_weight_flag, chroma_weight_flag;
2624 luma_weight_flag = get_bits1(&h->gb);
2625 if (luma_weight_flag) {
2626 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2627 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2628 if (h->luma_weight[i][list][0] != luma_def ||
2629 h->luma_weight[i][list][1] != 0) {
2631 h->luma_weight_flag[list] = 1;
2634 h->luma_weight[i][list][0] = luma_def;
2635 h->luma_weight[i][list][1] = 0;
2638 if (h->sps.chroma_format_idc) {
2639 chroma_weight_flag = get_bits1(&h->gb);
2640 if (chroma_weight_flag) {
2642 for (j = 0; j < 2; j++) {
2643 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2644 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2645 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2646 h->chroma_weight[i][list][j][1] != 0) {
2647 h->use_weight_chroma = 1;
2648 h->chroma_weight_flag[list] = 1;
2653 for (j = 0; j < 2; j++) {
2654 h->chroma_weight[i][list][j][0] = chroma_def;
2655 h->chroma_weight[i][list][j][1] = 0;
2660 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2663 h->use_weight = h->use_weight || h->use_weight_chroma;
2668 * Initialize implicit_weight table.
2669 * @param field 0/1 initialize the weight for interlaced MBAFF
2670 * -1 initializes the rest
2672 static void implicit_weight_table(H264Context *h, int field)
2674 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2676 for (i = 0; i < 2; i++) {
2677 h->luma_weight_flag[i] = 0;
2678 h->chroma_weight_flag[i] = 0;
2682 if (h->picture_structure == PICT_FRAME) {
2683 cur_poc = h->cur_pic_ptr->poc;
2685 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2687 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2688 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2690 h->use_weight_chroma = 0;
2694 ref_count0 = h->ref_count[0];
2695 ref_count1 = h->ref_count[1];
2697 cur_poc = h->cur_pic_ptr->field_poc[field];
2699 ref_count0 = 16 + 2 * h->ref_count[0];
2700 ref_count1 = 16 + 2 * h->ref_count[1];
2704 h->use_weight_chroma = 2;
2705 h->luma_log2_weight_denom = 5;
2706 h->chroma_log2_weight_denom = 5;
2708 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2709 int poc0 = h->ref_list[0][ref0].poc;
2710 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2712 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2713 int poc1 = h->ref_list[1][ref1].poc;
2714 int td = av_clip(poc1 - poc0, -128, 127);
2716 int tb = av_clip(cur_poc - poc0, -128, 127);
2717 int tx = (16384 + (FFABS(td) >> 1)) / td;
2718 int dist_scale_factor = (tb * tx + 32) >> 8;
2719 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2720 w = 64 - dist_scale_factor;
2724 h->implicit_weight[ref0][ref1][0] =
2725 h->implicit_weight[ref0][ref1][1] = w;
2727 h->implicit_weight[ref0][ref1][field] = w;
2734 * instantaneous decoder refresh.
2736 static void idr(H264Context *h)
2739 ff_h264_remove_all_refs(h);
2740 h->prev_frame_num = 0;
2741 h->prev_frame_num_offset = 0;
2742 h->prev_poc_msb = 1<<16;
2743 h->prev_poc_lsb = 0;
2744 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2745 h->last_pocs[i] = INT_MIN;
2748 /* forget old pics after a seek */
2749 static void flush_change(H264Context *h)
2753 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2754 h->prev_interlaced_frame = 1;
2757 h->prev_frame_num = -1;
2758 if (h->cur_pic_ptr) {
2759 h->cur_pic_ptr->reference = 0;
2760 for (j=i=0; h->delayed_pic[i]; i++)
2761 if (h->delayed_pic[i] != h->cur_pic_ptr)
2762 h->delayed_pic[j++] = h->delayed_pic[i];
2763 h->delayed_pic[j] = NULL;
2766 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2767 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2768 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2769 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2770 ff_h264_reset_sei(h);
2771 h->recovery_frame= -1;
2774 h->current_slice = 0;
2777 /* forget old pics after a seek */
2778 static void flush_dpb(AVCodecContext *avctx)
2780 H264Context *h = avctx->priv_data;
2783 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2784 if (h->delayed_pic[i])
2785 h->delayed_pic[i]->reference = 0;
2786 h->delayed_pic[i] = NULL;
2792 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2793 unref_picture(h, &h->DPB[i]);
2794 h->cur_pic_ptr = NULL;
2795 unref_picture(h, &h->cur_pic);
2797 h->mb_x = h->mb_y = 0;
2799 h->parse_context.state = -1;
2800 h->parse_context.frame_start_found = 0;
2801 h->parse_context.overread = 0;
2802 h->parse_context.overread_index = 0;
2803 h->parse_context.index = 0;
2804 h->parse_context.last_index = 0;
2807 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2809 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2812 h->frame_num_offset = h->prev_frame_num_offset;
2813 if (h->frame_num < h->prev_frame_num)
2814 h->frame_num_offset += max_frame_num;
2816 if (h->sps.poc_type == 0) {
2817 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2819 if (h->poc_lsb < h->prev_poc_lsb &&
2820 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2821 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2822 else if (h->poc_lsb > h->prev_poc_lsb &&
2823 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2824 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2826 h->poc_msb = h->prev_poc_msb;
2828 field_poc[1] = h->poc_msb + h->poc_lsb;
2829 if (h->picture_structure == PICT_FRAME)
2830 field_poc[1] += h->delta_poc_bottom;
2831 } else if (h->sps.poc_type == 1) {
2832 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2835 if (h->sps.poc_cycle_length != 0)
2836 abs_frame_num = h->frame_num_offset + h->frame_num;
2840 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2843 expected_delta_per_poc_cycle = 0;
2844 for (i = 0; i < h->sps.poc_cycle_length; i++)
2845 // FIXME integrate during sps parse
2846 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2848 if (abs_frame_num > 0) {
2849 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2850 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2852 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2853 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2854 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2858 if (h->nal_ref_idc == 0)
2859 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2861 field_poc[0] = expectedpoc + h->delta_poc[0];
2862 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2864 if (h->picture_structure == PICT_FRAME)
2865 field_poc[1] += h->delta_poc[1];
2867 int poc = 2 * (h->frame_num_offset + h->frame_num);
2869 if (!h->nal_ref_idc)
2876 if (h->picture_structure != PICT_BOTTOM_FIELD)
2877 pic_field_poc[0] = field_poc[0];
2878 if (h->picture_structure != PICT_TOP_FIELD)
2879 pic_field_poc[1] = field_poc[1];
2880 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2886 * initialize scan tables
2888 static void init_scan_tables(H264Context *h)
2891 for (i = 0; i < 16; i++) {
2892 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2893 h->zigzag_scan[i] = T(zigzag_scan[i]);
2894 h->field_scan[i] = T(field_scan[i]);
2897 for (i = 0; i < 64; i++) {
2898 #define T(x) (x >> 3) | ((x & 7) << 3)
2899 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2900 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2901 h->field_scan8x8[i] = T(field_scan8x8[i]);
2902 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2905 if (h->sps.transform_bypass) { // FIXME same ugly
2906 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2907 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2908 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2909 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2910 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2911 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2913 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2914 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2915 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2916 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2917 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2918 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2922 static int field_end(H264Context *h, int in_setup)
2924 AVCodecContext *const avctx = h->avctx;
2928 if (CONFIG_H264_VDPAU_DECODER &&
2929 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2930 ff_vdpau_h264_set_reference_frames(h);
2932 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2933 if (!h->droppable) {
2934 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2935 h->prev_poc_msb = h->poc_msb;
2936 h->prev_poc_lsb = h->poc_lsb;
2938 h->prev_frame_num_offset = h->frame_num_offset;
2939 h->prev_frame_num = h->frame_num;
2940 h->outputed_poc = h->next_outputed_poc;
2943 if (avctx->hwaccel) {
2944 if (avctx->hwaccel->end_frame(avctx) < 0)
2945 av_log(avctx, AV_LOG_ERROR,
2946 "hardware accelerator failed to decode picture\n");
2949 if (CONFIG_H264_VDPAU_DECODER &&
2950 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2951 ff_vdpau_h264_picture_complete(h);
2954 * FIXME: Error handling code does not seem to support interlaced
2955 * when slices span multiple rows
2956 * The ff_er_add_slice calls don't work right for bottom
2957 * fields; they cause massive erroneous error concealing
2958 * Error marking covers both fields (top and bottom).
2959 * This causes a mismatched s->error_count
2960 * and a bad error table. Further, the error count goes to
2961 * INT_MAX when called for bottom field, because mb_y is
2962 * past end by one (callers fault) and resync_mb_y != 0
2963 * causes problems for the first MB line, too.
2965 if (CONFIG_ERROR_RESILIENCE &&
2966 !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
2967 h->er.cur_pic = h->cur_pic_ptr;
2968 ff_er_frame_end(&h->er);
2970 if (!in_setup && !h->droppable)
2971 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2972 h->picture_structure == PICT_BOTTOM_FIELD);
2975 h->current_slice = 0;
2981 * Replicate H264 "master" context to thread contexts.
2983 static int clone_slice(H264Context *dst, H264Context *src)
2985 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2986 dst->cur_pic_ptr = src->cur_pic_ptr;
2987 dst->cur_pic = src->cur_pic;
2988 dst->linesize = src->linesize;
2989 dst->uvlinesize = src->uvlinesize;
2990 dst->first_field = src->first_field;
2992 dst->prev_poc_msb = src->prev_poc_msb;
2993 dst->prev_poc_lsb = src->prev_poc_lsb;
2994 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2995 dst->prev_frame_num = src->prev_frame_num;
2996 dst->short_ref_count = src->short_ref_count;
2998 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2999 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
3000 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3002 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
3003 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
3009 * Compute profile from profile_idc and constraint_set?_flags.
3013 * @return profile as defined by FF_PROFILE_H264_*
3015 int ff_h264_get_profile(SPS *sps)
3017 int profile = sps->profile_idc;
3019 switch (sps->profile_idc) {
3020 case FF_PROFILE_H264_BASELINE:
3021 // constraint_set1_flag set to 1
3022 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3024 case FF_PROFILE_H264_HIGH_10:
3025 case FF_PROFILE_H264_HIGH_422:
3026 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3027 // constraint_set3_flag set to 1
3028 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3035 static int h264_set_parameter_from_sps(H264Context *h)
3037 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3038 (h->sps.bitstream_restriction_flag &&
3039 !h->sps.num_reorder_frames)) {
3040 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3041 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3042 "Reenabling low delay requires a codec flush.\n");
3047 if (h->avctx->has_b_frames < 2)
3048 h->avctx->has_b_frames = !h->low_delay;
3050 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
3051 avpriv_request_sample(h->avctx,
3052 "Different chroma and luma bit depth");
3053 return AVERROR_PATCHWELCOME;
3056 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3057 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
3058 if (h->avctx->codec &&
3059 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
3060 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
3061 av_log(h->avctx, AV_LOG_ERROR,
3062 "VDPAU decoding does not support video colorspace.\n");
3063 return AVERROR_INVALIDDATA;
3065 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
3066 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
3067 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3068 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
3069 h->pixel_shift = h->sps.bit_depth_luma > 8;
3071 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3072 h->sps.chroma_format_idc);
3073 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3074 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3075 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3076 h->sps.chroma_format_idc);
3078 if (CONFIG_ERROR_RESILIENCE)
3079 ff_dsputil_init(&h->dsp, h->avctx);
3080 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3082 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3083 h->sps.bit_depth_luma);
3084 return AVERROR_INVALIDDATA;
3090 static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3092 switch (h->sps.bit_depth_luma) {
3095 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3096 return AV_PIX_FMT_GBRP9;
3098 return AV_PIX_FMT_YUV444P9;
3099 } else if (CHROMA422(h))
3100 return AV_PIX_FMT_YUV422P9;
3102 return AV_PIX_FMT_YUV420P9;
3106 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3107 return AV_PIX_FMT_GBRP10;
3109 return AV_PIX_FMT_YUV444P10;
3110 } else if (CHROMA422(h))
3111 return AV_PIX_FMT_YUV422P10;
3113 return AV_PIX_FMT_YUV420P10;
3117 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3118 return AV_PIX_FMT_GBRP12;
3120 return AV_PIX_FMT_YUV444P12;
3121 } else if (CHROMA422(h))
3122 return AV_PIX_FMT_YUV422P12;
3124 return AV_PIX_FMT_YUV420P12;
3128 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3129 return AV_PIX_FMT_GBRP14;
3131 return AV_PIX_FMT_YUV444P14;
3132 } else if (CHROMA422(h))
3133 return AV_PIX_FMT_YUV422P14;
3135 return AV_PIX_FMT_YUV420P14;
3139 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3140 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
3141 return AV_PIX_FMT_GBR24P;
3142 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
3143 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
3145 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3146 : AV_PIX_FMT_YUV444P;
3147 } else if (CHROMA422(h)) {
3148 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3149 : AV_PIX_FMT_YUV422P;
3152 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
3153 h->avctx->codec->pix_fmts :
3154 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3155 h264_hwaccel_pixfmt_list_jpeg_420 :
3156 h264_hwaccel_pixfmt_list_420;
3158 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
3159 if (fmt[i] == h->avctx->pix_fmt && !force_callback)
3161 return ff_thread_get_format(h->avctx, fmt);
3165 av_log(h->avctx, AV_LOG_ERROR,
3166 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3167 return AVERROR_INVALIDDATA;
3171 /* export coded and cropped frame dimensions to AVCodecContext */
3172 static int init_dimensions(H264Context *h)
3174 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3175 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3176 av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
3177 av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
3179 /* handle container cropping */
3181 FFALIGN(h->avctx->width, 16) == h->width &&
3182 FFALIGN(h->avctx->height, 16) == h->height) {
3183 width = h->avctx->width;
3184 height = h->avctx->height;
3187 if (width <= 0 || height <= 0) {
3188 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3190 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3191 return AVERROR_INVALIDDATA;
3193 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3194 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3201 h->avctx->coded_width = h->width;
3202 h->avctx->coded_height = h->height;
3203 h->avctx->width = width;
3204 h->avctx->height = height;
3209 static int h264_slice_header_init(H264Context *h, int reinit)
3211 int nb_slices = (HAVE_THREADS &&
3212 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3213 h->avctx->thread_count : 1;
3216 h->avctx->sample_aspect_ratio = h->sps.sar;
3217 av_assert0(h->avctx->sample_aspect_ratio.den);
3218 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3219 &h->chroma_x_shift, &h->chroma_y_shift);
3221 if (h->sps.timing_info_present_flag) {
3222 int64_t den = h->sps.time_scale;
3223 if (h->x264_build < 44U)
3225 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3226 h->sps.num_units_in_tick, den, 1 << 30);
3229 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
3234 h->prev_interlaced_frame = 1;
3236 init_scan_tables(h);
3237 ret = ff_h264_alloc_tables(h);
3239 av_log(h->avctx, AV_LOG_ERROR,
3240 "Could not allocate memory for h264\n");
3244 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3247 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3249 max_slices = MAX_THREADS;
3250 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3251 " reducing to %d\n", nb_slices, max_slices);
3252 nb_slices = max_slices;
3254 h->slice_context_count = nb_slices;
3256 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3257 ret = context_init(h);
3259 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3263 for (i = 1; i < h->slice_context_count; i++) {
3265 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3266 c->avctx = h->avctx;
3267 if (CONFIG_ERROR_RESILIENCE) {
3271 c->h264dsp = h->h264dsp;
3272 c->h264qpel = h->h264qpel;
3273 c->h264chroma = h->h264chroma;
3276 c->pixel_shift = h->pixel_shift;
3277 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3278 c->width = h->width;
3279 c->height = h->height;
3280 c->linesize = h->linesize;
3281 c->uvlinesize = h->uvlinesize;
3282 c->chroma_x_shift = h->chroma_x_shift;
3283 c->chroma_y_shift = h->chroma_y_shift;
3284 c->qscale = h->qscale;
3285 c->droppable = h->droppable;
3286 c->data_partitioning = h->data_partitioning;
3287 c->low_delay = h->low_delay;
3288 c->mb_width = h->mb_width;
3289 c->mb_height = h->mb_height;
3290 c->mb_stride = h->mb_stride;
3291 c->mb_num = h->mb_num;
3292 c->flags = h->flags;
3293 c->workaround_bugs = h->workaround_bugs;
3294 c->pict_type = h->pict_type;
3296 init_scan_tables(c);
3297 clone_tables(c, h, i);
3298 c->context_initialized = 1;
3301 for (i = 0; i < h->slice_context_count; i++)
3302 if ((ret = context_init(h->thread_context[i])) < 0) {
3303 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3308 h->context_initialized = 1;
3313 int ff_set_ref_count(H264Context *h)
3315 int num_ref_idx_active_override_flag;
3317 // set defaults, might be overridden a few lines later
3318 h->ref_count[0] = h->pps.ref_count[0];
3319 h->ref_count[1] = h->pps.ref_count[1];
3321 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3323 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3325 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3326 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3327 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3329 if (num_ref_idx_active_override_flag) {
3330 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3331 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3332 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3334 // full range is spec-ok in this case, even for frames
3335 h->ref_count[1] = 1;
3338 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3339 av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
3340 h->ref_count[0] = h->ref_count[1] = 0;
3341 return AVERROR_INVALIDDATA;
3344 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3350 h->ref_count[0] = h->ref_count[1] = 0;
3357 * Decode a slice header.
3358 * This will also call ff_MPV_common_init() and frame_start() as needed.
3360 * @param h h264context
3361 * @param h0 h264 master context (differs from 'h' when doing sliced based
3362 * parallel decoding)
3364 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3366 static int decode_slice_header(H264Context *h, H264Context *h0)
3368 unsigned int first_mb_in_slice;
3369 unsigned int pps_id;
3371 unsigned int slice_type, tmp, i, j;
3372 int last_pic_structure, last_pic_droppable;
3374 int needs_reinit = 0;
3375 int field_pic_flag, bottom_field_flag;
3377 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3378 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3380 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3382 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3383 if (h0->current_slice && FIELD_PICTURE(h)) {
3387 h0->current_slice = 0;
3388 if (!h0->first_field) {
3389 if (h->cur_pic_ptr && !h->droppable) {
3390 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3391 h->picture_structure == PICT_BOTTOM_FIELD);
3393 h->cur_pic_ptr = NULL;
3397 slice_type = get_ue_golomb_31(&h->gb);
3398 if (slice_type > 9) {
3399 av_log(h->avctx, AV_LOG_ERROR,
3400 "slice type too large (%d) at %d %d\n",
3401 slice_type, h->mb_x, h->mb_y);
3402 return AVERROR_INVALIDDATA;
3404 if (slice_type > 4) {
3406 h->slice_type_fixed = 1;
3408 h->slice_type_fixed = 0;
3410 slice_type = golomb_to_pict_type[slice_type];
3411 h->slice_type = slice_type;
3412 h->slice_type_nos = slice_type & 3;
3414 // to make a few old functions happy, it's wrong though
3415 h->pict_type = h->slice_type;
3417 pps_id = get_ue_golomb(&h->gb);
3418 if (pps_id >= MAX_PPS_COUNT) {
3419 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3420 return AVERROR_INVALIDDATA;
3422 if (!h0->pps_buffers[pps_id]) {
3423 av_log(h->avctx, AV_LOG_ERROR,
3424 "non-existing PPS %u referenced\n",
3426 return AVERROR_INVALIDDATA;
3428 h->pps = *h0->pps_buffers[pps_id];
3430 if (!h0->sps_buffers[h->pps.sps_id]) {
3431 av_log(h->avctx, AV_LOG_ERROR,
3432 "non-existing SPS %u referenced\n",
3434 return AVERROR_INVALIDDATA;
3437 if (h->pps.sps_id != h->current_sps_id ||
3438 h0->sps_buffers[h->pps.sps_id]->new) {
3439 h0->sps_buffers[h->pps.sps_id]->new = 0;
3441 h->current_sps_id = h->pps.sps_id;
3442 h->sps = *h0->sps_buffers[h->pps.sps_id];
3444 if (h->mb_width != h->sps.mb_width ||
3445 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3446 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3447 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3451 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3452 h->chroma_format_idc != h->sps.chroma_format_idc) {
3453 h->bit_depth_luma = h->sps.bit_depth_luma;
3454 h->chroma_format_idc = h->sps.chroma_format_idc;
3457 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3461 h->avctx->profile = ff_h264_get_profile(&h->sps);
3462 h->avctx->level = h->sps.level_idc;
3463 h->avctx->refs = h->sps.ref_frame_count;
3465 must_reinit = (h->context_initialized &&
3466 ( 16*h->sps.mb_width != h->avctx->coded_width
3467 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3468 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3469 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3470 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
3471 || h->mb_width != h->sps.mb_width
3472 || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
3474 if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3477 h->mb_width = h->sps.mb_width;
3478 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3479 h->mb_num = h->mb_width * h->mb_height;
3480 h->mb_stride = h->mb_width + 1;
3482 h->b_stride = h->mb_width * 4;
3484 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3486 h->width = 16 * h->mb_width;
3487 h->height = 16 * h->mb_height;
3489 ret = init_dimensions(h);
3493 if (h->sps.video_signal_type_present_flag) {
3494 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3496 if (h->sps.colour_description_present_flag) {
3497 if (h->avctx->colorspace != h->sps.colorspace)
3499 h->avctx->color_primaries = h->sps.color_primaries;
3500 h->avctx->color_trc = h->sps.color_trc;
3501 h->avctx->colorspace = h->sps.colorspace;
3505 if (h->context_initialized &&
3506 (h->width != h->avctx->coded_width ||
3507 h->height != h->avctx->coded_height ||
3511 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3512 "slice %d\n", h0->current_slice + 1);
3513 return AVERROR_INVALIDDATA;
3518 if ((ret = get_pixel_format(h, 1)) < 0)
3520 h->avctx->pix_fmt = ret;
3522 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3523 "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
3525 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3526 av_log(h->avctx, AV_LOG_ERROR,
3527 "h264_slice_header_init() failed\n");
3531 if (!h->context_initialized) {
3533 av_log(h->avctx, AV_LOG_ERROR,
3534 "Cannot (re-)initialize context during parallel decoding.\n");
3535 return AVERROR_PATCHWELCOME;
3538 if ((ret = get_pixel_format(h, 1)) < 0)
3540 h->avctx->pix_fmt = ret;
3542 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3543 av_log(h->avctx, AV_LOG_ERROR,
3544 "h264_slice_header_init() failed\n");
3549 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3550 h->dequant_coeff_pps = pps_id;
3551 init_dequant_tables(h);
3554 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3557 h->mb_aff_frame = 0;
3558 last_pic_structure = h0->picture_structure;
3559 last_pic_droppable = h0->droppable;
3560 h->droppable = h->nal_ref_idc == 0;
3561 if (h->sps.frame_mbs_only_flag) {
3562 h->picture_structure = PICT_FRAME;
3564 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3565 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3568 field_pic_flag = get_bits1(&h->gb);
3569 if (field_pic_flag) {
3570 bottom_field_flag = get_bits1(&h->gb);
3571 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3573 h->picture_structure = PICT_FRAME;
3574 h->mb_aff_frame = h->sps.mb_aff;
3577 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3579 if (h0->current_slice != 0) {
3580 if (last_pic_structure != h->picture_structure ||
3581 last_pic_droppable != h->droppable) {
3582 av_log(h->avctx, AV_LOG_ERROR,
3583 "Changing field mode (%d -> %d) between slices is not allowed\n",
3584 last_pic_structure, h->picture_structure);
3585 h->picture_structure = last_pic_structure;
3586 h->droppable = last_pic_droppable;
3587 return AVERROR_INVALIDDATA;
3588 } else if (!h0->cur_pic_ptr) {
3589 av_log(h->avctx, AV_LOG_ERROR,
3590 "unset cur_pic_ptr on %d. slice\n",
3591 h0->current_slice + 1);
3592 return AVERROR_INVALIDDATA;
3595 /* Shorten frame num gaps so we don't have to allocate reference
3596 * frames just to throw them away */
3597 if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
3598 int unwrap_prev_frame_num = h->prev_frame_num;
3599 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3601 if (unwrap_prev_frame_num > h->frame_num)
3602 unwrap_prev_frame_num -= max_frame_num;
3604 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3605 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3606 if (unwrap_prev_frame_num < 0)
3607 unwrap_prev_frame_num += max_frame_num;
3609 h->prev_frame_num = unwrap_prev_frame_num;
3613 /* See if we have a decoded first field looking for a pair...
3614 * Here, we're using that to see if we should mark previously
3615 * decode frames as "finished".
3616 * We have to do that before the "dummy" in-between frame allocation,
3617 * since that can modify h->cur_pic_ptr. */
3618 if (h0->first_field) {
3619 assert(h0->cur_pic_ptr);
3620 assert(h0->cur_pic_ptr->f.data[0]);
3621 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3623 /* Mark old field/frame as completed */
3624 if (!last_pic_droppable && h0->cur_pic_ptr->tf.owner == h0->avctx) {
3625 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3626 last_pic_structure == PICT_BOTTOM_FIELD);
3629 /* figure out if we have a complementary field pair */
3630 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3631 /* Previous field is unmatched. Don't display it, but let it
3632 * remain for reference if marked as such. */
3633 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3634 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3635 last_pic_structure == PICT_TOP_FIELD);
3638 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3639 /* This and previous field were reference, but had
3640 * different frame_nums. Consider this field first in
3641 * pair. Throw away previous field except for reference
3643 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3644 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3645 last_pic_structure == PICT_TOP_FIELD);
3648 /* Second field in complementary pair */
3649 if (!((last_pic_structure == PICT_TOP_FIELD &&
3650 h->picture_structure == PICT_BOTTOM_FIELD) ||
3651 (last_pic_structure == PICT_BOTTOM_FIELD &&
3652 h->picture_structure == PICT_TOP_FIELD))) {
3653 av_log(h->avctx, AV_LOG_ERROR,
3654 "Invalid field mode combination %d/%d\n",
3655 last_pic_structure, h->picture_structure);
3656 h->picture_structure = last_pic_structure;
3657 h->droppable = last_pic_droppable;
3658 return AVERROR_INVALIDDATA;
3659 } else if (last_pic_droppable != h->droppable) {
3660 avpriv_request_sample(h->avctx,
3661 "Found reference and non-reference fields in the same frame, which");
3662 h->picture_structure = last_pic_structure;
3663 h->droppable = last_pic_droppable;
3664 return AVERROR_PATCHWELCOME;
3670 while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field &&
3671 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3672 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3673 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3674 h->frame_num, h->prev_frame_num);
3675 if (!h->sps.gaps_in_frame_num_allowed_flag)
3676 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3677 h->last_pocs[i] = INT_MIN;
3678 ret = h264_frame_start(h);
3681 h->prev_frame_num++;
3682 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3683 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3684 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3685 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3686 ret = ff_generate_sliding_window_mmcos(h, 1);
3687 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3689 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3690 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3692 /* Error concealment: If a ref is missing, copy the previous ref
3694 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3695 * many assumptions about there being no actual duplicates.
3696 * FIXME: This does not copy padding for out-of-frame motion
3697 * vectors. Given we are concealing a lost frame, this probably
3698 * is not noticeable by comparison, but it should be fixed. */
3699 if (h->short_ref_count) {
3701 av_image_copy(h->short_ref[0]->f.data,
3702 h->short_ref[0]->f.linesize,
3703 (const uint8_t **)prev->f.data,
3708 h->short_ref[0]->poc = prev->poc + 2;
3710 h->short_ref[0]->frame_num = h->prev_frame_num;
3714 /* See if we have a decoded first field looking for a pair...
3715 * We're using that to see whether to continue decoding in that
3716 * frame, or to allocate a new one. */
3717 if (h0->first_field) {
3718 assert(h0->cur_pic_ptr);
3719 assert(h0->cur_pic_ptr->f.data[0]);
3720 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3722 /* figure out if we have a complementary field pair */
3723 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3724 /* Previous field is unmatched. Don't display it, but let it
3725 * remain for reference if marked as such. */
3726 h0->cur_pic_ptr = NULL;
3727 h0->first_field = FIELD_PICTURE(h);
3729 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3730 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3731 h0->picture_structure==PICT_BOTTOM_FIELD);
3732 /* This and the previous field had different frame_nums.
3733 * Consider this field first in pair. Throw away previous
3734 * one except for reference purposes. */
3735 h0->first_field = 1;
3736 h0->cur_pic_ptr = NULL;
3738 /* Second field in complementary pair */
3739 h0->first_field = 0;
3743 /* Frame or first field in a potentially complementary pair */
3744 h0->first_field = FIELD_PICTURE(h);
3747 if (!FIELD_PICTURE(h) || h0->first_field) {
3748 if (h264_frame_start(h) < 0) {
3749 h0->first_field = 0;
3750 return AVERROR_INVALIDDATA;
3753 release_unused_pictures(h, 0);
3755 /* Some macroblocks can be accessed before they're available in case
3756 * of lost slices, MBAFF or threading. */
3757 if (FIELD_PICTURE(h)) {
3758 for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
3759 memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
3761 memset(h->slice_table, -1,
3762 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
3764 h0->last_slice_type = -1;
3766 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3769 /* can't be in alloc_tables because linesize isn't known there.
3770 * FIXME: redo bipred weight to not require extra buffer? */
3771 for (i = 0; i < h->slice_context_count; i++)
3772 if (h->thread_context[i]) {
3773 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
3778 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3780 av_assert1(h->mb_num == h->mb_width * h->mb_height);
3781 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3782 first_mb_in_slice >= h->mb_num) {
3783 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3784 return AVERROR_INVALIDDATA;
3786 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3787 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3788 FIELD_OR_MBAFF_PICTURE(h);
3789 if (h->picture_structure == PICT_BOTTOM_FIELD)
3790 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3791 av_assert1(h->mb_y < h->mb_height);
3793 if (h->picture_structure == PICT_FRAME) {
3794 h->curr_pic_num = h->frame_num;
3795 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3797 h->curr_pic_num = 2 * h->frame_num + 1;
3798 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3801 if (h->nal_unit_type == NAL_IDR_SLICE)
3802 get_ue_golomb(&h->gb); /* idr_pic_id */
3804 if (h->sps.poc_type == 0) {
3805 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3807 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3808 h->delta_poc_bottom = get_se_golomb(&h->gb);
3811 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3812 h->delta_poc[0] = get_se_golomb(&h->gb);
3814 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3815 h->delta_poc[1] = get_se_golomb(&h->gb);
3818 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3820 if (h->pps.redundant_pic_cnt_present)
3821 h->redundant_pic_count = get_ue_golomb(&h->gb);
3823 ret = ff_set_ref_count(h);
3827 if (slice_type != AV_PICTURE_TYPE_I &&
3828 (h0->current_slice == 0 ||
3829 slice_type != h0->last_slice_type ||
3830 memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3832 ff_h264_fill_default_ref_list(h);
3835 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3836 ret = ff_h264_decode_ref_pic_list_reordering(h);
3838 h->ref_count[1] = h->ref_count[0] = 0;
3843 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3844 (h->pps.weighted_bipred_idc == 1 &&
3845 h->slice_type_nos == AV_PICTURE_TYPE_B))
3846 ff_pred_weight_table(h);
3847 else if (h->pps.weighted_bipred_idc == 2 &&
3848 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3849 implicit_weight_table(h, -1);
3852 for (i = 0; i < 2; i++) {
3853 h->luma_weight_flag[i] = 0;
3854 h->chroma_weight_flag[i] = 0;
3858 // If frame-mt is enabled, only update mmco tables for the first slice
3859 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3860 // or h->mmco, which will cause ref list mix-ups and decoding errors
3861 // further down the line. This may break decoding if the first slice is
3862 // corrupt, thus we only do this if frame-mt is enabled.
3863 if (h->nal_ref_idc) {
3864 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3865 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3866 h0->current_slice == 0);
3867 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3868 return AVERROR_INVALIDDATA;
3871 if (FRAME_MBAFF(h)) {
3872 ff_h264_fill_mbaff_ref_list(h);
3874 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3875 implicit_weight_table(h, 0);
3876 implicit_weight_table(h, 1);
3880 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3881 ff_h264_direct_dist_scale_factor(h);
3882 ff_h264_direct_ref_list_init(h);
3884 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3885 tmp = get_ue_golomb_31(&h->gb);
3887 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3888 return AVERROR_INVALIDDATA;
3890 h->cabac_init_idc = tmp;
3893 h->last_qscale_diff = 0;
3894 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3895 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3896 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3897 return AVERROR_INVALIDDATA;
3900 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3901 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3902 // FIXME qscale / qp ... stuff
3903 if (h->slice_type == AV_PICTURE_TYPE_SP)
3904 get_bits1(&h->gb); /* sp_for_switch_flag */
3905 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3906 h->slice_type == AV_PICTURE_TYPE_SI)
3907 get_se_golomb(&h->gb); /* slice_qs_delta */
3909 h->deblocking_filter = 1;
3910 h->slice_alpha_c0_offset = 52;
3911 h->slice_beta_offset = 52;
3912 if (h->pps.deblocking_filter_parameters_present) {
3913 tmp = get_ue_golomb_31(&h->gb);
3915 av_log(h->avctx, AV_LOG_ERROR,
3916 "deblocking_filter_idc %u out of range\n", tmp);
3917 return AVERROR_INVALIDDATA;
3919 h->deblocking_filter = tmp;
3920 if (h->deblocking_filter < 2)
3921 h->deblocking_filter ^= 1; // 1<->0
3923 if (h->deblocking_filter) {
3924 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3925 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3926 if (h->slice_alpha_c0_offset > 104U ||
3927 h->slice_beta_offset > 104U) {
3928 av_log(h->avctx, AV_LOG_ERROR,
3929 "deblocking filter parameters %d %d out of range\n",
3930 h->slice_alpha_c0_offset, h->slice_beta_offset);
3931 return AVERROR_INVALIDDATA;
3936 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3937 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3938 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3939 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3940 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3941 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3942 h->nal_ref_idc == 0))
3943 h->deblocking_filter = 0;
3945 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3946 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3947 /* Cheat slightly for speed:
3948 * Do not bother to deblock across slices. */
3949 h->deblocking_filter = 2;
3951 h0->max_contexts = 1;
3952 if (!h0->single_decode_warning) {
3953 av_log(h->avctx, AV_LOG_INFO,
3954 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3955 h0->single_decode_warning = 1;
3958 av_log(h->avctx, AV_LOG_ERROR,
3959 "Deblocking switched inside frame.\n");
3964 h->qp_thresh = 15 + 52 -
3965 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3967 h->pps.chroma_qp_index_offset[0],
3968 h->pps.chroma_qp_index_offset[1]) +
3969 6 * (h->sps.bit_depth_luma - 8);
3971 h0->last_slice_type = slice_type;
3972 memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
3973 h->slice_num = ++h0->current_slice;
3976 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
3977 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
3978 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
3979 && h->slice_num >= MAX_SLICES) {
3980 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
3981 av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
3984 for (j = 0; j < 2; j++) {
3986 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3987 for (i = 0; i < 16; i++) {
3989 if (j < h->list_count && i < h->ref_count[j] &&
3990 h->ref_list[j][i].f.buf[0]) {
3992 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
3993 for (k = 0; k < h->short_ref_count; k++)
3994 if (h->short_ref[k]->f.buf[0]->buffer == buf) {