2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/avassert.h"
29 #include "libavutil/imgutils.h"
32 #include "cabac_functions.h"
34 #include "error_resilience.h"
36 #include "mpegvideo.h"
39 #include "h264chroma.h"
40 #include "h264_mvpred.h"
43 #include "rectangle.h"
49 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
51 static const uint8_t rem6[QP_MAX_NUM + 1] = {
52 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
53 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
54 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
57 static const uint8_t div6[QP_MAX_NUM + 1] = {
58 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
59 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
60 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
63 static const uint8_t field_scan[16] = {
64 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
65 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
66 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
67 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
70 static const uint8_t field_scan8x8[64] = {
71 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
72 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
73 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
74 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
75 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
76 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
77 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
78 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
79 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
80 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
81 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
82 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
83 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
84 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
85 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
86 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
89 static const uint8_t field_scan8x8_cavlc[64] = {
90 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
91 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
92 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
93 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
94 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
95 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
96 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
97 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
98 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
99 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
100 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
101 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
102 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
103 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
104 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
105 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
108 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
109 static const uint8_t zigzag_scan8x8_cavlc[64] = {
110 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
111 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
112 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
113 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
114 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
115 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
116 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
117 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
118 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
119 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
120 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
121 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
122 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
123 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
124 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
125 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
128 static const uint8_t dequant4_coeff_init[6][3] = {
137 static const uint8_t dequant8_coeff_init_scan[16] = {
138 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
141 static const uint8_t dequant8_coeff_init[6][6] = {
142 { 20, 18, 32, 19, 25, 24 },
143 { 22, 19, 35, 21, 28, 26 },
144 { 26, 23, 42, 24, 33, 31 },
145 { 28, 25, 45, 26, 35, 33 },
146 { 32, 28, 51, 30, 40, 38 },
147 { 36, 32, 58, 34, 46, 43 },
150 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
151 #if CONFIG_H264_DXVA2_HWACCEL
152 AV_PIX_FMT_DXVA2_VLD,
154 #if CONFIG_H264_VAAPI_HWACCEL
155 AV_PIX_FMT_VAAPI_VLD,
157 #if CONFIG_H264_VDA_HWACCEL
160 #if CONFIG_H264_VDPAU_HWACCEL
167 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
168 #if CONFIG_H264_DXVA2_HWACCEL
169 AV_PIX_FMT_DXVA2_VLD,
171 #if CONFIG_H264_VAAPI_HWACCEL
172 AV_PIX_FMT_VAAPI_VLD,
174 #if CONFIG_H264_VDA_HWACCEL
177 #if CONFIG_H264_VDPAU_HWACCEL
184 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
186 int mb_x, int mb_y, int mb_intra, int mb_skipped)
188 H264Context *h = opaque;
192 h->mb_xy = mb_x + mb_y * h->mb_stride;
193 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
195 /* FIXME: It is possible albeit uncommon that slice references
196 * differ between slices. We take the easy approach and ignore
197 * it for now. If this turns out to have any relevance in
198 * practice then correct remapping should be added. */
199 if (ref >= h->ref_count[0])
201 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
203 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
204 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
205 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
206 assert(!FRAME_MBAFF(h));
207 ff_h264_hl_decode_mb(h);
210 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
212 AVCodecContext *avctx = h->avctx;
213 Picture *cur = &h->cur_pic;
214 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
215 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
216 int vshift = desc->log2_chroma_h;
217 const int field_pic = h->picture_structure != PICT_FRAME;
223 height = FFMIN(height, avctx->height - y);
225 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
228 if (avctx->draw_horiz_band) {
230 int offset[AV_NUM_DATA_POINTERS];
233 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
234 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
241 offset[0] = y * src->linesize[0];
243 offset[2] = (y >> vshift) * src->linesize[1];
244 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
249 avctx->draw_horiz_band(avctx, src, offset,
250 y, h->picture_structure, height);
254 static void unref_picture(H264Context *h, Picture *pic)
256 int off = offsetof(Picture, tf) + sizeof(pic->tf);
262 ff_thread_release_buffer(h->avctx, &pic->tf);
263 av_buffer_unref(&pic->hwaccel_priv_buf);
265 av_buffer_unref(&pic->qscale_table_buf);
266 av_buffer_unref(&pic->mb_type_buf);
267 for (i = 0; i < 2; i++) {
268 av_buffer_unref(&pic->motion_val_buf[i]);
269 av_buffer_unref(&pic->ref_index_buf[i]);
272 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
275 static void release_unused_pictures(H264Context *h, int remove_current)
279 /* release non reference frames */
280 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
281 if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&
282 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
283 unref_picture(h, &h->DPB[i]);
288 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
292 av_assert0(!dst->f.buf[0]);
293 av_assert0(src->f.buf[0]);
297 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
301 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
302 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
303 if (!dst->qscale_table_buf || !dst->mb_type_buf)
305 dst->qscale_table = src->qscale_table;
306 dst->mb_type = src->mb_type;
308 for (i = 0; i < 2; i++) {
309 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
310 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
311 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
313 dst->motion_val[i] = src->motion_val[i];
314 dst->ref_index[i] = src->ref_index[i];
317 if (src->hwaccel_picture_private) {
318 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
319 if (!dst->hwaccel_priv_buf)
321 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
324 for (i = 0; i < 2; i++)
325 dst->field_poc[i] = src->field_poc[i];
327 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
328 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
331 dst->frame_num = src->frame_num;
332 dst->mmco_reset = src->mmco_reset;
333 dst->pic_id = src->pic_id;
334 dst->long_ref = src->long_ref;
335 dst->mbaff = src->mbaff;
336 dst->field_picture = src->field_picture;
337 dst->needs_realloc = src->needs_realloc;
338 dst->reference = src->reference;
342 unref_picture(h, dst);
346 static int alloc_scratch_buffers(H264Context *h, int linesize)
348 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
350 if (h->bipred_scratchpad)
353 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
354 // edge emu needs blocksize + filter length - 1
355 // (= 21x21 for h264)
356 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
357 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
359 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
360 av_freep(&h->bipred_scratchpad);
361 av_freep(&h->edge_emu_buffer);
362 av_freep(&h->me.scratchpad);
363 return AVERROR(ENOMEM);
366 h->me.temp = h->me.scratchpad;
371 static int init_table_pools(H264Context *h)
373 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
374 const int mb_array_size = h->mb_stride * h->mb_height;
375 const int b4_stride = h->mb_width * 4 + 1;
376 const int b4_array_size = b4_stride * h->mb_height * 4;
378 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
380 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
381 sizeof(uint32_t), av_buffer_allocz);
382 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
383 sizeof(int16_t), av_buffer_allocz);
384 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
386 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
387 !h->ref_index_pool) {
388 av_buffer_pool_uninit(&h->qscale_table_pool);
389 av_buffer_pool_uninit(&h->mb_type_pool);
390 av_buffer_pool_uninit(&h->motion_val_pool);
391 av_buffer_pool_uninit(&h->ref_index_pool);
392 return AVERROR(ENOMEM);
398 static int alloc_picture(H264Context *h, Picture *pic)
402 av_assert0(!pic->f.data[0]);
405 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
406 AV_GET_BUFFER_FLAG_REF : 0);
410 h->linesize = pic->f.linesize[0];
411 h->uvlinesize = pic->f.linesize[1];
413 if (h->avctx->hwaccel) {
414 const AVHWAccel *hwaccel = h->avctx->hwaccel;
415 av_assert0(!pic->hwaccel_picture_private);
416 if (hwaccel->priv_data_size) {
417 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
418 if (!pic->hwaccel_priv_buf)
419 return AVERROR(ENOMEM);
420 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
424 if (!h->qscale_table_pool) {
425 ret = init_table_pools(h);
430 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
431 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
432 if (!pic->qscale_table_buf || !pic->mb_type_buf)
435 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
436 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
438 for (i = 0; i < 2; i++) {
439 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
440 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
441 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
444 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
445 pic->ref_index[i] = pic->ref_index_buf[i]->data;
450 unref_picture(h, pic);
451 return (ret < 0) ? ret : AVERROR(ENOMEM);
454 static inline int pic_is_unused(H264Context *h, Picture *pic)
456 if (pic->f.data[0] == NULL)
458 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
463 static int find_unused_picture(H264Context *h)
467 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
468 if (pic_is_unused(h, &h->DPB[i]))
471 if (i == MAX_PICTURE_COUNT)
472 return AVERROR_INVALIDDATA;
474 if (h->DPB[i].needs_realloc) {
475 h->DPB[i].needs_realloc = 0;
476 unref_picture(h, &h->DPB[i]);
483 * Check if the top & left blocks are available if needed and
484 * change the dc mode so it only uses the available blocks.
486 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
488 static const int8_t top[12] = {
489 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
491 static const int8_t left[12] = {
492 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
496 if (!(h->top_samples_available & 0x8000)) {
497 for (i = 0; i < 4; i++) {
498 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
500 av_log(h->avctx, AV_LOG_ERROR,
501 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
502 status, h->mb_x, h->mb_y);
503 return AVERROR_INVALIDDATA;
505 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
510 if ((h->left_samples_available & 0x8888) != 0x8888) {
511 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
512 for (i = 0; i < 4; i++)
513 if (!(h->left_samples_available & mask[i])) {
514 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
516 av_log(h->avctx, AV_LOG_ERROR,
517 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
518 status, h->mb_x, h->mb_y);
519 return AVERROR_INVALIDDATA;
521 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
527 } // FIXME cleanup like ff_h264_check_intra_pred_mode
530 * Check if the top & left blocks are available if needed and
531 * change the dc mode so it only uses the available blocks.
533 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
535 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
536 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
539 av_log(h->avctx, AV_LOG_ERROR,
540 "out of range intra chroma pred mode at %d %d\n",
542 return AVERROR_INVALIDDATA;
545 if (!(h->top_samples_available & 0x8000)) {
548 av_log(h->avctx, AV_LOG_ERROR,
549 "top block unavailable for requested intra mode at %d %d\n",
551 return AVERROR_INVALIDDATA;
555 if ((h->left_samples_available & 0x8080) != 0x8080) {
557 if (is_chroma && (h->left_samples_available & 0x8080)) {
558 // mad cow disease mode, aka MBAFF + constrained_intra_pred
559 mode = ALZHEIMER_DC_L0T_PRED8x8 +
560 (!(h->left_samples_available & 0x8000)) +
561 2 * (mode == DC_128_PRED8x8);
564 av_log(h->avctx, AV_LOG_ERROR,
565 "left block unavailable for requested intra mode at %d %d\n",
567 return AVERROR_INVALIDDATA;
574 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
575 int *dst_length, int *consumed, int length)
581 // src[0]&0x80; // forbidden bit
582 h->nal_ref_idc = src[0] >> 5;
583 h->nal_unit_type = src[0] & 0x1F;
588 #define STARTCODE_TEST \
589 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
590 if (src[i + 2] != 3) { \
591 /* startcode, so we must be past the end */ \
597 #if HAVE_FAST_UNALIGNED
598 #define FIND_FIRST_ZERO \
599 if (i > 0 && !src[i]) \
605 for (i = 0; i + 1 < length; i += 9) {
606 if (!((~AV_RN64A(src + i) &
607 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
608 0x8000800080008080ULL))
615 for (i = 0; i + 1 < length; i += 5) {
616 if (!((~AV_RN32A(src + i) &
617 (AV_RN32A(src + i) - 0x01000101U)) &
626 for (i = 0; i + 1 < length; i += 2) {
629 if (i > 0 && src[i - 1] == 0)
635 if (i >= length - 1) { // no escaped 0
636 *dst_length = length;
637 *consumed = length + 1; // +1 for the header
641 // use second escape buffer for inter data
642 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
643 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
644 length + FF_INPUT_BUFFER_PADDING_SIZE);
645 dst = h->rbsp_buffer[bufidx];
652 while (si + 2 < length) {
653 // remove escapes (very rare 1:2^22)
654 if (src[si + 2] > 3) {
655 dst[di++] = src[si++];
656 dst[di++] = src[si++];
657 } else if (src[si] == 0 && src[si + 1] == 0) {
658 if (src[si + 2] == 3) { // escape
663 } else // next start code
667 dst[di++] = src[si++];
670 dst[di++] = src[si++];
673 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
676 *consumed = si + 1; // +1 for the header
677 /* FIXME store exact number of bits in the getbitcontext
678 * (it is needed for decoding) */
683 * Identify the exact end of the bitstream
684 * @return the length of the trailing, or 0 if damaged
686 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
691 tprintf(h->avctx, "rbsp trailing %X\n", v);
693 for (r = 1; r < 9; r++) {
701 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
702 int height, int y_offset, int list)
704 int raw_my = h->mv_cache[list][scan8[n]][1];
705 int filter_height_up = (raw_my & 3) ? 2 : 0;
706 int filter_height_down = (raw_my & 3) ? 3 : 0;
707 int full_my = (raw_my >> 2) + y_offset;
708 int top = full_my - filter_height_up;
709 int bottom = full_my + filter_height_down + height;
711 return FFMAX(abs(top), bottom);
714 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
715 int height, int y_offset, int list0,
716 int list1, int *nrefs)
720 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
723 int ref_n = h->ref_cache[0][scan8[n]];
724 Picture *ref = &h->ref_list[0][ref_n];
726 // Error resilience puts the current picture in the ref list.
727 // Don't try to wait on these as it will cause a deadlock.
728 // Fields can wait on each other, though.
729 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
730 (ref->reference & 3) != h->picture_structure) {
731 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
732 if (refs[0][ref_n] < 0)
734 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
739 int ref_n = h->ref_cache[1][scan8[n]];
740 Picture *ref = &h->ref_list[1][ref_n];
742 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
743 (ref->reference & 3) != h->picture_structure) {
744 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
745 if (refs[1][ref_n] < 0)
747 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
753 * Wait until all reference frames are available for MC operations.
755 * @param h the H264 context
757 static void await_references(H264Context *h)
759 const int mb_xy = h->mb_xy;
760 const int mb_type = h->cur_pic.mb_type[mb_xy];
762 int nrefs[2] = { 0 };
765 memset(refs, -1, sizeof(refs));
767 if (IS_16X16(mb_type)) {
768 get_lowest_part_y(h, refs, 0, 16, 0,
769 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
770 } else if (IS_16X8(mb_type)) {
771 get_lowest_part_y(h, refs, 0, 8, 0,
772 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
773 get_lowest_part_y(h, refs, 8, 8, 8,
774 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
775 } else if (IS_8X16(mb_type)) {
776 get_lowest_part_y(h, refs, 0, 16, 0,
777 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
778 get_lowest_part_y(h, refs, 4, 16, 0,
779 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
783 assert(IS_8X8(mb_type));
785 for (i = 0; i < 4; i++) {
786 const int sub_mb_type = h->sub_mb_type[i];
788 int y_offset = (i & 2) << 2;
790 if (IS_SUB_8X8(sub_mb_type)) {
791 get_lowest_part_y(h, refs, n, 8, y_offset,
792 IS_DIR(sub_mb_type, 0, 0),
793 IS_DIR(sub_mb_type, 0, 1),
795 } else if (IS_SUB_8X4(sub_mb_type)) {
796 get_lowest_part_y(h, refs, n, 4, y_offset,
797 IS_DIR(sub_mb_type, 0, 0),
798 IS_DIR(sub_mb_type, 0, 1),
800 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
801 IS_DIR(sub_mb_type, 0, 0),
802 IS_DIR(sub_mb_type, 0, 1),
804 } else if (IS_SUB_4X8(sub_mb_type)) {
805 get_lowest_part_y(h, refs, n, 8, y_offset,
806 IS_DIR(sub_mb_type, 0, 0),
807 IS_DIR(sub_mb_type, 0, 1),
809 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
810 IS_DIR(sub_mb_type, 0, 0),
811 IS_DIR(sub_mb_type, 0, 1),
815 assert(IS_SUB_4X4(sub_mb_type));
816 for (j = 0; j < 4; j++) {
817 int sub_y_offset = y_offset + 2 * (j & 2);
818 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
819 IS_DIR(sub_mb_type, 0, 0),
820 IS_DIR(sub_mb_type, 0, 1),
827 for (list = h->list_count - 1; list >= 0; list--)
828 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
829 int row = refs[list][ref];
831 Picture *ref_pic = &h->ref_list[list][ref];
832 int ref_field = ref_pic->reference - 1;
833 int ref_field_picture = ref_pic->field_picture;
834 int pic_height = 16 * h->mb_height >> ref_field_picture;
839 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
840 ff_thread_await_progress(&ref_pic->tf,
841 FFMIN((row >> 1) - !(row & 1),
844 ff_thread_await_progress(&ref_pic->tf,
845 FFMIN((row >> 1), pic_height - 1),
847 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
848 ff_thread_await_progress(&ref_pic->tf,
849 FFMIN(row * 2 + ref_field,
852 } else if (FIELD_PICTURE(h)) {
853 ff_thread_await_progress(&ref_pic->tf,
854 FFMIN(row, pic_height - 1),
857 ff_thread_await_progress(&ref_pic->tf,
858 FFMIN(row, pic_height - 1),
865 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
866 int n, int square, int height,
868 uint8_t *dest_y, uint8_t *dest_cb,
870 int src_x_offset, int src_y_offset,
871 qpel_mc_func *qpix_op,
872 h264_chroma_mc_func chroma_op,
873 int pixel_shift, int chroma_idc)
875 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
876 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
877 const int luma_xy = (mx & 3) + ((my & 3) << 2);
878 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
879 uint8_t *src_y = pic->f.data[0] + offset;
880 uint8_t *src_cb, *src_cr;
882 int extra_height = 0;
884 const int full_mx = mx >> 2;
885 const int full_my = my >> 2;
886 const int pic_width = 16 * h->mb_width;
887 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
895 if (full_mx < 0 - extra_width ||
896 full_my < 0 - extra_height ||
897 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
898 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
899 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
900 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
902 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
903 full_my - 2, pic_width, pic_height);
904 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
908 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
910 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
912 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
915 if (chroma_idc == 3 /* yuv444 */) {
916 src_cb = pic->f.data[1] + offset;
918 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
919 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
921 16 + 5, 16 + 5 /*FIXME*/,
922 full_mx - 2, full_my - 2,
923 pic_width, pic_height);
924 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
926 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
928 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
930 src_cr = pic->f.data[2] + offset;
932 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
933 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
935 16 + 5, 16 + 5 /*FIXME*/,
936 full_mx - 2, full_my - 2,
937 pic_width, pic_height);
938 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
940 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
942 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
946 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
947 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
948 // chroma offset when predicting from a field of opposite parity
949 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
950 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
953 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
954 (my >> ysh) * h->mb_uvlinesize;
955 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
956 (my >> ysh) * h->mb_uvlinesize;
959 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb, h->mb_uvlinesize,
960 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
961 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
962 src_cb = h->edge_emu_buffer;
964 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
965 height >> (chroma_idc == 1 /* yuv420 */),
966 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
969 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr, h->mb_uvlinesize,
970 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
971 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
972 src_cr = h->edge_emu_buffer;
974 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
975 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
978 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
979 int height, int delta,
980 uint8_t *dest_y, uint8_t *dest_cb,
982 int x_offset, int y_offset,
983 qpel_mc_func *qpix_put,
984 h264_chroma_mc_func chroma_put,
985 qpel_mc_func *qpix_avg,
986 h264_chroma_mc_func chroma_avg,
987 int list0, int list1,
988 int pixel_shift, int chroma_idc)
990 qpel_mc_func *qpix_op = qpix_put;
991 h264_chroma_mc_func chroma_op = chroma_put;
993 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
994 if (chroma_idc == 3 /* yuv444 */) {
995 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
996 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
997 } else if (chroma_idc == 2 /* yuv422 */) {
998 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
999 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1000 } else { /* yuv420 */
1001 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1002 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1004 x_offset += 8 * h->mb_x;
1005 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1008 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1009 mc_dir_part(h, ref, n, square, height, delta, 0,
1010 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1011 qpix_op, chroma_op, pixel_shift, chroma_idc);
1014 chroma_op = chroma_avg;
1018 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1019 mc_dir_part(h, ref, n, square, height, delta, 1,
1020 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1021 qpix_op, chroma_op, pixel_shift, chroma_idc);
1025 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1026 int height, int delta,
1027 uint8_t *dest_y, uint8_t *dest_cb,
1029 int x_offset, int y_offset,
1030 qpel_mc_func *qpix_put,
1031 h264_chroma_mc_func chroma_put,
1032 h264_weight_func luma_weight_op,
1033 h264_weight_func chroma_weight_op,
1034 h264_biweight_func luma_weight_avg,
1035 h264_biweight_func chroma_weight_avg,
1036 int list0, int list1,
1037 int pixel_shift, int chroma_idc)
1041 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1042 if (chroma_idc == 3 /* yuv444 */) {
1043 chroma_height = height;
1044 chroma_weight_avg = luma_weight_avg;
1045 chroma_weight_op = luma_weight_op;
1046 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1047 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1048 } else if (chroma_idc == 2 /* yuv422 */) {
1049 chroma_height = height;
1050 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1051 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1052 } else { /* yuv420 */
1053 chroma_height = height >> 1;
1054 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1055 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1057 x_offset += 8 * h->mb_x;
1058 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1060 if (list0 && list1) {
1061 /* don't optimize for luma-only case, since B-frames usually
1062 * use implicit weights => chroma too. */
1063 uint8_t *tmp_cb = h->bipred_scratchpad;
1064 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1065 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1066 int refn0 = h->ref_cache[0][scan8[n]];
1067 int refn1 = h->ref_cache[1][scan8[n]];
1069 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1070 dest_y, dest_cb, dest_cr,
1071 x_offset, y_offset, qpix_put, chroma_put,
1072 pixel_shift, chroma_idc);
1073 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1074 tmp_y, tmp_cb, tmp_cr,
1075 x_offset, y_offset, qpix_put, chroma_put,
1076 pixel_shift, chroma_idc);
1078 if (h->use_weight == 2) {
1079 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1080 int weight1 = 64 - weight0;
1081 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1082 height, 5, weight0, weight1, 0);
1083 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1084 chroma_height, 5, weight0, weight1, 0);
1085 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1086 chroma_height, 5, weight0, weight1, 0);
1088 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1089 h->luma_log2_weight_denom,
1090 h->luma_weight[refn0][0][0],
1091 h->luma_weight[refn1][1][0],
1092 h->luma_weight[refn0][0][1] +
1093 h->luma_weight[refn1][1][1]);
1094 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1095 h->chroma_log2_weight_denom,
1096 h->chroma_weight[refn0][0][0][0],
1097 h->chroma_weight[refn1][1][0][0],
1098 h->chroma_weight[refn0][0][0][1] +
1099 h->chroma_weight[refn1][1][0][1]);
1100 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1101 h->chroma_log2_weight_denom,
1102 h->chroma_weight[refn0][0][1][0],
1103 h->chroma_weight[refn1][1][1][0],
1104 h->chroma_weight[refn0][0][1][1] +
1105 h->chroma_weight[refn1][1][1][1]);
1108 int list = list1 ? 1 : 0;
1109 int refn = h->ref_cache[list][scan8[n]];
1110 Picture *ref = &h->ref_list[list][refn];
1111 mc_dir_part(h, ref, n, square, height, delta, list,
1112 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1113 qpix_put, chroma_put, pixel_shift, chroma_idc);
1115 luma_weight_op(dest_y, h->mb_linesize, height,
1116 h->luma_log2_weight_denom,
1117 h->luma_weight[refn][list][0],
1118 h->luma_weight[refn][list][1]);
1119 if (h->use_weight_chroma) {
1120 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1121 h->chroma_log2_weight_denom,
1122 h->chroma_weight[refn][list][0][0],
1123 h->chroma_weight[refn][list][0][1]);
1124 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1125 h->chroma_log2_weight_denom,
1126 h->chroma_weight[refn][list][1][0],
1127 h->chroma_weight[refn][list][1][1]);
1132 static av_always_inline void prefetch_motion(H264Context *h, int list,
1133 int pixel_shift, int chroma_idc)
1135 /* fetch pixels for estimated mv 4 macroblocks ahead
1136 * optimized for 64byte cache lines */
1137 const int refn = h->ref_cache[list][scan8[0]];
1139 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1140 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1141 uint8_t **src = h->ref_list[list][refn].f.data;
1142 int off = (mx << pixel_shift) +
1143 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1144 (64 << pixel_shift);
1145 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1146 if (chroma_idc == 3 /* yuv444 */) {
1147 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1148 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1150 off = ((mx >> 1) << pixel_shift) +
1151 ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
1152 (64 << pixel_shift);
1153 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1158 static void free_tables(H264Context *h, int free_rbsp)
1163 av_freep(&h->intra4x4_pred_mode);
1164 av_freep(&h->chroma_pred_mode_table);
1165 av_freep(&h->cbp_table);
1166 av_freep(&h->mvd_table[0]);
1167 av_freep(&h->mvd_table[1]);
1168 av_freep(&h->direct_table);
1169 av_freep(&h->non_zero_count);
1170 av_freep(&h->slice_table_base);
1171 h->slice_table = NULL;
1172 av_freep(&h->list_counts);
1174 av_freep(&h->mb2b_xy);
1175 av_freep(&h->mb2br_xy);
1177 av_buffer_pool_uninit(&h->qscale_table_pool);
1178 av_buffer_pool_uninit(&h->mb_type_pool);
1179 av_buffer_pool_uninit(&h->motion_val_pool);
1180 av_buffer_pool_uninit(&h->ref_index_pool);
1182 if (free_rbsp && h->DPB) {
1183 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1184 unref_picture(h, &h->DPB[i]);
1186 } else if (h->DPB) {
1187 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1188 h->DPB[i].needs_realloc = 1;
1191 h->cur_pic_ptr = NULL;
1193 for (i = 0; i < MAX_THREADS; i++) {
1194 hx = h->thread_context[i];
1197 av_freep(&hx->top_borders[1]);
1198 av_freep(&hx->top_borders[0]);
1199 av_freep(&hx->bipred_scratchpad);
1200 av_freep(&hx->edge_emu_buffer);
1201 av_freep(&hx->dc_val_base);
1202 av_freep(&hx->me.scratchpad);
1203 av_freep(&hx->er.mb_index2xy);
1204 av_freep(&hx->er.error_status_table);
1205 av_freep(&hx->er.er_temp_buffer);
1206 av_freep(&hx->er.mbintra_table);
1207 av_freep(&hx->er.mbskip_table);
1210 av_freep(&hx->rbsp_buffer[1]);
1211 av_freep(&hx->rbsp_buffer[0]);
1212 hx->rbsp_buffer_size[0] = 0;
1213 hx->rbsp_buffer_size[1] = 0;
1216 av_freep(&h->thread_context[i]);
1220 static void init_dequant8_coeff_table(H264Context *h)
1223 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1225 for (i = 0; i < 6; i++) {
1226 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1227 for (j = 0; j < i; j++)
1228 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1229 64 * sizeof(uint8_t))) {
1230 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1236 for (q = 0; q < max_qp + 1; q++) {
1237 int shift = div6[q];
1239 for (x = 0; x < 64; x++)
1240 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1241 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1242 h->pps.scaling_matrix8[i][x]) << shift;
1247 static void init_dequant4_coeff_table(H264Context *h)
1250 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1251 for (i = 0; i < 6; i++) {
1252 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1253 for (j = 0; j < i; j++)
1254 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1255 16 * sizeof(uint8_t))) {
1256 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1262 for (q = 0; q < max_qp + 1; q++) {
1263 int shift = div6[q] + 2;
1265 for (x = 0; x < 16; x++)
1266 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1267 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1268 h->pps.scaling_matrix4[i][x]) << shift;
1273 static void init_dequant_tables(H264Context *h)
1276 init_dequant4_coeff_table(h);
1277 if (h->pps.transform_8x8_mode)
1278 init_dequant8_coeff_table(h);
1279 if (h->sps.transform_bypass) {
1280 for (i = 0; i < 6; i++)
1281 for (x = 0; x < 16; x++)
1282 h->dequant4_coeff[i][0][x] = 1 << 6;
1283 if (h->pps.transform_8x8_mode)
1284 for (i = 0; i < 6; i++)
1285 for (x = 0; x < 64; x++)
1286 h->dequant8_coeff[i][0][x] = 1 << 6;
1290 int ff_h264_alloc_tables(H264Context *h)
1292 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1293 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
1296 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1297 row_mb_num * 8 * sizeof(uint8_t), fail)
1298 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1299 big_mb_num * 48 * sizeof(uint8_t), fail)
1300 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1301 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1302 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1303 big_mb_num * sizeof(uint16_t), fail)
1304 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1305 big_mb_num * sizeof(uint8_t), fail)
1306 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1307 16 * row_mb_num * sizeof(uint8_t), fail);
1308 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1309 16 * row_mb_num * sizeof(uint8_t), fail);
1310 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1311 4 * big_mb_num * sizeof(uint8_t), fail);
1312 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1313 big_mb_num * sizeof(uint8_t), fail)
1315 memset(h->slice_table_base, -1,
1316 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1317 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1319 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1320 big_mb_num * sizeof(uint32_t), fail);
1321 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1322 big_mb_num * sizeof(uint32_t), fail);
1323 for (y = 0; y < h->mb_height; y++)
1324 for (x = 0; x < h->mb_width; x++) {
1325 const int mb_xy = x + y * h->mb_stride;
1326 const int b_xy = 4 * x + 4 * y * h->b_stride;
1328 h->mb2b_xy[mb_xy] = b_xy;
1329 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1332 if (!h->dequant4_coeff[0])
1333 init_dequant_tables(h);
1336 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1338 return AVERROR(ENOMEM);
1339 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1340 avcodec_get_frame_defaults(&h->DPB[i].f);
1341 avcodec_get_frame_defaults(&h->cur_pic.f);
1348 return AVERROR(ENOMEM);
1352 * Mimic alloc_tables(), but for every context thread.
1354 static void clone_tables(H264Context *dst, H264Context *src, int i)
1356 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1357 dst->non_zero_count = src->non_zero_count;
1358 dst->slice_table = src->slice_table;
1359 dst->cbp_table = src->cbp_table;
1360 dst->mb2b_xy = src->mb2b_xy;
1361 dst->mb2br_xy = src->mb2br_xy;
1362 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1363 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1364 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1365 dst->direct_table = src->direct_table;
1366 dst->list_counts = src->list_counts;
1367 dst->DPB = src->DPB;
1368 dst->cur_pic_ptr = src->cur_pic_ptr;
1369 dst->cur_pic = src->cur_pic;
1370 dst->bipred_scratchpad = NULL;
1371 dst->edge_emu_buffer = NULL;
1372 dst->me.scratchpad = NULL;
1373 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1374 src->sps.chroma_format_idc);
1379 * Allocate buffers which are not shared amongst multiple threads.
1381 static int context_init(H264Context *h)
1383 ERContext *er = &h->er;
1384 int mb_array_size = h->mb_height * h->mb_stride;
1385 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1386 int c_size = h->mb_stride * (h->mb_height + 1);
1387 int yc_size = y_size + 2 * c_size;
1390 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1391 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1392 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1393 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1395 h->ref_cache[0][scan8[5] + 1] =
1396 h->ref_cache[0][scan8[7] + 1] =
1397 h->ref_cache[0][scan8[13] + 1] =
1398 h->ref_cache[1][scan8[5] + 1] =
1399 h->ref_cache[1][scan8[7] + 1] =
1400 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1402 if (CONFIG_ERROR_RESILIENCE) {
1404 er->avctx = h->avctx;
1406 er->decode_mb = h264_er_decode_mb;
1408 er->quarter_sample = 1;
1410 er->mb_num = h->mb_num;
1411 er->mb_width = h->mb_width;
1412 er->mb_height = h->mb_height;
1413 er->mb_stride = h->mb_stride;
1414 er->b8_stride = h->mb_width * 2 + 1;
1416 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1417 fail); // error ressilience code looks cleaner with this
1418 for (y = 0; y < h->mb_height; y++)
1419 for (x = 0; x < h->mb_width; x++)
1420 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1422 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1423 h->mb_stride + h->mb_width;
1425 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1426 mb_array_size * sizeof(uint8_t), fail);
1428 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1429 memset(er->mbintra_table, 1, mb_array_size);
1431 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1433 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1436 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1437 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1438 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1439 er->dc_val[2] = er->dc_val[1] + c_size;
1440 for (i = 0; i < yc_size; i++)
1441 h->dc_val_base[i] = 1024;
1447 return AVERROR(ENOMEM); // free_tables will clean up for us
1450 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1451 int parse_extradata);
1453 int ff_h264_decode_extradata(H264Context *h)
1455 AVCodecContext *avctx = h->avctx;
1458 if (avctx->extradata[0] == 1) {
1459 int i, cnt, nalsize;
1460 unsigned char *p = avctx->extradata;
1464 if (avctx->extradata_size < 7) {
1465 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1466 return AVERROR_INVALIDDATA;
1468 /* sps and pps in the avcC always have length coded with 2 bytes,
1469 * so put a fake nal_length_size = 2 while parsing them */
1470 h->nal_length_size = 2;
1471 // Decode sps from avcC
1472 cnt = *(p + 5) & 0x1f; // Number of sps
1474 for (i = 0; i < cnt; i++) {
1475 nalsize = AV_RB16(p) + 2;
1476 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1477 return AVERROR_INVALIDDATA;
1478 ret = decode_nal_units(h, p, nalsize, 1);
1480 av_log(avctx, AV_LOG_ERROR,
1481 "Decoding sps %d from avcC failed\n", i);
1486 // Decode pps from avcC
1487 cnt = *(p++); // Number of pps
1488 for (i = 0; i < cnt; i++) {
1489 nalsize = AV_RB16(p) + 2;
1490 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1491 return AVERROR_INVALIDDATA;
1492 ret = decode_nal_units(h, p, nalsize, 1);
1494 av_log(avctx, AV_LOG_ERROR,
1495 "Decoding pps %d from avcC failed\n", i);
1500 // Now store right nal length size, that will be used to parse all other nals
1501 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1504 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
1511 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1513 H264Context *h = avctx->priv_data;
1519 h->bit_depth_luma = 8;
1520 h->chroma_format_idc = 1;
1522 ff_h264dsp_init(&h->h264dsp, 8, 1);
1523 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1524 ff_h264qpel_init(&h->h264qpel, 8);
1525 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1527 h->dequant_coeff_pps = -1;
1529 /* needed so that IDCT permutation is known early */
1530 if (CONFIG_ERROR_RESILIENCE)
1531 ff_dsputil_init(&h->dsp, h->avctx);
1532 ff_videodsp_init(&h->vdsp, 8);
1534 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1535 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1537 h->picture_structure = PICT_FRAME;
1538 h->slice_context_count = 1;
1539 h->workaround_bugs = avctx->workaround_bugs;
1540 h->flags = avctx->flags;
1543 // s->decode_mb = ff_h263_decode_mb;
1544 if (!avctx->has_b_frames)
1547 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1549 ff_h264_decode_init_vlc();
1551 ff_init_cabac_states();
1554 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1556 h->thread_context[0] = h;
1557 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1558 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1559 h->last_pocs[i] = INT_MIN;
1560 h->prev_poc_msb = 1 << 16;
1562 ff_h264_reset_sei(h);
1563 if (avctx->codec_id == AV_CODEC_ID_H264) {
1564 if (avctx->ticks_per_frame == 1)
1565 h->avctx->time_base.den *= 2;
1566 avctx->ticks_per_frame = 2;
1569 if (avctx->extradata_size > 0 && avctx->extradata) {
1570 ret = ff_h264_decode_extradata(h);
1575 if (h->sps.bitstream_restriction_flag &&
1576 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1577 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1581 avctx->internal->allocate_progress = 1;
1586 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1587 #undef REBASE_PICTURE
1588 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1589 ((pic && pic >= old_ctx->DPB && \
1590 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1591 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1593 static void copy_picture_range(Picture **to, Picture **from, int count,
1594 H264Context *new_base,
1595 H264Context *old_base)
1599 for (i = 0; i < count; i++) {
1600 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1601 IN_RANGE(from[i], old_base->DPB,
1602 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1604 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1608 static void copy_parameter_set(void **to, void **from, int count, int size)
1612 for (i = 0; i < count; i++) {
1613 if (to[i] && !from[i])
1615 else if (from[i] && !to[i])
1616 to[i] = av_malloc(size);
1619 memcpy(to[i], from[i], size);
1623 static int decode_init_thread_copy(AVCodecContext *avctx)
1625 H264Context *h = avctx->priv_data;
1627 if (!avctx->internal->is_copy)
1629 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1630 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1632 h->context_initialized = 0;
1637 #define copy_fields(to, from, start_field, end_field) \
1638 memcpy(&to->start_field, &from->start_field, \
1639 (char *)&to->end_field - (char *)&to->start_field)
1641 static int h264_slice_header_init(H264Context *, int);
1643 static int h264_set_parameter_from_sps(H264Context *h);
1645 static int decode_update_thread_context(AVCodecContext *dst,
1646 const AVCodecContext *src)
1648 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1649 int inited = h->context_initialized, err = 0;
1650 int context_reinitialized = 0;
1653 if (dst == src || !h1->context_initialized)
1657 (h->width != h1->width ||
1658 h->height != h1->height ||
1659 h->mb_width != h1->mb_width ||
1660 h->mb_height != h1->mb_height ||
1661 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1662 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1663 h->sps.colorspace != h1->sps.colorspace)) {
1665 /* set bits_per_raw_sample to the previous value. the check for changed
1666 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1667 * the current value */
1668 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1670 av_freep(&h->bipred_scratchpad);
1672 h->width = h1->width;
1673 h->height = h1->height;
1674 h->mb_height = h1->mb_height;
1675 h->mb_width = h1->mb_width;
1676 h->mb_num = h1->mb_num;
1677 h->mb_stride = h1->mb_stride;
1678 h->b_stride = h1->b_stride;
1680 if ((err = h264_slice_header_init(h, 1)) < 0) {
1681 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1684 context_reinitialized = 1;
1686 /* update linesize on resize. The decoder doesn't
1687 * necessarily call h264_frame_start in the new thread */
1688 h->linesize = h1->linesize;
1689 h->uvlinesize = h1->uvlinesize;
1691 /* copy block_offset since frame_start may not be called */
1692 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1696 for (i = 0; i < MAX_SPS_COUNT; i++)
1697 av_freep(h->sps_buffers + i);
1699 for (i = 0; i < MAX_PPS_COUNT; i++)
1700 av_freep(h->pps_buffers + i);
1702 memcpy(h, h1, sizeof(*h1));
1703 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1704 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1705 memset(&h->er, 0, sizeof(h->er));
1706 memset(&h->me, 0, sizeof(h->me));
1707 memset(&h->mb, 0, sizeof(h->mb));
1708 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1709 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1710 h->context_initialized = 0;
1712 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1713 avcodec_get_frame_defaults(&h->cur_pic.f);
1714 h->cur_pic.tf.f = &h->cur_pic.f;
1718 h->qscale_table_pool = NULL;
1719 h->mb_type_pool = NULL;
1720 h->ref_index_pool = NULL;
1721 h->motion_val_pool = NULL;
1723 ret = ff_h264_alloc_tables(h);
1725 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1728 ret = context_init(h);
1730 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1734 for (i = 0; i < 2; i++) {
1735 h->rbsp_buffer[i] = NULL;
1736 h->rbsp_buffer_size[i] = 0;
1738 h->bipred_scratchpad = NULL;
1739 h->edge_emu_buffer = NULL;
1741 h->thread_context[0] = h;
1743 h->context_initialized = 1;
1746 h->avctx->coded_height = h1->avctx->coded_height;
1747 h->avctx->coded_width = h1->avctx->coded_width;
1748 h->avctx->width = h1->avctx->width;
1749 h->avctx->height = h1->avctx->height;
1750 h->coded_picture_number = h1->coded_picture_number;
1751 h->first_field = h1->first_field;
1752 h->picture_structure = h1->picture_structure;
1753 h->qscale = h1->qscale;
1754 h->droppable = h1->droppable;
1755 h->data_partitioning = h1->data_partitioning;
1756 h->low_delay = h1->low_delay;
1758 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1759 unref_picture(h, &h->DPB[i]);
1760 if (h1->DPB[i].f.data[0] &&
1761 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1765 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1766 unref_picture(h, &h->cur_pic);
1767 if ((ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1770 h->workaround_bugs = h1->workaround_bugs;
1771 h->low_delay = h1->low_delay;
1772 h->droppable = h1->droppable;
1774 /* frame_start may not be called for the next thread (if it's decoding
1775 * a bottom field) so this has to be allocated here */
1776 err = alloc_scratch_buffers(h, h1->linesize);
1780 // extradata/NAL handling
1781 h->is_avc = h1->is_avc;
1784 copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
1785 MAX_SPS_COUNT, sizeof(SPS));
1787 copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
1788 MAX_PPS_COUNT, sizeof(PPS));
1791 // Dequantization matrices
1792 // FIXME these are big - can they be only copied when PPS changes?
1793 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1795 for (i = 0; i < 6; i++)
1796 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1797 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1799 for (i = 0; i < 6; i++)
1800 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1801 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1803 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1806 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1809 copy_fields(h, h1, short_ref, cabac_init_idc);
1811 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1812 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1813 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1814 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1816 h->last_slice_type = h1->last_slice_type;
1818 if (context_reinitialized)
1819 h264_set_parameter_from_sps(h);
1821 if (!h->cur_pic_ptr)
1824 if (!h->droppable) {
1825 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1826 h->prev_poc_msb = h->poc_msb;
1827 h->prev_poc_lsb = h->poc_lsb;
1829 h->prev_frame_num_offset = h->frame_num_offset;
1830 h->prev_frame_num = h->frame_num;
1831 h->outputed_poc = h->next_outputed_poc;
1836 static int h264_frame_start(H264Context *h)
1840 const int pixel_shift = h->pixel_shift;
1842 release_unused_pictures(h, 1);
1843 h->cur_pic_ptr = NULL;
1845 i = find_unused_picture(h);
1847 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1852 pic->reference = h->droppable ? 0 : h->picture_structure;
1853 pic->f.coded_picture_number = h->coded_picture_number++;
1854 pic->field_picture = h->picture_structure != PICT_FRAME;
1856 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1858 * See decode_nal_units().
1860 pic->f.key_frame = 0;
1861 pic->mmco_reset = 0;
1863 if ((ret = alloc_picture(h, pic)) < 0)
1866 h->cur_pic_ptr = pic;
1867 unref_picture(h, &h->cur_pic);
1868 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1871 if (CONFIG_ERROR_RESILIENCE)
1872 ff_er_frame_start(&h->er);
1874 assert(h->linesize && h->uvlinesize);
1876 for (i = 0; i < 16; i++) {
1877 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1878 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1880 for (i = 0; i < 16; i++) {
1881 h->block_offset[16 + i] =
1882 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1883 h->block_offset[48 + 16 + i] =
1884 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1887 /* can't be in alloc_tables because linesize isn't known there.
1888 * FIXME: redo bipred weight to not require extra buffer? */
1889 for (i = 0; i < h->slice_context_count; i++)
1890 if (h->thread_context[i]) {
1891 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1896 /* Some macroblocks can be accessed before they're available in case
1897 * of lost slices, MBAFF or threading. */
1898 memset(h->slice_table, -1,
1899 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1901 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1902 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1904 /* We mark the current picture as non-reference after allocating it, so
1905 * that if we break out due to an error it can be released automatically
1906 * in the next ff_MPV_frame_start().
1908 h->cur_pic_ptr->reference = 0;
1910 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1912 h->next_output_pic = NULL;
1914 assert(h->cur_pic_ptr->long_ref == 0);
1920 * Run setup operations that must be run after slice header decoding.
1921 * This includes finding the next displayed frame.
1923 * @param h h264 master context
1924 * @param setup_finished enough NALs have been read that we can call
1925 * ff_thread_finish_setup()
1927 static void decode_postinit(H264Context *h, int setup_finished)
1929 Picture *out = h->cur_pic_ptr;
1930 Picture *cur = h->cur_pic_ptr;
1931 int i, pics, out_of_order, out_idx;
1932 int invalid = 0, cnt = 0;
1934 h->cur_pic_ptr->f.pict_type = h->pict_type;
1936 if (h->next_output_pic)
1939 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1940 /* FIXME: if we have two PAFF fields in one packet, we can't start
1941 * the next thread here. If we have one field per packet, we can.
1942 * The check in decode_nal_units() is not good enough to find this
1943 * yet, so we assume the worst for now. */
1944 // if (setup_finished)
1945 // ff_thread_finish_setup(h->avctx);
1949 cur->f.interlaced_frame = 0;
1950 cur->f.repeat_pict = 0;
1952 /* Signal interlacing information externally. */
1953 /* Prioritize picture timing SEI information over used
1954 * decoding process if it exists. */
1956 if (h->sps.pic_struct_present_flag) {
1957 switch (h->sei_pic_struct) {
1958 case SEI_PIC_STRUCT_FRAME:
1960 case SEI_PIC_STRUCT_TOP_FIELD:
1961 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1962 cur->f.interlaced_frame = 1;
1964 case SEI_PIC_STRUCT_TOP_BOTTOM:
1965 case SEI_PIC_STRUCT_BOTTOM_TOP:
1966 if (FIELD_OR_MBAFF_PICTURE(h))
1967 cur->f.interlaced_frame = 1;
1969 // try to flag soft telecine progressive
1970 cur->f.interlaced_frame = h->prev_interlaced_frame;
1972 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1973 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1974 /* Signal the possibility of telecined film externally
1975 * (pic_struct 5,6). From these hints, let the applications
1976 * decide if they apply deinterlacing. */
1977 cur->f.repeat_pict = 1;
1979 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1980 cur->f.repeat_pict = 2;
1982 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1983 cur->f.repeat_pict = 4;
1987 if ((h->sei_ct_type & 3) &&
1988 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1989 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
1991 /* Derive interlacing flag from used decoding process. */
1992 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
1994 h->prev_interlaced_frame = cur->f.interlaced_frame;
1996 if (cur->field_poc[0] != cur->field_poc[1]) {
1997 /* Derive top_field_first from field pocs. */
1998 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2000 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2001 /* Use picture timing SEI information. Even if it is a
2002 * information of a past frame, better than nothing. */
2003 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2004 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2005 cur->f.top_field_first = 1;
2007 cur->f.top_field_first = 0;
2009 /* Most likely progressive */
2010 cur->f.top_field_first = 0;
2014 // FIXME do something with unavailable reference frames
2016 /* Sort B-frames into display order */
2018 if (h->sps.bitstream_restriction_flag &&
2019 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2020 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2024 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2025 !h->sps.bitstream_restriction_flag) {
2026 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2031 while (h->delayed_pic[pics])
2034 assert(pics <= MAX_DELAYED_PIC_COUNT);
2036 h->delayed_pic[pics++] = cur;
2037 if (cur->reference == 0)
2038 cur->reference = DELAYED_PIC_REF;
2040 /* Frame reordering. This code takes pictures from coding order and sorts
2041 * them by their incremental POC value into display order. It supports POC
2042 * gaps, MMCO reset codes and random resets.
2043 * A "display group" can start either with a IDR frame (f.key_frame = 1),
2044 * and/or can be closed down with a MMCO reset code. In sequences where
2045 * there is no delay, we can't detect that (since the frame was already
2046 * output to the user), so we also set h->mmco_reset to detect the MMCO
2048 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
2049 * we increase the delay between input and output. All frames affected by
2050 * the lag (e.g. those that should have been output before another frame
2051 * that we already returned to the user) will be dropped. This is a bug
2052 * that we will fix later. */
2053 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2054 cnt += out->poc < h->last_pocs[i];
2055 invalid += out->poc == INT_MIN;
2057 if (!h->mmco_reset && !cur->f.key_frame &&
2058 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
2061 h->delayed_pic[pics - 2]->mmco_reset = 2;
2063 if (h->mmco_reset || cur->f.key_frame) {
2064 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2065 h->last_pocs[i] = INT_MIN;
2067 invalid = MAX_DELAYED_PIC_COUNT;
2069 out = h->delayed_pic[0];
2071 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
2072 h->delayed_pic[i] &&
2073 !h->delayed_pic[i - 1]->mmco_reset &&
2074 !h->delayed_pic[i]->f.key_frame;
2076 if (h->delayed_pic[i]->poc < out->poc) {
2077 out = h->delayed_pic[i];
2080 if (h->avctx->has_b_frames == 0 &&
2081 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
2082 h->next_outputed_poc = INT_MIN;
2083 out_of_order = !out->f.key_frame && !h->mmco_reset &&
2084 (out->poc < h->next_outputed_poc);
2086 if (h->sps.bitstream_restriction_flag &&
2087 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
2088 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
2089 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
2090 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
2091 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
2094 } else if (h->low_delay &&
2095 ((h->next_outputed_poc != INT_MIN &&
2096 out->poc > h->next_outputed_poc + 2) ||
2097 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
2099 h->avctx->has_b_frames++;
2102 if (pics > h->avctx->has_b_frames) {
2103 out->reference &= ~DELAYED_PIC_REF;
2104 // for frame threading, the owner must be the second field's thread or
2105 // else the first thread can release the picture and reuse it unsafely
2106 for (i = out_idx; h->delayed_pic[i]; i++)
2107 h->delayed_pic[i] = h->delayed_pic[i + 1];
2109 memmove(h->last_pocs, &h->last_pocs[1],
2110 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
2111 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
2112 if (!out_of_order && pics > h->avctx->has_b_frames) {
2113 h->next_output_pic = out;
2114 if (out->mmco_reset) {
2116 h->next_outputed_poc = out->poc;
2117 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
2119 h->next_outputed_poc = INT_MIN;
2122 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
2123 h->next_outputed_poc = INT_MIN;
2125 h->next_outputed_poc = out->poc;
2130 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
2133 if (setup_finished && !h->avctx->hwaccel)
2134 ff_thread_finish_setup(h->avctx);
2137 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2138 uint8_t *src_cb, uint8_t *src_cr,
2139 int linesize, int uvlinesize,
2142 uint8_t *top_border;
2144 const int pixel_shift = h->pixel_shift;
2145 int chroma444 = CHROMA444(h);
2146 int chroma422 = CHROMA422(h);
2149 src_cb -= uvlinesize;
2150 src_cr -= uvlinesize;
2152 if (!simple && FRAME_MBAFF(h)) {
2155 top_border = h->top_borders[0][h->mb_x];
2156 AV_COPY128(top_border, src_y + 15 * linesize);
2158 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2159 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2162 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2163 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2164 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2165 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2167 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2168 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2170 } else if (chroma422) {
2172 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2173 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2175 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2176 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2180 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2181 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2183 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2184 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2189 } else if (MB_MBAFF(h)) {
2195 top_border = h->top_borders[top_idx][h->mb_x];
2196 /* There are two lines saved, the line above the top macroblock
2197 * of a pair, and the line above the bottom macroblock. */
2198 AV_COPY128(top_border, src_y + 16 * linesize);
2200 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2202 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2205 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2206 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2207 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2208 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2210 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2211 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2213 } else if (chroma422) {
2215 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2216 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2218 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2219 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2223 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2224 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2226 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2227 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2233 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2234 uint8_t *src_cb, uint8_t *src_cr,
2235 int linesize, int uvlinesize,
2236 int xchg, int chroma444,
2237 int simple, int pixel_shift)
2239 int deblock_topleft;
2242 uint8_t *top_border_m1;
2243 uint8_t *top_border;
2245 if (!simple && FRAME_MBAFF(h)) {
2250 top_idx = MB_MBAFF(h) ? 0 : 1;
2254 if (h->deblocking_filter == 2) {
2255 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2256 deblock_top = h->top_type;
2258 deblock_topleft = (h->mb_x > 0);
2259 deblock_top = (h->mb_y > !!MB_FIELD(h));
2262 src_y -= linesize + 1 + pixel_shift;
2263 src_cb -= uvlinesize + 1 + pixel_shift;
2264 src_cr -= uvlinesize + 1 + pixel_shift;
2266 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2267 top_border = h->top_borders[top_idx][h->mb_x];
2269 #define XCHG(a, b, xchg) \
2270 if (pixel_shift) { \
2272 AV_SWAP64(b + 0, a + 0); \
2273 AV_SWAP64(b + 8, a + 8); \
2283 if (deblock_topleft) {
2284 XCHG(top_border_m1 + (8 << pixel_shift),
2285 src_y - (7 << pixel_shift), 1);
2287 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2288 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2289 if (h->mb_x + 1 < h->mb_width) {
2290 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2291 src_y + (17 << pixel_shift), 1);
2294 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2296 if (deblock_topleft) {
2297 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2298 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2300 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2301 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2302 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2303 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2304 if (h->mb_x + 1 < h->mb_width) {
2305 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2306 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2310 if (deblock_topleft) {
2311 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2312 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2314 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2315 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2321 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2324 if (high_bit_depth) {
2325 return AV_RN32A(((int32_t *)mb) + index);
2327 return AV_RN16A(mb + index);
2330 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2331 int index, int value)
2333 if (high_bit_depth) {
2334 AV_WN32A(((int32_t *)mb) + index, value);
2336 AV_WN16A(mb + index, value);
2339 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2340 int mb_type, int is_h264,
2342 int transform_bypass,
2346 uint8_t *dest_y, int p)
2348 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2349 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2351 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2352 block_offset += 16 * p;
2353 if (IS_INTRA4x4(mb_type)) {
2354 if (IS_8x8DCT(mb_type)) {
2355 if (transform_bypass) {
2357 idct_add = h->h264dsp.h264_add_pixels8_clear;
2359 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2360 idct_add = h->h264dsp.h264_idct8_add;
2362 for (i = 0; i < 16; i += 4) {
2363 uint8_t *const ptr = dest_y + block_offset[i];
2364 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2365 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2366 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2368 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2369 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2370 (h->topright_samples_available << i) & 0x4000, linesize);
2372 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2373 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2375 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2380 if (transform_bypass) {
2382 idct_add = h->h264dsp.h264_add_pixels4_clear;
2384 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2385 idct_add = h->h264dsp.h264_idct_add;
2387 for (i = 0; i < 16; i++) {
2388 uint8_t *const ptr = dest_y + block_offset[i];
2389 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2391 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2392 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2397 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2398 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2399 assert(h->mb_y || linesize <= block_offset[i]);
2400 if (!topright_avail) {
2402 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2403 topright = (uint8_t *)&tr_high;
2405 tr = ptr[3 - linesize] * 0x01010101u;
2406 topright = (uint8_t *)&tr;
2409 topright = ptr + (4 << pixel_shift) - linesize;
2413 h->hpc.pred4x4[dir](ptr, topright, linesize);
2414 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2417 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2418 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2420 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2421 } else if (CONFIG_SVQ3_DECODER)
2422 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2428 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2430 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2431 if (!transform_bypass)
2432 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2434 h->dequant4_coeff[p][qscale][0]);
2436 static const uint8_t dc_mapping[16] = {
2437 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2438 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2439 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2440 10 * 16, 11 * 16, 14 * 16, 15 * 16
2442 for (i = 0; i < 16; i++)
2443 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2444 pixel_shift, dc_mapping[i],
2445 dctcoef_get(h->mb_luma_dc[p],
2449 } else if (CONFIG_SVQ3_DECODER)
2450 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2451 h->mb_luma_dc[p], qscale);
2455 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2456 int is_h264, int simple,
2457 int transform_bypass,
2461 uint8_t *dest_y, int p)
2463 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2465 block_offset += 16 * p;
2466 if (!IS_INTRA4x4(mb_type)) {
2468 if (IS_INTRA16x16(mb_type)) {
2469 if (transform_bypass) {
2470 if (h->sps.profile_idc == 244 &&
2471 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2472 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2473 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2474 h->mb + (p * 256 << pixel_shift),
2477 for (i = 0; i < 16; i++)
2478 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2479 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2480 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2481 h->mb + (i * 16 + p * 256 << pixel_shift),
2485 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2486 h->mb + (p * 256 << pixel_shift),
2488 h->non_zero_count_cache + p * 5 * 8);
2490 } else if (h->cbp & 15) {
2491 if (transform_bypass) {
2492 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2493 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2494 : h->h264dsp.h264_add_pixels4_clear;
2495 for (i = 0; i < 16; i += di)
2496 if (h->non_zero_count_cache[scan8[i + p * 16]])
2497 idct_add(dest_y + block_offset[i],
2498 h->mb + (i * 16 + p * 256 << pixel_shift),
2501 if (IS_8x8DCT(mb_type))
2502 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2503 h->mb + (p * 256 << pixel_shift),
2505 h->non_zero_count_cache + p * 5 * 8);
2507 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2508 h->mb + (p * 256 << pixel_shift),
2510 h->non_zero_count_cache + p * 5 * 8);
2513 } else if (CONFIG_SVQ3_DECODER) {
2514 for (i = 0; i < 16; i++)
2515 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2516 // FIXME benchmark weird rule, & below
2517 uint8_t *const ptr = dest_y + block_offset[i];
2518 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2519 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2527 #include "h264_mb_template.c"
2531 #include "h264_mb_template.c"
2535 #include "h264_mb_template.c"
2537 void ff_h264_hl_decode_mb(H264Context *h)
2539 const int mb_xy = h->mb_xy;
2540 const int mb_type = h->cur_pic.mb_type[mb_xy];
2541 int is_complex = CONFIG_SMALL || h->is_complex ||
2542 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2545 if (is_complex || h->pixel_shift)
2546 hl_decode_mb_444_complex(h);
2548 hl_decode_mb_444_simple_8(h);
2549 } else if (is_complex) {
2550 hl_decode_mb_complex(h);
2551 } else if (h->pixel_shift) {
2552 hl_decode_mb_simple_16(h);
2554 hl_decode_mb_simple_8(h);
2557 int ff_pred_weight_table(H264Context *h)
2560 int luma_def, chroma_def;
2563 h->use_weight_chroma = 0;
2564 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2565 if (h->sps.chroma_format_idc)
2566 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2567 luma_def = 1 << h->luma_log2_weight_denom;
2568 chroma_def = 1 << h->chroma_log2_weight_denom;
2570 for (list = 0; list < 2; list++) {
2571 h->luma_weight_flag[list] = 0;
2572 h->chroma_weight_flag[list] = 0;
2573 for (i = 0; i < h->ref_count[list]; i++) {
2574 int luma_weight_flag, chroma_weight_flag;
2576 luma_weight_flag = get_bits1(&h->gb);
2577 if (luma_weight_flag) {
2578 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2579 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2580 if (h->luma_weight[i][list][0] != luma_def ||
2581 h->luma_weight[i][list][1] != 0) {
2583 h->luma_weight_flag[list] = 1;
2586 h->luma_weight[i][list][0] = luma_def;
2587 h->luma_weight[i][list][1] = 0;
2590 if (h->sps.chroma_format_idc) {
2591 chroma_weight_flag = get_bits1(&h->gb);
2592 if (chroma_weight_flag) {
2594 for (j = 0; j < 2; j++) {
2595 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2596 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2597 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2598 h->chroma_weight[i][list][j][1] != 0) {
2599 h->use_weight_chroma = 1;
2600 h->chroma_weight_flag[list] = 1;
2605 for (j = 0; j < 2; j++) {
2606 h->chroma_weight[i][list][j][0] = chroma_def;
2607 h->chroma_weight[i][list][j][1] = 0;
2612 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2615 h->use_weight = h->use_weight || h->use_weight_chroma;
2620 * Initialize implicit_weight table.
2621 * @param field 0/1 initialize the weight for interlaced MBAFF
2622 * -1 initializes the rest
2624 static void implicit_weight_table(H264Context *h, int field)
2626 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2628 for (i = 0; i < 2; i++) {
2629 h->luma_weight_flag[i] = 0;
2630 h->chroma_weight_flag[i] = 0;
2634 if (h->picture_structure == PICT_FRAME) {
2635 cur_poc = h->cur_pic_ptr->poc;
2637 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2639 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2640 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2642 h->use_weight_chroma = 0;
2646 ref_count0 = h->ref_count[0];
2647 ref_count1 = h->ref_count[1];
2649 cur_poc = h->cur_pic_ptr->field_poc[field];
2651 ref_count0 = 16 + 2 * h->ref_count[0];
2652 ref_count1 = 16 + 2 * h->ref_count[1];
2656 h->use_weight_chroma = 2;
2657 h->luma_log2_weight_denom = 5;
2658 h->chroma_log2_weight_denom = 5;
2660 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2661 int poc0 = h->ref_list[0][ref0].poc;
2662 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2664 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2665 int poc1 = h->ref_list[1][ref1].poc;
2666 int td = av_clip(poc1 - poc0, -128, 127);
2668 int tb = av_clip(cur_poc - poc0, -128, 127);
2669 int tx = (16384 + (FFABS(td) >> 1)) / td;
2670 int dist_scale_factor = (tb * tx + 32) >> 8;
2671 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2672 w = 64 - dist_scale_factor;
2676 h->implicit_weight[ref0][ref1][0] =
2677 h->implicit_weight[ref0][ref1][1] = w;
2679 h->implicit_weight[ref0][ref1][field] = w;
2686 * instantaneous decoder refresh.
2688 static void idr(H264Context *h)
2690 ff_h264_remove_all_refs(h);
2691 h->prev_frame_num = 0;
2692 h->prev_frame_num_offset = 0;
2694 h->prev_poc_lsb = 0;
2697 /* forget old pics after a seek */
2698 static void flush_change(H264Context *h)
2701 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2702 h->last_pocs[i] = INT_MIN;
2703 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2704 h->prev_interlaced_frame = 1;
2707 h->cur_pic_ptr->reference = 0;
2709 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2710 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2711 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2712 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2713 ff_h264_reset_sei(h);
2716 /* forget old pics after a seek */
2717 static void flush_dpb(AVCodecContext *avctx)
2719 H264Context *h = avctx->priv_data;
2722 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2723 if (h->delayed_pic[i])
2724 h->delayed_pic[i]->reference = 0;
2725 h->delayed_pic[i] = NULL;
2731 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2732 unref_picture(h, &h->DPB[i]);
2733 h->cur_pic_ptr = NULL;
2734 unref_picture(h, &h->cur_pic);
2736 h->mb_x = h->mb_y = 0;
2738 h->parse_context.state = -1;
2739 h->parse_context.frame_start_found = 0;
2740 h->parse_context.overread = 0;
2741 h->parse_context.overread_index = 0;
2742 h->parse_context.index = 0;
2743 h->parse_context.last_index = 0;
2746 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2748 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2751 h->frame_num_offset = h->prev_frame_num_offset;
2752 if (h->frame_num < h->prev_frame_num)
2753 h->frame_num_offset += max_frame_num;
2755 if (h->sps.poc_type == 0) {
2756 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2758 if (h->poc_lsb < h->prev_poc_lsb &&
2759 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2760 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2761 else if (h->poc_lsb > h->prev_poc_lsb &&
2762 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2763 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2765 h->poc_msb = h->prev_poc_msb;
2767 field_poc[1] = h->poc_msb + h->poc_lsb;
2768 if (h->picture_structure == PICT_FRAME)
2769 field_poc[1] += h->delta_poc_bottom;
2770 } else if (h->sps.poc_type == 1) {
2771 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2774 if (h->sps.poc_cycle_length != 0)
2775 abs_frame_num = h->frame_num_offset + h->frame_num;
2779 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2782 expected_delta_per_poc_cycle = 0;
2783 for (i = 0; i < h->sps.poc_cycle_length; i++)
2784 // FIXME integrate during sps parse
2785 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2787 if (abs_frame_num > 0) {
2788 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2789 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2791 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2792 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2793 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2797 if (h->nal_ref_idc == 0)
2798 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2800 field_poc[0] = expectedpoc + h->delta_poc[0];
2801 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2803 if (h->picture_structure == PICT_FRAME)
2804 field_poc[1] += h->delta_poc[1];
2806 int poc = 2 * (h->frame_num_offset + h->frame_num);
2808 if (!h->nal_ref_idc)
2815 if (h->picture_structure != PICT_BOTTOM_FIELD)
2816 pic_field_poc[0] = field_poc[0];
2817 if (h->picture_structure != PICT_TOP_FIELD)
2818 pic_field_poc[1] = field_poc[1];
2819 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2825 * initialize scan tables
2827 static void init_scan_tables(H264Context *h)
2830 for (i = 0; i < 16; i++) {
2831 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2832 h->zigzag_scan[i] = T(zigzag_scan[i]);
2833 h->field_scan[i] = T(field_scan[i]);
2836 for (i = 0; i < 64; i++) {
2837 #define T(x) (x >> 3) | ((x & 7) << 3)
2838 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2839 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2840 h->field_scan8x8[i] = T(field_scan8x8[i]);
2841 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2844 if (h->sps.transform_bypass) { // FIXME same ugly
2845 h->zigzag_scan_q0 = zigzag_scan;
2846 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2847 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2848 h->field_scan_q0 = field_scan;
2849 h->field_scan8x8_q0 = field_scan8x8;
2850 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2852 h->zigzag_scan_q0 = h->zigzag_scan;
2853 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2854 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2855 h->field_scan_q0 = h->field_scan;
2856 h->field_scan8x8_q0 = h->field_scan8x8;
2857 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2861 static int field_end(H264Context *h, int in_setup)
2863 AVCodecContext *const avctx = h->avctx;
2867 if (!in_setup && !h->droppable)
2868 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2869 h->picture_structure == PICT_BOTTOM_FIELD);
2871 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2872 if (!h->droppable) {
2873 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2874 h->prev_poc_msb = h->poc_msb;
2875 h->prev_poc_lsb = h->poc_lsb;
2877 h->prev_frame_num_offset = h->frame_num_offset;
2878 h->prev_frame_num = h->frame_num;
2879 h->outputed_poc = h->next_outputed_poc;
2882 if (avctx->hwaccel) {
2883 if (avctx->hwaccel->end_frame(avctx) < 0)
2884 av_log(avctx, AV_LOG_ERROR,
2885 "hardware accelerator failed to decode picture\n");
2889 * FIXME: Error handling code does not seem to support interlaced
2890 * when slices span multiple rows
2891 * The ff_er_add_slice calls don't work right for bottom
2892 * fields; they cause massive erroneous error concealing
2893 * Error marking covers both fields (top and bottom).
2894 * This causes a mismatched s->error_count
2895 * and a bad error table. Further, the error count goes to
2896 * INT_MAX when called for bottom field, because mb_y is
2897 * past end by one (callers fault) and resync_mb_y != 0
2898 * causes problems for the first MB line, too.
2900 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h)) {
2901 h->er.cur_pic = h->cur_pic_ptr;
2902 h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
2903 h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
2904 ff_er_frame_end(&h->er);
2908 h->current_slice = 0;
2914 * Replicate H264 "master" context to thread contexts.
2916 static int clone_slice(H264Context *dst, H264Context *src)
2918 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2919 dst->cur_pic_ptr = src->cur_pic_ptr;
2920 dst->cur_pic = src->cur_pic;
2921 dst->linesize = src->linesize;
2922 dst->uvlinesize = src->uvlinesize;
2923 dst->first_field = src->first_field;
2925 dst->prev_poc_msb = src->prev_poc_msb;
2926 dst->prev_poc_lsb = src->prev_poc_lsb;
2927 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2928 dst->prev_frame_num = src->prev_frame_num;
2929 dst->short_ref_count = src->short_ref_count;
2931 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2932 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2933 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2935 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2936 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2942 * Compute profile from profile_idc and constraint_set?_flags.
2946 * @return profile as defined by FF_PROFILE_H264_*
2948 int ff_h264_get_profile(SPS *sps)
2950 int profile = sps->profile_idc;
2952 switch (sps->profile_idc) {
2953 case FF_PROFILE_H264_BASELINE:
2954 // constraint_set1_flag set to 1
2955 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2957 case FF_PROFILE_H264_HIGH_10:
2958 case FF_PROFILE_H264_HIGH_422:
2959 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2960 // constraint_set3_flag set to 1
2961 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
2968 static int h264_set_parameter_from_sps(H264Context *h)
2970 if (h->flags & CODEC_FLAG_LOW_DELAY ||
2971 (h->sps.bitstream_restriction_flag &&
2972 !h->sps.num_reorder_frames)) {
2973 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
2974 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
2975 "Reenabling low delay requires a codec flush.\n");
2980 if (h->avctx->has_b_frames < 2)
2981 h->avctx->has_b_frames = !h->low_delay;
2983 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
2984 avpriv_request_sample(h->avctx,
2985 "Different chroma and luma bit depth");
2986 return AVERROR_PATCHWELCOME;
2989 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
2990 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
2991 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
2992 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
2993 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
2994 h->pixel_shift = h->sps.bit_depth_luma > 8;
2996 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
2997 h->sps.chroma_format_idc);
2998 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
2999 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3000 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3001 h->sps.chroma_format_idc);
3002 if (CONFIG_ERROR_RESILIENCE)
3003 ff_dsputil_init(&h->dsp, h->avctx);
3004 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3006 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3007 h->sps.bit_depth_luma);
3008 return AVERROR_INVALIDDATA;
3014 static enum AVPixelFormat get_pixel_format(H264Context *h)
3016 switch (h->sps.bit_depth_luma) {
3019 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3020 return AV_PIX_FMT_GBRP9;
3022 return AV_PIX_FMT_YUV444P9;
3023 } else if (CHROMA422(h))
3024 return AV_PIX_FMT_YUV422P9;
3026 return AV_PIX_FMT_YUV420P9;
3030 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3031 return AV_PIX_FMT_GBRP10;
3033 return AV_PIX_FMT_YUV444P10;
3034 } else if (CHROMA422(h))
3035 return AV_PIX_FMT_YUV422P10;
3037 return AV_PIX_FMT_YUV420P10;
3041 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3042 return AV_PIX_FMT_GBRP;
3044 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3045 : AV_PIX_FMT_YUV444P;
3046 } else if (CHROMA422(h)) {
3047 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3048 : AV_PIX_FMT_YUV422P;
3050 return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
3051 h->avctx->codec->pix_fmts :
3052 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3053 h264_hwaccel_pixfmt_list_jpeg_420 :
3054 h264_hwaccel_pixfmt_list_420);
3058 av_log(h->avctx, AV_LOG_ERROR,
3059 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3060 return AVERROR_INVALIDDATA;
3064 /* export coded and cropped frame dimensions to AVCodecContext */
3065 static int init_dimensions(H264Context *h)
3067 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3068 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3070 /* handle container cropping */
3072 FFALIGN(h->avctx->width, 16) == h->width &&
3073 FFALIGN(h->avctx->height, 16) == h->height) {
3074 width = h->avctx->width;
3075 height = h->avctx->height;
3078 if (width <= 0 || height <= 0) {
3079 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3081 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3082 return AVERROR_INVALIDDATA;
3084 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3085 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3092 h->avctx->coded_width = h->width;
3093 h->avctx->coded_height = h->height;
3094 h->avctx->width = width;
3095 h->avctx->height = height;
3100 static int h264_slice_header_init(H264Context *h, int reinit)
3102 int nb_slices = (HAVE_THREADS &&
3103 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3104 h->avctx->thread_count : 1;
3107 h->avctx->sample_aspect_ratio = h->sps.sar;
3108 av_assert0(h->avctx->sample_aspect_ratio.den);
3109 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3110 &h->chroma_x_shift, &h->chroma_y_shift);
3112 if (h->sps.timing_info_present_flag) {
3113 int64_t den = h->sps.time_scale;
3114 if (h->x264_build < 44U)
3116 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3117 h->sps.num_units_in_tick, den, 1 << 30);
3120 h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
3125 h->prev_interlaced_frame = 1;
3127 init_scan_tables(h);
3128 ret = ff_h264_alloc_tables(h);
3130 av_log(h->avctx, AV_LOG_ERROR,
3131 "Could not allocate memory for h264\n");
3135 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3138 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3140 max_slices = MAX_THREADS;
3141 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3142 " reducing to %d\n", nb_slices, max_slices);
3143 nb_slices = max_slices;
3145 h->slice_context_count = nb_slices;
3147 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3148 ret = context_init(h);
3150 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3154 for (i = 1; i < h->slice_context_count; i++) {
3156 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3157 c->avctx = h->avctx;
3160 c->h264dsp = h->h264dsp;
3161 c->h264qpel = h->h264qpel;
3162 c->h264chroma = h->h264chroma;
3165 c->pixel_shift = h->pixel_shift;
3166 c->width = h->width;
3167 c->height = h->height;
3168 c->linesize = h->linesize;
3169 c->uvlinesize = h->uvlinesize;
3170 c->chroma_x_shift = h->chroma_x_shift;
3171 c->chroma_y_shift = h->chroma_y_shift;
3172 c->qscale = h->qscale;
3173 c->droppable = h->droppable;
3174 c->data_partitioning = h->data_partitioning;
3175 c->low_delay = h->low_delay;
3176 c->mb_width = h->mb_width;
3177 c->mb_height = h->mb_height;
3178 c->mb_stride = h->mb_stride;
3179 c->mb_num = h->mb_num;
3180 c->flags = h->flags;
3181 c->workaround_bugs = h->workaround_bugs;
3182 c->pict_type = h->pict_type;
3184 init_scan_tables(c);
3185 clone_tables(c, h, i);
3186 c->context_initialized = 1;
3189 for (i = 0; i < h->slice_context_count; i++)
3190 if ((ret = context_init(h->thread_context[i])) < 0) {
3191 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3196 h->context_initialized = 1;
3201 int ff_set_ref_count(H264Context *h)
3203 int num_ref_idx_active_override_flag, max_refs;
3205 // set defaults, might be overridden a few lines later
3206 h->ref_count[0] = h->pps.ref_count[0];
3207 h->ref_count[1] = h->pps.ref_count[1];
3209 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3210 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3211 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3212 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3214 if (num_ref_idx_active_override_flag) {
3215 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3216 if (h->ref_count[0] < 1)
3217 return AVERROR_INVALIDDATA;
3218 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3219 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3220 if (h->ref_count[1] < 1)
3221 return AVERROR_INVALIDDATA;
3225 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3231 h->ref_count[0] = h->ref_count[1] = 0;
3234 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
3236 if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
3237 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
3238 h->ref_count[0] = h->ref_count[1] = 0;
3239 return AVERROR_INVALIDDATA;
3246 * Decode a slice header.
3247 * This will also call ff_MPV_common_init() and frame_start() as needed.
3249 * @param h h264context
3250 * @param h0 h264 master context (differs from 'h' when doing sliced based
3251 * parallel decoding)
3253 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3255 static int decode_slice_header(H264Context *h, H264Context *h0)
3257 unsigned int first_mb_in_slice;
3258 unsigned int pps_id;
3260 unsigned int slice_type, tmp, i, j;
3261 int default_ref_list_done = 0;
3262 int last_pic_structure, last_pic_droppable;
3263 int needs_reinit = 0;
3264 int field_pic_flag, bottom_field_flag;
3266 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3267 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3269 first_mb_in_slice = get_ue_golomb(&h->gb);
3271 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3272 if (h0->current_slice && FIELD_PICTURE(h)) {
3276 h0->current_slice = 0;
3277 if (!h0->first_field) {
3278 if (h->cur_pic_ptr && !h->droppable) {
3279 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3280 h->picture_structure == PICT_BOTTOM_FIELD);
3282 h->cur_pic_ptr = NULL;
3286 slice_type = get_ue_golomb_31(&h->gb);
3287 if (slice_type > 9) {
3288 av_log(h->avctx, AV_LOG_ERROR,
3289 "slice type too large (%d) at %d %d\n",
3290 h->slice_type, h->mb_x, h->mb_y);
3291 return AVERROR_INVALIDDATA;
3293 if (slice_type > 4) {
3295 h->slice_type_fixed = 1;
3297 h->slice_type_fixed = 0;
3299 slice_type = golomb_to_pict_type[slice_type];
3300 if (slice_type == AV_PICTURE_TYPE_I ||
3301 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3302 default_ref_list_done = 1;
3304 h->slice_type = slice_type;
3305 h->slice_type_nos = slice_type & 3;
3307 // to make a few old functions happy, it's wrong though
3308 h->pict_type = h->slice_type;
3310 pps_id = get_ue_golomb(&h->gb);
3311 if (pps_id >= MAX_PPS_COUNT) {
3312 av_log(h->avctx, AV_LOG_ERROR, "pps_id out of range\n");
3313 return AVERROR_INVALIDDATA;
3315 if (!h0->pps_buffers[pps_id]) {
3316 av_log(h->avctx, AV_LOG_ERROR,
3317 "non-existing PPS %u referenced\n",
3319 return AVERROR_INVALIDDATA;
3321 h->pps = *h0->pps_buffers[pps_id];
3323 if (!h0->sps_buffers[h->pps.sps_id]) {
3324 av_log(h->avctx, AV_LOG_ERROR,
3325 "non-existing SPS %u referenced\n",
3327 return AVERROR_INVALIDDATA;
3330 if (h->pps.sps_id != h->current_sps_id ||
3331 h0->sps_buffers[h->pps.sps_id]->new) {
3332 h0->sps_buffers[h->pps.sps_id]->new = 0;
3334 h->current_sps_id = h->pps.sps_id;
3335 h->sps = *h0->sps_buffers[h->pps.sps_id];
3337 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3338 h->chroma_format_idc != h->sps.chroma_format_idc) {
3339 h->bit_depth_luma = h->sps.bit_depth_luma;
3340 h->chroma_format_idc = h->sps.chroma_format_idc;
3343 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3347 h->avctx->profile = ff_h264_get_profile(&h->sps);
3348 h->avctx->level = h->sps.level_idc;
3349 h->avctx->refs = h->sps.ref_frame_count;
3351 if (h->mb_width != h->sps.mb_width ||
3352 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
3355 h->mb_width = h->sps.mb_width;
3356 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3357 h->mb_num = h->mb_width * h->mb_height;
3358 h->mb_stride = h->mb_width + 1;
3360 h->b_stride = h->mb_width * 4;
3362 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3364 h->width = 16 * h->mb_width;
3365 h->height = 16 * h->mb_height;
3367 ret = init_dimensions(h);
3371 if (h->sps.video_signal_type_present_flag) {
3372 h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
3374 if (h->sps.colour_description_present_flag) {
3375 if (h->avctx->colorspace != h->sps.colorspace)
3377 h->avctx->color_primaries = h->sps.color_primaries;
3378 h->avctx->color_trc = h->sps.color_trc;
3379 h->avctx->colorspace = h->sps.colorspace;
3383 if (h->context_initialized &&
3384 (h->width != h->avctx->coded_width ||
3385 h->height != h->avctx->coded_height ||
3388 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3389 "slice %d\n", h0->current_slice + 1);
3390 return AVERROR_INVALIDDATA;
3395 if ((ret = get_pixel_format(h)) < 0)
3397 h->avctx->pix_fmt = ret;
3399 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3400 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3402 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3403 av_log(h->avctx, AV_LOG_ERROR,
3404 "h264_slice_header_init() failed\n");
3408 if (!h->context_initialized) {
3410 av_log(h->avctx, AV_LOG_ERROR,
3411 "Cannot (re-)initialize context during parallel decoding.\n");
3412 return AVERROR_PATCHWELCOME;
3415 if ((ret = get_pixel_format(h)) < 0)
3417 h->avctx->pix_fmt = ret;
3419 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3420 av_log(h->avctx, AV_LOG_ERROR,
3421 "h264_slice_header_init() failed\n");
3426 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3427 h->dequant_coeff_pps = pps_id;
3428 init_dequant_tables(h);
3431 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3434 h->mb_aff_frame = 0;
3435 last_pic_structure = h0->picture_structure;
3436 last_pic_droppable = h0->droppable;
3437 h->droppable = h->nal_ref_idc == 0;
3438 if (h->sps.frame_mbs_only_flag) {
3439 h->picture_structure = PICT_FRAME;
3441 field_pic_flag = get_bits1(&h->gb);
3442 if (field_pic_flag) {
3443 bottom_field_flag = get_bits1(&h->gb);
3444 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3446 h->picture_structure = PICT_FRAME;
3447 h->mb_aff_frame = h->sps.mb_aff;
3450 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3452 if (h0->current_slice != 0) {
3453 if (last_pic_structure != h->picture_structure ||
3454 last_pic_droppable != h->droppable) {
3455 av_log(h->avctx, AV_LOG_ERROR,
3456 "Changing field mode (%d -> %d) between slices is not allowed\n",
3457 last_pic_structure, h->picture_structure);
3458 h->picture_structure = last_pic_structure;
3459 h->droppable = last_pic_droppable;
3460 return AVERROR_INVALIDDATA;
3461 } else if (!h0->cur_pic_ptr) {
3462 av_log(h->avctx, AV_LOG_ERROR,
3463 "unset cur_pic_ptr on %d. slice\n",
3464 h0->current_slice + 1);
3465 return AVERROR_INVALIDDATA;
3468 /* Shorten frame num gaps so we don't have to allocate reference
3469 * frames just to throw them away */
3470 if (h->frame_num != h->prev_frame_num) {
3471 int unwrap_prev_frame_num = h->prev_frame_num;
3472 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3474 if (unwrap_prev_frame_num > h->frame_num)
3475 unwrap_prev_frame_num -= max_frame_num;
3477 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3478 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3479 if (unwrap_prev_frame_num < 0)
3480 unwrap_prev_frame_num += max_frame_num;
3482 h->prev_frame_num = unwrap_prev_frame_num;
3486 /* See if we have a decoded first field looking for a pair...
3487 * Here, we're using that to see if we should mark previously
3488 * decode frames as "finished".
3489 * We have to do that before the "dummy" in-between frame allocation,
3490 * since that can modify s->current_picture_ptr. */
3491 if (h0->first_field) {
3492 assert(h0->cur_pic_ptr);
3493 assert(h0->cur_pic_ptr->f.data[0]);
3494 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3496 /* figure out if we have a complementary field pair */
3497 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3498 /* Previous field is unmatched. Don't display it, but let it
3499 * remain for reference if marked as such. */
3500 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3501 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3502 last_pic_structure == PICT_TOP_FIELD);
3505 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3506 /* This and previous field were reference, but had
3507 * different frame_nums. Consider this field first in
3508 * pair. Throw away previous field except for reference
3510 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3511 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3512 last_pic_structure == PICT_TOP_FIELD);
3515 /* Second field in complementary pair */
3516 if (!((last_pic_structure == PICT_TOP_FIELD &&
3517 h->picture_structure == PICT_BOTTOM_FIELD) ||
3518 (last_pic_structure == PICT_BOTTOM_FIELD &&
3519 h->picture_structure == PICT_TOP_FIELD))) {
3520 av_log(h->avctx, AV_LOG_ERROR,
3521 "Invalid field mode combination %d/%d\n",
3522 last_pic_structure, h->picture_structure);
3523 h->picture_structure = last_pic_structure;
3524 h->droppable = last_pic_droppable;
3525 return AVERROR_INVALIDDATA;
3526 } else if (last_pic_droppable != h->droppable) {
3527 avpriv_request_sample(h->avctx,
3528 "Found reference and non-reference fields in the same frame, which");
3529 h->picture_structure = last_pic_structure;
3530 h->droppable = last_pic_droppable;
3531 return AVERROR_PATCHWELCOME;
3537 while (h->frame_num != h->prev_frame_num &&
3538 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3539 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3540 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3541 h->frame_num, h->prev_frame_num);
3542 ret = h264_frame_start(h);
3545 h->prev_frame_num++;
3546 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3547 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3548 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3549 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3550 ret = ff_generate_sliding_window_mmcos(h, 1);
3551 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3553 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3554 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3556 /* Error concealment: If a ref is missing, copy the previous ref
3558 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3559 * many assumptions about there being no actual duplicates.
3560 * FIXME: This does not copy padding for out-of-frame motion
3561 * vectors. Given we are concealing a lost frame, this probably
3562 * is not noticeable by comparison, but it should be fixed. */
3563 if (h->short_ref_count) {
3565 av_image_copy(h->short_ref[0]->f.data,
3566 h->short_ref[0]->f.linesize,
3567 (const uint8_t **)prev->f.data,
3572 h->short_ref[0]->poc = prev->poc + 2;
3574 h->short_ref[0]->frame_num = h->prev_frame_num;
3578 /* See if we have a decoded first field looking for a pair...
3579 * We're using that to see whether to continue decoding in that
3580 * frame, or to allocate a new one. */
3581 if (h0->first_field) {
3582 assert(h0->cur_pic_ptr);
3583 assert(h0->cur_pic_ptr->f.data[0]);
3584 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3586 /* figure out if we have a complementary field pair */
3587 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3588 /* Previous field is unmatched. Don't display it, but let it
3589 * remain for reference if marked as such. */
3590 h0->cur_pic_ptr = NULL;
3591 h0->first_field = FIELD_PICTURE(h);
3593 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3594 /* This and the previous field had different frame_nums.
3595 * Consider this field first in pair. Throw away previous
3596 * one except for reference purposes. */
3597 h0->first_field = 1;
3598 h0->cur_pic_ptr = NULL;
3600 /* Second field in complementary pair */
3601 h0->first_field = 0;
3605 /* Frame or first field in a potentially complementary pair */
3606 h0->first_field = FIELD_PICTURE(h);
3609 if (!FIELD_PICTURE(h) || h0->first_field) {
3610 if (h264_frame_start(h) < 0) {
3611 h0->first_field = 0;
3612 return AVERROR_INVALIDDATA;
3615 release_unused_pictures(h, 0);
3618 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3621 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3623 assert(h->mb_num == h->mb_width * h->mb_height);
3624 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3625 first_mb_in_slice >= h->mb_num) {
3626 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3627 return AVERROR_INVALIDDATA;
3629 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3630 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3631 FIELD_OR_MBAFF_PICTURE(h);
3632 if (h->picture_structure == PICT_BOTTOM_FIELD)
3633 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3634 assert(h->mb_y < h->mb_height);
3636 if (h->picture_structure == PICT_FRAME) {
3637 h->curr_pic_num = h->frame_num;
3638 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3640 h->curr_pic_num = 2 * h->frame_num + 1;
3641 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3644 if (h->nal_unit_type == NAL_IDR_SLICE)
3645 get_ue_golomb(&h->gb); /* idr_pic_id */
3647 if (h->sps.poc_type == 0) {
3648 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3650 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3651 h->delta_poc_bottom = get_se_golomb(&h->gb);
3654 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3655 h->delta_poc[0] = get_se_golomb(&h->gb);
3657 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3658 h->delta_poc[1] = get_se_golomb(&h->gb);
3661 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3663 if (h->pps.redundant_pic_cnt_present)
3664 h->redundant_pic_count = get_ue_golomb(&h->gb);
3666 ret = ff_set_ref_count(h);
3670 if (!default_ref_list_done)
3671 ff_h264_fill_default_ref_list(h);
3673 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3674 ret = ff_h264_decode_ref_pic_list_reordering(h);
3676 h->ref_count[1] = h->ref_count[0] = 0;
3681 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3682 (h->pps.weighted_bipred_idc == 1 &&
3683 h->slice_type_nos == AV_PICTURE_TYPE_B))
3684 ff_pred_weight_table(h);
3685 else if (h->pps.weighted_bipred_idc == 2 &&
3686 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3687 implicit_weight_table(h, -1);
3690 for (i = 0; i < 2; i++) {
3691 h->luma_weight_flag[i] = 0;
3692 h->chroma_weight_flag[i] = 0;
3696 // If frame-mt is enabled, only update mmco tables for the first slice
3697 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3698 // or h->mmco, which will cause ref list mix-ups and decoding errors
3699 // further down the line. This may break decoding if the first slice is
3700 // corrupt, thus we only do this if frame-mt is enabled.
3701 if (h->nal_ref_idc) {
3702 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3703 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3704 h0->current_slice == 0);
3705 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3706 return AVERROR_INVALIDDATA;
3709 if (FRAME_MBAFF(h)) {
3710 ff_h264_fill_mbaff_ref_list(h);
3712 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3713 implicit_weight_table(h, 0);
3714 implicit_weight_table(h, 1);
3718 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3719 ff_h264_direct_dist_scale_factor(h);
3720 ff_h264_direct_ref_list_init(h);
3722 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3723 tmp = get_ue_golomb_31(&h->gb);
3725 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3726 return AVERROR_INVALIDDATA;
3728 h->cabac_init_idc = tmp;
3731 h->last_qscale_diff = 0;
3732 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3733 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3734 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3735 return AVERROR_INVALIDDATA;
3738 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3739 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3740 // FIXME qscale / qp ... stuff
3741 if (h->slice_type == AV_PICTURE_TYPE_SP)
3742 get_bits1(&h->gb); /* sp_for_switch_flag */
3743 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3744 h->slice_type == AV_PICTURE_TYPE_SI)
3745 get_se_golomb(&h->gb); /* slice_qs_delta */
3747 h->deblocking_filter = 1;
3748 h->slice_alpha_c0_offset = 52;
3749 h->slice_beta_offset = 52;
3750 if (h->pps.deblocking_filter_parameters_present) {
3751 tmp = get_ue_golomb_31(&h->gb);
3753 av_log(h->avctx, AV_LOG_ERROR,
3754 "deblocking_filter_idc %u out of range\n", tmp);
3755 return AVERROR_INVALIDDATA;
3757 h->deblocking_filter = tmp;
3758 if (h->deblocking_filter < 2)
3759 h->deblocking_filter ^= 1; // 1<->0
3761 if (h->deblocking_filter) {
3762 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3763 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3764 if (h->slice_alpha_c0_offset > 104U ||
3765 h->slice_beta_offset > 104U) {
3766 av_log(h->avctx, AV_LOG_ERROR,
3767 "deblocking filter parameters %d %d out of range\n",
3768 h->slice_alpha_c0_offset, h->slice_beta_offset);
3769 return AVERROR_INVALIDDATA;
3774 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3775 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3776 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3777 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3778 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3779 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3780 h->nal_ref_idc == 0))
3781 h->deblocking_filter = 0;
3783 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3784 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3785 /* Cheat slightly for speed:
3786 * Do not bother to deblock across slices. */
3787 h->deblocking_filter = 2;
3789 h0->max_contexts = 1;
3790 if (!h0->single_decode_warning) {
3791 av_log(h->avctx, AV_LOG_INFO,
3792 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3793 h0->single_decode_warning = 1;
3796 av_log(h->avctx, AV_LOG_ERROR,
3797 "Deblocking switched inside frame.\n");
3802 h->qp_thresh = 15 + 52 -
3803 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3805 h->pps.chroma_qp_index_offset[0],
3806 h->pps.chroma_qp_index_offset[1]) +
3807 6 * (h->sps.bit_depth_luma - 8);
3809 h0->last_slice_type = slice_type;
3810 h->slice_num = ++h0->current_slice;
3811 if (h->slice_num >= MAX_SLICES) {
3812 av_log(h->avctx, AV_LOG_ERROR,
3813 "Too many slices, increase MAX_SLICES and recompile\n");
3816 for (j = 0; j < 2; j++) {
3818 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3819 for (i = 0; i < 16; i++) {
3821 if (j < h->list_count && i < h->ref_count[j] &&
3822 h->ref_list[j][i].f.buf[0]) {
3824 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
3825 for (k = 0; k < h->short_ref_count; k++)
3826 if (h->short_ref[k]->f.buf[0]->buffer == buf) {
3830 for (k = 0; k < h->long_ref_count; k++)
3831 if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
3832 id_list[i] = h->short_ref_count + k;
3840 for (i = 0; i < 16; i++)
3841 ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
3843 ref2frm[18 + 1] = -1;
3844 for (i = 16; i < 48; i++)
3845 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3846 (h->ref_list[j][i].reference & 3);
3849 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
3850 av_log(h->avctx, AV_LOG_DEBUG,
3851 "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
3853 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3855 av_get_picture_type_char(h->slice_type),
3856 h->slice_type_fixed ? " fix" : "",
3857 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3858 pps_id, h->frame_num,
3859 h->cur_pic_ptr->field_poc[0],
3860 h->cur_pic_ptr->field_poc[1],
3861 h->ref_count[0], h->ref_count[1],
3863 h->deblocking_filter,
3864 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3866 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3867 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3873 int ff_h264_get_slice_type(const H264Context *h)
3875 switch (h->slice_type) {
3876 case AV_PICTURE_TYPE_P:
3878 case AV_PICTURE_TYPE_B:
3880 case AV_PICTURE_TYPE_I:
3882 case AV_PICTURE_TYPE_SP:
3884 case AV_PICTURE_TYPE_SI:
3887 return AVERROR_INVALIDDATA;
3891 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3892 int mb_type, int top_xy,
3893 int left_xy[LEFT_MBS],
3895 int left_type[LEFT_MBS],
3896 int mb_xy, int list)
3898 int b_stride = h->b_stride;
3899 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3900 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3901 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3902 if (USES_LIST(top_type, list)) {
3903 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3904 const int b8_xy = 4 * top_xy + 2;
3905 int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
3906 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
3907 ref_cache[0 - 1 * 8] =
3908 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
3909 ref_cache[2 - 1 * 8] =
3910 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
3912 AV_ZERO128(mv_dst - 1 * 8);
3913 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3916 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3917 if (USES_LIST(left_type[LTOP], list)) {
3918 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3919 const int b8_xy = 4 * left_xy[LTOP] + 1;
3920 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
3921 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
3922 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
3923 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
3924 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
3926 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
3927 ref_cache[-1 + 16] =
3928 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
3930 AV_ZERO32(mv_dst - 1 + 0);
3931 AV_ZERO32(mv_dst - 1 + 8);
3932 AV_ZERO32(mv_dst - 1 + 16);
3933 AV_ZERO32(mv_dst - 1 + 24);
3936 ref_cache[-1 + 16] =
3937 ref_cache[-1 + 24] = LIST_NOT_USED;
3942 if (!USES_LIST(mb_type, list)) {
3943 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3944 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3945 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3946 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3947 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3952 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
3953 int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
3954 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3955 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3956 AV_WN32A(&ref_cache[0 * 8], ref01);
3957 AV_WN32A(&ref_cache[1 * 8], ref01);
3958 AV_WN32A(&ref_cache[2 * 8], ref23);
3959 AV_WN32A(&ref_cache[3 * 8], ref23);
3963 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
3964 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3965 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
3966 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
3967 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
3973 * @return non zero if the loop filter can be skipped
3975 static int fill_filter_caches(H264Context *h, int mb_type)
3977 const int mb_xy = h->mb_xy;
3978 int top_xy, left_xy[LEFT_MBS];
3979 int top_type, left_type[LEFT_MBS];
3983 top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
3985 /* Wow, what a mess, why didn't they simplify the interlacing & intra
3986 * stuff, I can't imagine that these complex rules are worth it. */
3988 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
3989 if (FRAME_MBAFF(h)) {
3990 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
3991 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
3993 if (left_mb_field_flag != curr_mb_field_flag)
3994 left_xy[LTOP] -= h->mb_stride;
3996 if (curr_mb_field_flag)
3997 top_xy += h->mb_stride &
3998 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
3999 if (left_mb_field_flag != curr_mb_field_flag)
4000 left_xy[LBOT] += h->mb_stride;
4004 h->top_mb_xy = top_xy;
4005 h->left_mb_xy[LTOP] = left_xy[LTOP];
4006 h->left_mb_xy[LBOT] = left_xy[LBOT];
4008 /* For sufficiently low qp, filtering wouldn't do anything.
4009 * This is a conservative estimate: could also check beta_offset
4010 * and more accurate chroma_qp. */
4011 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4012 int qp = h->cur_pic.qscale_table[mb_xy];
4013 if (qp <= qp_thresh &&
4014 (left_xy[LTOP] < 0 ||
4015 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4017 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4018 if (!FRAME_MBAFF(h))
4020 if ((left_xy[LTOP] < 0 ||
4021 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4022 (top_xy < h->mb_stride ||
4023 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4028 top_type = h->cur_pic.mb_type[top_xy];
4029 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4030 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4031 if (h->deblocking_filter == 2) {
4032 if (h->slice_table[top_xy] != h->slice_num)
4034 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4035 left_type[LTOP] = left_type[LBOT] = 0;
4037 if (h->slice_table[top_xy] == 0xFFFF)
4039 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4040 left_type[LTOP] = left_type[LBOT] = 0;
4042 h->top_type = top_type;
4043 h->left_type[LTOP] = left_type[LTOP];
4044 h->left_type[LBOT] = left_type[LBOT];
4046 if (IS_INTRA(mb_type))
4049 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4050 top_type, left_type, mb_xy, 0);
4051 if (h->list_count == 2)
4052 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4053 top_type, left_type, mb_xy, 1);
4055 nnz = h->non_zero_count[mb_xy];
4056 nnz_cache = h->non_zero_count_cache;
4057 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4058 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4059 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4060 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4061 h->cbp = h->cbp_table[mb_xy];
4064 nnz = h->non_zero_count[top_xy];
4065 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4068 if (left_type[LTOP]) {
4069 nnz = h->non_zero_count[left_xy[LTOP]];
4070 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4071 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4072 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4073 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4076 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4077 * from what the loop filter needs */
4078 if (!CABAC(h) && h->pps.transform_8x8_mode) {
4079 if (IS_8x8DCT(top_type)) {
4080 nnz_cache[4 + 8 * 0] =
4081 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4082 nnz_cache[6 + 8 * 0] =
4083 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4085 if (IS_8x8DCT(left_type[LTOP])) {
4086 nnz_cache[3 + 8 * 1] =
4087 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4089 if (IS_8x8DCT(left_type[LBOT])) {
4090 nnz_cache[3 + 8 * 3] =
4091 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4094 if (IS_8x8DCT(mb_type)) {
4095 nnz_cache[scan8[0]] =
4096 nnz_cache[scan8[1]] =
4097 nnz_cache[scan8[2]] =
4098 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4100 nnz_cache[scan8[0 + 4]] =
4101 nnz_cache[scan8[1 + 4]] =
4102 nnz_cache[scan8[2 + 4]] =
4103 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4105 nnz_cache[scan8[0 + 8]] =
4106 nnz_cache[scan8[1 + 8]] =
4107 nnz_cache[scan8[2 + 8]] =
4108 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4110 nnz_cache[scan8[0 + 12]] =
4111 nnz_cache[scan8[1 + 12]] =
4112 nnz_cache[scan8[2 + 12]] =
4113 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4120 static void loop_filter(H264Context *h, int start_x, int end_x)
4122 uint8_t *dest_y, *dest_cb, *dest_cr;
4123 int linesize, uvlinesize, mb_x, mb_y;
4124 const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4125 const int old_slice_type = h->slice_type;
4126 const int pixel_shift = h->pixel_shift;
4127 const int block_h = 16 >> h->chroma_y_shift;
4129 if (h->deblocking_filter) {
4130 for (mb_x = start_x; mb_x < end_x; mb_x++)
4131 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4133 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4134 h->slice_num = h->slice_table[mb_xy];
4135 mb_type = h->cur_pic.mb_type[mb_xy];
4136 h->list_count = h->list_counts[mb_xy];
4140 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4144 dest_y = h->cur_pic.f.data[0] +
4145 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4146 dest_cb = h->cur_pic.f.data[1] +
4147 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4148 mb_y * h->uvlinesize * block_h;
4149 dest_cr = h->cur_pic.f.data[2] +
4150 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4151 mb_y * h->uvlinesize * block_h;
4152 // FIXME simplify above
4155 linesize = h->mb_linesize = h->linesize * 2;
4156 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4157 if (mb_y & 1) { // FIXME move out of this function?
4158 dest_y -= h->linesize * 15;
4159 dest_cb -= h->uvlinesize * (block_h - 1);
4160 dest_cr -= h->uvlinesize * (block_h - 1);
4163 linesize = h->mb_linesize = h->linesize;
4164 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4166 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4168 if (fill_filter_caches(h, mb_type))
4170 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4171 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4173 if (FRAME_MBAFF(h)) {
4174 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4175 linesize, uvlinesize);
4177 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4178 dest_cr, linesize, uvlinesize);
4182 h->slice_type = old_slice_type;
4184 h->mb_y = end_mb_y - FRAME_MBAFF(h);
4185 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4186 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4189 static void predict_field_decoding_flag(H264Context *h)
4191 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4192 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4193 h->cur_pic.mb_type[mb_xy - 1] :
4194 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4195 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4196 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4200 * Draw edges and report progress for the last MB row.
4202 static void decode_finish_row(H264Context *h)
4204 int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4205 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4206 int height = 16 << FRAME_MBAFF(h);
4207 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4209 if (h->deblocking_filter) {
4210 if ((top + height) >= pic_height)
4211 height += deblock_border;
4212 top -= deblock_border;
4215 if (top >= pic_height || (top + height) < 0)
4218 height = FFMIN(height, pic_height - top);
4220 height = top + height;
4224 ff_h264_draw_horiz_band(h, top, height);
4229 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4230 h->picture_structure == PICT_BOTTOM_FIELD);
4233 static void er_add_slice(H264Context *h, int startx, int starty,
4234 int endx, int endy, int status)
4236 #if CONFIG_ERROR_RESILIENCE
4237 ERContext *er = &h->er;
4239 er->ref_count = h->ref_count[0];
4240 ff_er_add_slice(er, startx, starty, endx, endy, status);
4244 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4246 H264Context *h = *(void **)arg;
4247 int lf_x_start = h->mb_x;
4249 h->mb_skip_run = -1;
4251 h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4252 avctx->codec_id != AV_CODEC_ID_H264 ||
4253 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4257 align_get_bits(&h->gb);
4260 ff_init_cabac_decoder(&h->cabac,
4261 h->gb.buffer + get_bits_count(&h->gb) / 8,
4262 (get_bits_left(&h->gb) + 7) / 8);
4264 ff_h264_init_cabac_states(h);
4268 int ret = ff_h264_decode_mb_cabac(h);
4270 // STOP_TIMER("decode_mb_cabac")
4273 ff_h264_hl_decode_mb(h);
4275 // FIXME optimal? or let mb_decode decode 16x32 ?
4276 if (ret >= 0 && FRAME_MBAFF(h)) {
4279 ret = ff_h264_decode_mb_cabac(h);
4282 ff_h264_hl_decode_mb(h);
4285 eos = get_cabac_terminate(&h->cabac);
4287 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4288 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4289 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4290 h->mb_y, ER_MB_END);
4291 if (h->mb_x >= lf_x_start)
4292 loop_filter(h, lf_x_start, h->mb_x + 1);
4295 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4296 av_log(h->avctx, AV_LOG_ERROR,
4297 "error while decoding MB %d %d, bytestream (%td)\n",
4299 h->cabac.bytestream_end - h->cabac.bytestream);
4300 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4301 h->mb_y, ER_MB_ERROR);
4302 return AVERROR_INVALIDDATA;
4305 if (++h->mb_x >= h->mb_width) {
4306 loop_filter(h, lf_x_start, h->mb_x);
4307 h->mb_x = lf_x_start = 0;
4308 decode_finish_row(h);
4310 if (FIELD_OR_MBAFF_PICTURE(h)) {
4312 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4313 predict_field_decoding_flag(h);
4317 if (eos || h->mb_y >= h->mb_height) {
4318 tprintf(h->avctx, "slice end %d %d\n",
4319 get_bits_count(&h->gb), h->gb.size_in_bits);
4320 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4321 h->mb_y, ER_MB_END);
4322 if (h->mb_x > lf_x_start)
4323 loop_filter(h, lf_x_start, h->mb_x);
4329 int ret = ff_h264_decode_mb_cavlc(h);
4332 ff_h264_hl_decode_mb(h);
4334 // FIXME optimal? or let mb_decode decode 16x32 ?
4335 if (ret >= 0 && FRAME_MBAFF(h)) {
4337 ret = ff_h264_decode_mb_cavlc(h);
4340 ff_h264_hl_decode_mb(h);
4345 av_log(h->avctx, AV_LOG_ERROR,
4346 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4347 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4348 h->mb_y, ER_MB_ERROR);
4352 if (++h->mb_x >= h->mb_width) {
4353 loop_filter(h, lf_x_start, h->mb_x);
4354 h->mb_x = lf_x_start = 0;
4355 decode_finish_row(h);
4357 if (FIELD_OR_MBAFF_PICTURE(h)) {
4359 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4360 predict_field_decoding_flag(h);
4362 if (h->mb_y >= h->mb_height) {
4363 tprintf(h->avctx, "slice end %d %d\n",
4364 get_bits_count(&h->gb), h->gb.size_in_bits);
4366 if (get_bits_left(&h->gb) == 0) {
4367 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4368 h->mb_x - 1, h->mb_y,
4373 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4374 h->mb_x - 1, h->mb_y,
4377 return AVERROR_INVALIDDATA;
4382 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4383 tprintf(h->avctx, "slice end %d %d\n",
4384 get_bits_count(&h->gb), h->gb.size_in_bits);
4386 if (get_bits_left(&h->gb) == 0) {
4387 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4388 h->mb_x - 1, h->mb_y,
4390 if (h->mb_x > lf_x_start)
4391 loop_filter(h, lf_x_start, h->mb_x);
4395 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4396 h->mb_y, ER_MB_ERROR);
4398 return AVERROR_INVALIDDATA;
4406 * Call decode_slice() for each context.
4408 * @param h h264 master context
4409 * @param context_count number of contexts to execute
4411 static int execute_decode_slices(H264Context *h, int context_count)
4413 AVCodecContext *const avctx = h->avctx;
4417 if (h->avctx->hwaccel)
4419 if (context_count == 1) {
4420 return decode_slice(avctx, &h);
4422 for (i = 1; i < context_count; i++) {
4423 hx = h->thread_context[i];
4424 hx->er.error_count = 0;
4427 avctx->execute(avctx, decode_slice, h->thread_context,
4428 NULL, context_count, sizeof(void *));
4430 /* pull back stuff from slices to master context */
4431 hx = h->thread_context[context_count - 1];
4434 h->droppable = hx->droppable;
4435 h->picture_structure = hx->picture_structure;
4436 for (i = 1; i < context_count; i++)
4437 h->er.error_count += h->thread_context[i]->er.error_count;
4443 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4444 int parse_extradata)
4446 AVCodecContext *const avctx = h->avctx;
4447 H264Context *hx; ///< thread context
4451 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4452 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4456 h->max_contexts = h->slice_context_count;
4457 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4458 h->current_slice = 0;
4459 if (!h->first_field)
4460 h->cur_pic_ptr = NULL;
4461 ff_h264_reset_sei(h);
4464 for (; pass <= 1; pass++) {
4467 next_avc = h->is_avc ? 0 : buf_size;
4477 if (buf_index >= next_avc) {
4478 if (buf_index >= buf_size - h->nal_length_size)
4481 for (i = 0; i < h->nal_length_size; i++)
4482 nalsize = (nalsize << 8) | buf[buf_index++];
4483 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4484 av_log(h->avctx, AV_LOG_ERROR,
4485 "AVC: nal size %d\n", nalsize);
4488 next_avc = buf_index + nalsize;
4490 // start code prefix search
4491 for (; buf_index + 3 < next_avc; buf_index++)
4492 // This should always succeed in the first iteration.
4493 if (buf[buf_index] == 0 &&
4494 buf[buf_index + 1] == 0 &&
4495 buf[buf_index + 2] == 1)
4498 if (buf_index + 3 >= buf_size) {
4499 buf_index = buf_size;
4504 if (buf_index >= next_avc)
4508 hx = h->thread_context[context_count];
4510 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4511 &consumed, next_avc - buf_index);
4512 if (ptr == NULL || dst_length < 0) {
4516 i = buf_index + consumed;
4517 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4518 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4519 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4520 h->workaround_bugs |= FF_BUG_TRUNCATED;
4522 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4523 while (ptr[dst_length - 1] == 0 && dst_length > 0)
4525 bit_length = !dst_length ? 0
4527 decode_rbsp_trailing(h, ptr + dst_length - 1));
4529 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4530 av_log(h->avctx, AV_LOG_DEBUG,
4531 "NAL %d at %d/%d length %d\n",
4532 hx->nal_unit_type, buf_index, buf_size, dst_length);
4534 if (h->is_avc && (nalsize != consumed) && nalsize)
4535 av_log(h->avctx, AV_LOG_DEBUG,
4536 "AVC: Consumed only %d bytes instead of %d\n",
4539 buf_index += consumed;
4543 /* packets can sometimes contain multiple PPS/SPS,
4544 * e.g. two PAFF field pictures in one packet, or a demuxer
4545 * which splits NALs strangely if so, when frame threading we
4546 * can't start the next thread until we've read all of them */
4547 switch (hx->nal_unit_type) {
4550 nals_needed = nal_index;
4555 init_get_bits(&hx->gb, ptr, bit_length);
4556 if (!get_ue_golomb(&hx->gb))
4557 nals_needed = nal_index;
4562 if (avctx->skip_frame >= AVDISCARD_NONREF &&
4563 h->nal_ref_idc == 0 &&
4564 h->nal_unit_type != NAL_SEI)
4568 /* Ignore every NAL unit type except PPS and SPS during extradata
4569 * parsing. Decoding slices is not possible in codec init
4571 if (parse_extradata && HAVE_THREADS &&
4572 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
4573 (hx->nal_unit_type != NAL_PPS &&
4574 hx->nal_unit_type != NAL_SPS)) {
4575 if (hx->nal_unit_type < NAL_AUD ||
4576 hx->nal_unit_type > NAL_AUXILIARY_SLICE)
4577 av_log(avctx, AV_LOG_INFO,
4578 "Ignoring NAL unit %d during extradata parsing\n",
4580 hx->nal_unit_type = NAL_FF_IGNORE;
4583 switch (hx->nal_unit_type) {
4585 if (h->nal_unit_type != NAL_IDR_SLICE) {
4586 av_log(h->avctx, AV_LOG_ERROR,
4587 "Invalid mix of idr and non-idr slices\n");
4591 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4593 init_get_bits(&hx->gb, ptr, bit_length);
4595 hx->inter_gb_ptr = &hx->gb;
4596 hx->data_partitioning = 0;
4598 if ((err = decode_slice_header(hx, h)))
4601 h->cur_pic_ptr->f.key_frame |=
4602 (hx->nal_unit_type == NAL_IDR_SLICE) ||
4603 (h->sei_recovery_frame_cnt >= 0);
4605 if (h->current_slice == 1) {
4606 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4607 decode_postinit(h, nal_index >= nals_needed);
4609 if (h->avctx->hwaccel &&
4610 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4614 if (hx->redundant_pic_count == 0 &&
4615 (avctx->skip_frame < AVDISCARD_NONREF ||
4617 (avctx->skip_frame < AVDISCARD_BIDIR ||
4618 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4619 (avctx->skip_frame < AVDISCARD_NONKEY ||
4620 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4621 avctx->skip_frame < AVDISCARD_ALL) {
4622 if (avctx->hwaccel) {
4623 ret = avctx->hwaccel->decode_slice(avctx,
4624 &buf[buf_index - consumed],
4633 init_get_bits(&hx->gb, ptr, bit_length);
4635 hx->inter_gb_ptr = NULL;
4637 if ((err = decode_slice_header(hx, h)) < 0)
4640 hx->data_partitioning = 1;
4643 init_get_bits(&hx->intra_gb, ptr, bit_length);
4644 hx->intra_gb_ptr = &hx->intra_gb;
4647 init_get_bits(&hx->inter_gb, ptr, bit_length);
4648 hx->inter_gb_ptr = &hx->inter_gb;
4650 if (hx->redundant_pic_count == 0 &&
4652 hx->data_partitioning &&
4653 h->cur_pic_ptr && h->context_initialized &&
4654 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4655 (avctx->skip_frame < AVDISCARD_BIDIR ||
4656 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4657 (avctx->skip_frame < AVDISCARD_NONKEY ||
4658 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4659 avctx->skip_frame < AVDISCARD_ALL)
4663 init_get_bits(&h->gb, ptr, bit_length);
4664 ff_h264_decode_sei(h);
4667 init_get_bits(&h->gb, ptr, bit_length);
4668 ret = ff_h264_decode_seq_parameter_set(h);
4669 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
4670 av_log(h->avctx, AV_LOG_DEBUG,
4671 "SPS decoding failure, trying again with the complete NAL\n");
4672 init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
4674 ff_h264_decode_seq_parameter_set(h);
4677 ret = h264_set_parameter_from_sps(h);
4683 init_get_bits(&h->gb, ptr, bit_length);
4684 ff_h264_decode_picture_parameter_set(h, bit_length);
4687 case NAL_END_SEQUENCE:
4688 case NAL_END_STREAM:
4689 case NAL_FILLER_DATA:
4691 case NAL_AUXILIARY_SLICE:
4696 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4697 hx->nal_unit_type, bit_length);
4700 if (context_count == h->max_contexts) {
4701 execute_decode_slices(h, context_count);
4706 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4707 else if (err == 1) {
4708 /* Slice could not be decoded in parallel mode, copy down
4709 * NAL unit stuff to context 0 and restart. Note that
4710 * rbsp_buffer is not transferred, but since we no longer
4711 * run in parallel mode this should not be an issue. */
4712 h->nal_unit_type = hx->nal_unit_type;
4713 h->nal_ref_idc = hx->nal_ref_idc;
4720 execute_decode_slices(h, context_count);
4724 if (h->cur_pic_ptr && !h->droppable) {
4725 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
4726 h->picture_structure == PICT_BOTTOM_FIELD);
4729 return (ret < 0) ? ret : buf_index;
4733 * Return the number of bytes consumed for building the current frame.
4735 static int get_consumed_bytes(int pos, int buf_size)
4738 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4739 if (pos + 10 > buf_size)
4740 pos = buf_size; // oops ;)
4745 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
4748 int ret = av_frame_ref(dst, src);
4755 for (i = 0; i < 3; i++) {
4756 int hshift = (i > 0) ? h->chroma_x_shift : 0;
4757 int vshift = (i > 0) ? h->chroma_y_shift : 0;
4758 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
4759 (h->sps.crop_top >> vshift) * dst->linesize[i];
4760 dst->data[i] += off;
4765 static int decode_frame(AVCodecContext *avctx, void *data,
4766 int *got_frame, AVPacket *avpkt)
4768 const uint8_t *buf = avpkt->data;
4769 int buf_size = avpkt->size;
4770 H264Context *h = avctx->priv_data;
4771 AVFrame *pict = data;
4775 h->flags = avctx->flags;
4777 /* end of stream, output what is still in the buffers */
4779 if (buf_size == 0) {
4783 h->cur_pic_ptr = NULL;
4785 // FIXME factorize this with the output code below
4786 out = h->delayed_pic[0];
4789 h->delayed_pic[i] &&
4790 !h->delayed_pic[i]->f.key_frame &&
4791 !h->delayed_pic[i]->mmco_reset;
4793 if (h->delayed_pic[i]->poc < out->poc) {
4794 out = h->delayed_pic[i];
4798 for (i = out_idx; h->delayed_pic[i]; i++)
4799 h->delayed_pic[i] = h->delayed_pic[i + 1];
4802 ret = output_frame(h, pict, &out->f);
4811 buf_index = decode_nal_units(h, buf, buf_size, 0);
4813 return AVERROR_INVALIDDATA;
4815 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4820 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
4821 if (avctx->skip_frame >= AVDISCARD_NONREF)
4823 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4824 return AVERROR_INVALIDDATA;
4827 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
4828 (h->mb_y >= h->mb_height && h->mb_height)) {
4829 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
4830 decode_postinit(h, 1);
4834 if (!h->next_output_pic) {
4835 /* Wait for second field. */
4838 ret = output_frame(h, pict, &h->next_output_pic->f);
4845 assert(pict->data[0] || !*got_frame);
4847 return get_consumed_bytes(buf_index, buf_size);
4850 av_cold void ff_h264_free_context(H264Context *h)
4854 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4856 for (i = 0; i < MAX_SPS_COUNT; i++)
4857 av_freep(h->sps_buffers + i);
4859 for (i = 0; i < MAX_PPS_COUNT; i++)
4860 av_freep(h->pps_buffers + i);
4863 static av_cold int h264_decode_end(AVCodecContext *avctx)
4865 H264Context *h = avctx->priv_data;
4867 ff_h264_free_context(h);
4869 unref_picture(h, &h->cur_pic);
4874 static const AVProfile profiles[] = {
4875 { FF_PROFILE_H264_BASELINE, "Baseline" },
4876 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4877 { FF_PROFILE_H264_MAIN, "Main" },
4878 { FF_PROFILE_H264_EXTENDED, "Extended" },
4879 { FF_PROFILE_H264_HIGH, "High" },
4880 { FF_PROFILE_H264_HIGH_10, "High 10" },
4881 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4882 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4883 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4884 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4885 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4886 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4887 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4888 { FF_PROFILE_UNKNOWN },
4891 AVCodec ff_h264_decoder = {
4893 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4894 .type = AVMEDIA_TYPE_VIDEO,
4895 .id = AV_CODEC_ID_H264,
4896 .priv_data_size = sizeof(H264Context),
4897 .init = ff_h264_decode_init,
4898 .close = h264_decode_end,
4899 .decode = decode_frame,
4900 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4901 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4902 CODEC_CAP_FRAME_THREADS,
4904 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4905 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4906 .profiles = NULL_IF_CONFIG_SMALL(profiles),