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"
30 #include "libavutil/stereo3d.h"
31 #include "libavutil/timer.h"
34 #include "cabac_functions.h"
36 #include "error_resilience.h"
40 #include "h264chroma.h"
41 #include "h264_mvpred.h"
44 #include "mpegutils.h"
45 #include "rectangle.h"
51 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
53 static const uint8_t rem6[QP_MAX_NUM + 1] = {
54 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
55 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
56 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
59 static const uint8_t div6[QP_MAX_NUM + 1] = {
60 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
61 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
62 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
65 static const uint8_t field_scan[16] = {
66 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
67 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
68 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
69 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
72 static const uint8_t field_scan8x8[64] = {
73 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
74 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
75 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
76 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
77 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
78 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
79 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
80 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
81 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
82 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
83 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
84 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
85 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
86 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
87 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
88 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
91 static const uint8_t field_scan8x8_cavlc[64] = {
92 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
93 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
94 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
95 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
96 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
97 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
98 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
99 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
100 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
101 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
102 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
103 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
104 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
105 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
106 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
107 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
110 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
111 static const uint8_t zigzag_scan8x8_cavlc[64] = {
112 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
113 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
114 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
115 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
116 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
117 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
118 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
119 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
120 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
121 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
122 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
123 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
124 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
125 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
126 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
127 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
130 static const uint8_t dequant4_coeff_init[6][3] = {
139 static const uint8_t dequant8_coeff_init_scan[16] = {
140 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
143 static const uint8_t dequant8_coeff_init[6][6] = {
144 { 20, 18, 32, 19, 25, 24 },
145 { 22, 19, 35, 21, 28, 26 },
146 { 26, 23, 42, 24, 33, 31 },
147 { 28, 25, 45, 26, 35, 33 },
148 { 32, 28, 51, 30, 40, 38 },
149 { 36, 32, 58, 34, 46, 43 },
152 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
153 #if CONFIG_H264_DXVA2_HWACCEL
154 AV_PIX_FMT_DXVA2_VLD,
156 #if CONFIG_H264_VAAPI_HWACCEL
157 AV_PIX_FMT_VAAPI_VLD,
159 #if CONFIG_H264_VDA_HWACCEL
162 #if CONFIG_H264_VDPAU_HWACCEL
169 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
170 #if CONFIG_H264_DXVA2_HWACCEL
171 AV_PIX_FMT_DXVA2_VLD,
173 #if CONFIG_H264_VAAPI_HWACCEL
174 AV_PIX_FMT_VAAPI_VLD,
176 #if CONFIG_H264_VDA_HWACCEL
179 #if CONFIG_H264_VDPAU_HWACCEL
186 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
188 int mb_x, int mb_y, int mb_intra, int mb_skipped)
190 H264Context *h = opaque;
194 h->mb_xy = mb_x + mb_y * h->mb_stride;
195 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
197 /* FIXME: It is possible albeit uncommon that slice references
198 * differ between slices. We take the easy approach and ignore
199 * it for now. If this turns out to have any relevance in
200 * practice then correct remapping should be added. */
201 if (ref >= h->ref_count[0])
203 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
205 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
206 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
207 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
208 assert(!FRAME_MBAFF(h));
209 ff_h264_hl_decode_mb(h);
212 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
214 AVCodecContext *avctx = h->avctx;
215 AVFrame *cur = &h->cur_pic.f;
216 AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
217 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
218 int vshift = desc->log2_chroma_h;
219 const int field_pic = h->picture_structure != PICT_FRAME;
225 height = FFMIN(height, avctx->height - y);
227 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
230 if (avctx->draw_horiz_band) {
232 int offset[AV_NUM_DATA_POINTERS];
235 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
236 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
243 offset[0] = y * src->linesize[0];
245 offset[2] = (y >> vshift) * src->linesize[1];
246 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
251 avctx->draw_horiz_band(avctx, src, offset,
252 y, h->picture_structure, height);
256 static void unref_picture(H264Context *h, H264Picture *pic)
258 int off = offsetof(H264Picture, tf) + sizeof(pic->tf);
264 ff_thread_release_buffer(h->avctx, &pic->tf);
265 av_buffer_unref(&pic->hwaccel_priv_buf);
267 av_buffer_unref(&pic->qscale_table_buf);
268 av_buffer_unref(&pic->mb_type_buf);
269 for (i = 0; i < 2; i++) {
270 av_buffer_unref(&pic->motion_val_buf[i]);
271 av_buffer_unref(&pic->ref_index_buf[i]);
274 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
277 static void release_unused_pictures(H264Context *h, int remove_current)
281 /* release non reference frames */
282 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
283 if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
284 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
285 unref_picture(h, &h->DPB[i]);
290 static int ref_picture(H264Context *h, H264Picture *dst, H264Picture *src)
294 av_assert0(!dst->f.buf[0]);
295 av_assert0(src->f.buf[0]);
299 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
303 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
304 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
305 if (!dst->qscale_table_buf || !dst->mb_type_buf)
307 dst->qscale_table = src->qscale_table;
308 dst->mb_type = src->mb_type;
310 for (i = 0; i < 2; i++) {
311 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
312 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
313 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
315 dst->motion_val[i] = src->motion_val[i];
316 dst->ref_index[i] = src->ref_index[i];
319 if (src->hwaccel_picture_private) {
320 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
321 if (!dst->hwaccel_priv_buf)
323 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
326 for (i = 0; i < 2; i++)
327 dst->field_poc[i] = src->field_poc[i];
329 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
330 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
333 dst->frame_num = src->frame_num;
334 dst->mmco_reset = src->mmco_reset;
335 dst->pic_id = src->pic_id;
336 dst->long_ref = src->long_ref;
337 dst->mbaff = src->mbaff;
338 dst->field_picture = src->field_picture;
339 dst->needs_realloc = src->needs_realloc;
340 dst->reference = src->reference;
341 dst->recovered = src->recovered;
345 unref_picture(h, dst);
349 static int alloc_scratch_buffers(H264Context *h, int linesize)
351 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
353 if (h->bipred_scratchpad)
356 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
357 // edge emu needs blocksize + filter length - 1
358 // (= 21x21 for h264)
359 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
361 if (!h->bipred_scratchpad || !h->edge_emu_buffer) {
362 av_freep(&h->bipred_scratchpad);
363 av_freep(&h->edge_emu_buffer);
364 return AVERROR(ENOMEM);
370 static int init_table_pools(H264Context *h)
372 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
373 const int mb_array_size = h->mb_stride * h->mb_height;
374 const int b4_stride = h->mb_width * 4 + 1;
375 const int b4_array_size = b4_stride * h->mb_height * 4;
377 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
379 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
380 sizeof(uint32_t), av_buffer_allocz);
381 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
382 sizeof(int16_t), av_buffer_allocz);
383 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
385 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
386 !h->ref_index_pool) {
387 av_buffer_pool_uninit(&h->qscale_table_pool);
388 av_buffer_pool_uninit(&h->mb_type_pool);
389 av_buffer_pool_uninit(&h->motion_val_pool);
390 av_buffer_pool_uninit(&h->ref_index_pool);
391 return AVERROR(ENOMEM);
397 static int alloc_picture(H264Context *h, H264Picture *pic)
401 av_assert0(!pic->f.data[0]);
404 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
405 AV_GET_BUFFER_FLAG_REF : 0);
409 h->linesize = pic->f.linesize[0];
410 h->uvlinesize = pic->f.linesize[1];
412 if (h->avctx->hwaccel) {
413 const AVHWAccel *hwaccel = h->avctx->hwaccel;
414 av_assert0(!pic->hwaccel_picture_private);
415 if (hwaccel->priv_data_size) {
416 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
417 if (!pic->hwaccel_priv_buf)
418 return AVERROR(ENOMEM);
419 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
423 if (!h->qscale_table_pool) {
424 ret = init_table_pools(h);
429 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
430 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
431 if (!pic->qscale_table_buf || !pic->mb_type_buf)
434 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
435 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
437 for (i = 0; i < 2; i++) {
438 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
439 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
440 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
443 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
444 pic->ref_index[i] = pic->ref_index_buf[i]->data;
449 unref_picture(h, pic);
450 return (ret < 0) ? ret : AVERROR(ENOMEM);
453 static inline int pic_is_unused(H264Context *h, H264Picture *pic)
457 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
462 static int find_unused_picture(H264Context *h)
466 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
467 if (pic_is_unused(h, &h->DPB[i]))
470 if (i == H264_MAX_PICTURE_COUNT)
471 return AVERROR_INVALIDDATA;
473 if (h->DPB[i].needs_realloc) {
474 h->DPB[i].needs_realloc = 0;
475 unref_picture(h, &h->DPB[i]);
482 * Check if the top & left blocks are available if needed and
483 * change the dc mode so it only uses the available blocks.
485 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
487 static const int8_t top[12] = {
488 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
490 static const int8_t left[12] = {
491 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
495 if (!(h->top_samples_available & 0x8000)) {
496 for (i = 0; i < 4; i++) {
497 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
499 av_log(h->avctx, AV_LOG_ERROR,
500 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
501 status, h->mb_x, h->mb_y);
502 return AVERROR_INVALIDDATA;
504 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
509 if ((h->left_samples_available & 0x8888) != 0x8888) {
510 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
511 for (i = 0; i < 4; i++)
512 if (!(h->left_samples_available & mask[i])) {
513 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
515 av_log(h->avctx, AV_LOG_ERROR,
516 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
517 status, h->mb_x, h->mb_y);
518 return AVERROR_INVALIDDATA;
520 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
526 } // FIXME cleanup like ff_h264_check_intra_pred_mode
529 * Check if the top & left blocks are available if needed and
530 * change the dc mode so it only uses the available blocks.
532 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
534 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
535 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
538 av_log(h->avctx, AV_LOG_ERROR,
539 "out of range intra chroma pred mode at %d %d\n",
541 return AVERROR_INVALIDDATA;
544 if (!(h->top_samples_available & 0x8000)) {
547 av_log(h->avctx, AV_LOG_ERROR,
548 "top block unavailable for requested intra mode at %d %d\n",
550 return AVERROR_INVALIDDATA;
554 if ((h->left_samples_available & 0x8080) != 0x8080) {
556 if (is_chroma && (h->left_samples_available & 0x8080)) {
557 // mad cow disease mode, aka MBAFF + constrained_intra_pred
558 mode = ALZHEIMER_DC_L0T_PRED8x8 +
559 (!(h->left_samples_available & 0x8000)) +
560 2 * (mode == DC_128_PRED8x8);
563 av_log(h->avctx, AV_LOG_ERROR,
564 "left block unavailable for requested intra mode at %d %d\n",
566 return AVERROR_INVALIDDATA;
573 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
574 int *dst_length, int *consumed, int length)
580 // src[0]&0x80; // forbidden bit
581 h->nal_ref_idc = src[0] >> 5;
582 h->nal_unit_type = src[0] & 0x1F;
587 #define STARTCODE_TEST \
588 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
589 if (src[i + 2] != 3) { \
590 /* startcode, so we must be past the end */ \
596 #if HAVE_FAST_UNALIGNED
597 #define FIND_FIRST_ZERO \
598 if (i > 0 && !src[i]) \
604 for (i = 0; i + 1 < length; i += 9) {
605 if (!((~AV_RN64A(src + i) &
606 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
607 0x8000800080008080ULL))
614 for (i = 0; i + 1 < length; i += 5) {
615 if (!((~AV_RN32A(src + i) &
616 (AV_RN32A(src + i) - 0x01000101U)) &
625 for (i = 0; i + 1 < length; i += 2) {
628 if (i > 0 && src[i - 1] == 0)
634 if (i >= length - 1) { // no escaped 0
635 *dst_length = length;
636 *consumed = length + 1; // +1 for the header
640 // use second escape buffer for inter data
641 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
642 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
643 length + FF_INPUT_BUFFER_PADDING_SIZE);
644 dst = h->rbsp_buffer[bufidx];
651 while (si + 2 < length) {
652 // remove escapes (very rare 1:2^22)
653 if (src[si + 2] > 3) {
654 dst[di++] = src[si++];
655 dst[di++] = src[si++];
656 } else if (src[si] == 0 && src[si + 1] == 0) {
657 if (src[si + 2] == 3) { // escape
662 } else // next start code
666 dst[di++] = src[si++];
669 dst[di++] = src[si++];
672 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
675 *consumed = si + 1; // +1 for the header
676 /* FIXME store exact number of bits in the getbitcontext
677 * (it is needed for decoding) */
682 * Identify the exact end of the bitstream
683 * @return the length of the trailing, or 0 if damaged
685 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
690 tprintf(h->avctx, "rbsp trailing %X\n", v);
692 for (r = 1; r < 9; r++) {
700 static inline int get_lowest_part_list_y(H264Context *h, H264Picture *pic, int n,
701 int height, int y_offset, int list)
703 int raw_my = h->mv_cache[list][scan8[n]][1];
704 int filter_height_up = (raw_my & 3) ? 2 : 0;
705 int filter_height_down = (raw_my & 3) ? 3 : 0;
706 int full_my = (raw_my >> 2) + y_offset;
707 int top = full_my - filter_height_up;
708 int bottom = full_my + filter_height_down + height;
710 return FFMAX(abs(top), bottom);
713 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
714 int height, int y_offset, int list0,
715 int list1, int *nrefs)
719 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
722 int ref_n = h->ref_cache[0][scan8[n]];
723 H264Picture *ref = &h->ref_list[0][ref_n];
725 // Error resilience puts the current picture in the ref list.
726 // Don't try to wait on these as it will cause a deadlock.
727 // Fields can wait on each other, though.
728 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
729 (ref->reference & 3) != h->picture_structure) {
730 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
731 if (refs[0][ref_n] < 0)
733 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
738 int ref_n = h->ref_cache[1][scan8[n]];
739 H264Picture *ref = &h->ref_list[1][ref_n];
741 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
742 (ref->reference & 3) != h->picture_structure) {
743 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
744 if (refs[1][ref_n] < 0)
746 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
752 * Wait until all reference frames are available for MC operations.
754 * @param h the H264 context
756 static void await_references(H264Context *h)
758 const int mb_xy = h->mb_xy;
759 const int mb_type = h->cur_pic.mb_type[mb_xy];
761 int nrefs[2] = { 0 };
764 memset(refs, -1, sizeof(refs));
766 if (IS_16X16(mb_type)) {
767 get_lowest_part_y(h, refs, 0, 16, 0,
768 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
769 } else if (IS_16X8(mb_type)) {
770 get_lowest_part_y(h, refs, 0, 8, 0,
771 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
772 get_lowest_part_y(h, refs, 8, 8, 8,
773 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
774 } else if (IS_8X16(mb_type)) {
775 get_lowest_part_y(h, refs, 0, 16, 0,
776 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
777 get_lowest_part_y(h, refs, 4, 16, 0,
778 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
782 assert(IS_8X8(mb_type));
784 for (i = 0; i < 4; i++) {
785 const int sub_mb_type = h->sub_mb_type[i];
787 int y_offset = (i & 2) << 2;
789 if (IS_SUB_8X8(sub_mb_type)) {
790 get_lowest_part_y(h, refs, n, 8, y_offset,
791 IS_DIR(sub_mb_type, 0, 0),
792 IS_DIR(sub_mb_type, 0, 1),
794 } else if (IS_SUB_8X4(sub_mb_type)) {
795 get_lowest_part_y(h, refs, n, 4, y_offset,
796 IS_DIR(sub_mb_type, 0, 0),
797 IS_DIR(sub_mb_type, 0, 1),
799 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
800 IS_DIR(sub_mb_type, 0, 0),
801 IS_DIR(sub_mb_type, 0, 1),
803 } else if (IS_SUB_4X8(sub_mb_type)) {
804 get_lowest_part_y(h, refs, n, 8, y_offset,
805 IS_DIR(sub_mb_type, 0, 0),
806 IS_DIR(sub_mb_type, 0, 1),
808 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
809 IS_DIR(sub_mb_type, 0, 0),
810 IS_DIR(sub_mb_type, 0, 1),
814 assert(IS_SUB_4X4(sub_mb_type));
815 for (j = 0; j < 4; j++) {
816 int sub_y_offset = y_offset + 2 * (j & 2);
817 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
818 IS_DIR(sub_mb_type, 0, 0),
819 IS_DIR(sub_mb_type, 0, 1),
826 for (list = h->list_count - 1; list >= 0; list--)
827 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
828 int row = refs[list][ref];
830 H264Picture *ref_pic = &h->ref_list[list][ref];
831 int ref_field = ref_pic->reference - 1;
832 int ref_field_picture = ref_pic->field_picture;
833 int pic_height = 16 * h->mb_height >> ref_field_picture;
838 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
839 ff_thread_await_progress(&ref_pic->tf,
840 FFMIN((row >> 1) - !(row & 1),
843 ff_thread_await_progress(&ref_pic->tf,
844 FFMIN((row >> 1), pic_height - 1),
846 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
847 ff_thread_await_progress(&ref_pic->tf,
848 FFMIN(row * 2 + ref_field,
851 } else if (FIELD_PICTURE(h)) {
852 ff_thread_await_progress(&ref_pic->tf,
853 FFMIN(row, pic_height - 1),
856 ff_thread_await_progress(&ref_pic->tf,
857 FFMIN(row, pic_height - 1),
864 static av_always_inline void mc_dir_part(H264Context *h, H264Picture *pic,
865 int n, int square, int height,
867 uint8_t *dest_y, uint8_t *dest_cb,
869 int src_x_offset, int src_y_offset,
870 qpel_mc_func *qpix_op,
871 h264_chroma_mc_func chroma_op,
872 int pixel_shift, int chroma_idc)
874 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
875 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
876 const int luma_xy = (mx & 3) + ((my & 3) << 2);
877 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
878 uint8_t *src_y = pic->f.data[0] + offset;
879 uint8_t *src_cb, *src_cr;
881 int extra_height = 0;
883 const int full_mx = mx >> 2;
884 const int full_my = my >> 2;
885 const int pic_width = 16 * h->mb_width;
886 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
894 if (full_mx < 0 - extra_width ||
895 full_my < 0 - extra_height ||
896 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
897 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
898 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
899 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
900 h->mb_linesize, h->mb_linesize,
901 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
902 full_my - 2, pic_width, pic_height);
903 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
907 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
909 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
911 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
914 if (chroma_idc == 3 /* yuv444 */) {
915 src_cb = pic->f.data[1] + offset;
917 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
918 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
919 h->mb_linesize, h->mb_linesize,
920 16 + 5, 16 + 5 /*FIXME*/,
921 full_mx - 2, full_my - 2,
922 pic_width, pic_height);
923 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
925 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
927 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
929 src_cr = pic->f.data[2] + offset;
931 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
932 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
933 h->mb_linesize, h->mb_linesize,
934 16 + 5, 16 + 5 /*FIXME*/,
935 full_mx - 2, full_my - 2,
936 pic_width, pic_height);
937 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
939 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
941 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
945 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
946 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
947 // chroma offset when predicting from a field of opposite parity
948 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
949 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
952 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
953 (my >> ysh) * h->mb_uvlinesize;
954 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
955 (my >> ysh) * h->mb_uvlinesize;
958 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
959 h->mb_uvlinesize, 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,
970 h->mb_uvlinesize, h->mb_uvlinesize,
971 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
972 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
973 src_cr = h->edge_emu_buffer;
975 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
976 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
979 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
980 int height, int delta,
981 uint8_t *dest_y, uint8_t *dest_cb,
983 int x_offset, int y_offset,
984 qpel_mc_func *qpix_put,
985 h264_chroma_mc_func chroma_put,
986 qpel_mc_func *qpix_avg,
987 h264_chroma_mc_func chroma_avg,
988 int list0, int list1,
989 int pixel_shift, int chroma_idc)
991 qpel_mc_func *qpix_op = qpix_put;
992 h264_chroma_mc_func chroma_op = chroma_put;
994 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
995 if (chroma_idc == 3 /* yuv444 */) {
996 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
997 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
998 } else if (chroma_idc == 2 /* yuv422 */) {
999 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1000 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1001 } else { /* yuv420 */
1002 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1003 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1005 x_offset += 8 * h->mb_x;
1006 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1009 H264Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1010 mc_dir_part(h, ref, n, square, height, delta, 0,
1011 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1012 qpix_op, chroma_op, pixel_shift, chroma_idc);
1015 chroma_op = chroma_avg;
1019 H264Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1020 mc_dir_part(h, ref, n, square, height, delta, 1,
1021 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1022 qpix_op, chroma_op, pixel_shift, chroma_idc);
1026 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1027 int height, int delta,
1028 uint8_t *dest_y, uint8_t *dest_cb,
1030 int x_offset, int y_offset,
1031 qpel_mc_func *qpix_put,
1032 h264_chroma_mc_func chroma_put,
1033 h264_weight_func luma_weight_op,
1034 h264_weight_func chroma_weight_op,
1035 h264_biweight_func luma_weight_avg,
1036 h264_biweight_func chroma_weight_avg,
1037 int list0, int list1,
1038 int pixel_shift, int chroma_idc)
1042 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1043 if (chroma_idc == 3 /* yuv444 */) {
1044 chroma_height = height;
1045 chroma_weight_avg = luma_weight_avg;
1046 chroma_weight_op = luma_weight_op;
1047 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1048 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1049 } else if (chroma_idc == 2 /* yuv422 */) {
1050 chroma_height = height;
1051 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1052 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1053 } else { /* yuv420 */
1054 chroma_height = height >> 1;
1055 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1056 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1058 x_offset += 8 * h->mb_x;
1059 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1061 if (list0 && list1) {
1062 /* don't optimize for luma-only case, since B-frames usually
1063 * use implicit weights => chroma too. */
1064 uint8_t *tmp_cb = h->bipred_scratchpad;
1065 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1066 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1067 int refn0 = h->ref_cache[0][scan8[n]];
1068 int refn1 = h->ref_cache[1][scan8[n]];
1070 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1071 dest_y, dest_cb, dest_cr,
1072 x_offset, y_offset, qpix_put, chroma_put,
1073 pixel_shift, chroma_idc);
1074 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1075 tmp_y, tmp_cb, tmp_cr,
1076 x_offset, y_offset, qpix_put, chroma_put,
1077 pixel_shift, chroma_idc);
1079 if (h->use_weight == 2) {
1080 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1081 int weight1 = 64 - weight0;
1082 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1083 height, 5, weight0, weight1, 0);
1084 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1085 chroma_height, 5, weight0, weight1, 0);
1086 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1087 chroma_height, 5, weight0, weight1, 0);
1089 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1090 h->luma_log2_weight_denom,
1091 h->luma_weight[refn0][0][0],
1092 h->luma_weight[refn1][1][0],
1093 h->luma_weight[refn0][0][1] +
1094 h->luma_weight[refn1][1][1]);
1095 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1096 h->chroma_log2_weight_denom,
1097 h->chroma_weight[refn0][0][0][0],
1098 h->chroma_weight[refn1][1][0][0],
1099 h->chroma_weight[refn0][0][0][1] +
1100 h->chroma_weight[refn1][1][0][1]);
1101 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1102 h->chroma_log2_weight_denom,
1103 h->chroma_weight[refn0][0][1][0],
1104 h->chroma_weight[refn1][1][1][0],
1105 h->chroma_weight[refn0][0][1][1] +
1106 h->chroma_weight[refn1][1][1][1]);
1109 int list = list1 ? 1 : 0;
1110 int refn = h->ref_cache[list][scan8[n]];
1111 H264Picture *ref = &h->ref_list[list][refn];
1112 mc_dir_part(h, ref, n, square, height, delta, list,
1113 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1114 qpix_put, chroma_put, pixel_shift, chroma_idc);
1116 luma_weight_op(dest_y, h->mb_linesize, height,
1117 h->luma_log2_weight_denom,
1118 h->luma_weight[refn][list][0],
1119 h->luma_weight[refn][list][1]);
1120 if (h->use_weight_chroma) {
1121 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1122 h->chroma_log2_weight_denom,
1123 h->chroma_weight[refn][list][0][0],
1124 h->chroma_weight[refn][list][0][1]);
1125 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1126 h->chroma_log2_weight_denom,
1127 h->chroma_weight[refn][list][1][0],
1128 h->chroma_weight[refn][list][1][1]);
1133 static av_always_inline void prefetch_motion(H264Context *h, int list,
1134 int pixel_shift, int chroma_idc)
1136 /* fetch pixels for estimated mv 4 macroblocks ahead
1137 * optimized for 64byte cache lines */
1138 const int refn = h->ref_cache[list][scan8[0]];
1140 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1141 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1142 uint8_t **src = h->ref_list[list][refn].f.data;
1143 int off = (mx << pixel_shift) +
1144 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1145 (64 << pixel_shift);
1146 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1147 if (chroma_idc == 3 /* yuv444 */) {
1148 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1149 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1151 off = ((mx >> 1) << pixel_shift) +
1152 ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
1153 (64 << pixel_shift);
1154 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1159 static void free_tables(H264Context *h, int free_rbsp)
1164 av_freep(&h->intra4x4_pred_mode);
1165 av_freep(&h->chroma_pred_mode_table);
1166 av_freep(&h->cbp_table);
1167 av_freep(&h->mvd_table[0]);
1168 av_freep(&h->mvd_table[1]);
1169 av_freep(&h->direct_table);
1170 av_freep(&h->non_zero_count);
1171 av_freep(&h->slice_table_base);
1172 h->slice_table = NULL;
1173 av_freep(&h->list_counts);
1175 av_freep(&h->mb2b_xy);
1176 av_freep(&h->mb2br_xy);
1178 av_buffer_pool_uninit(&h->qscale_table_pool);
1179 av_buffer_pool_uninit(&h->mb_type_pool);
1180 av_buffer_pool_uninit(&h->motion_val_pool);
1181 av_buffer_pool_uninit(&h->ref_index_pool);
1183 if (free_rbsp && h->DPB) {
1184 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1185 unref_picture(h, &h->DPB[i]);
1187 } else if (h->DPB) {
1188 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1189 h->DPB[i].needs_realloc = 1;
1192 h->cur_pic_ptr = NULL;
1194 for (i = 0; i < H264_MAX_THREADS; i++) {
1195 hx = h->thread_context[i];
1198 av_freep(&hx->top_borders[1]);
1199 av_freep(&hx->top_borders[0]);
1200 av_freep(&hx->bipred_scratchpad);
1201 av_freep(&hx->edge_emu_buffer);
1202 av_freep(&hx->dc_val_base);
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(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
1338 return AVERROR(ENOMEM);
1339 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1340 av_frame_unref(&h->DPB[i].f);
1341 av_frame_unref(&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 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1373 src->sps.chroma_format_idc);
1378 * Allocate buffers which are not shared amongst multiple threads.
1380 static int context_init(H264Context *h)
1382 ERContext *er = &h->er;
1383 int mb_array_size = h->mb_height * h->mb_stride;
1384 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1385 int c_size = h->mb_stride * (h->mb_height + 1);
1386 int yc_size = y_size + 2 * c_size;
1389 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1390 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1391 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1392 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1394 h->ref_cache[0][scan8[5] + 1] =
1395 h->ref_cache[0][scan8[7] + 1] =
1396 h->ref_cache[0][scan8[13] + 1] =
1397 h->ref_cache[1][scan8[5] + 1] =
1398 h->ref_cache[1][scan8[7] + 1] =
1399 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1401 if (CONFIG_ERROR_RESILIENCE) {
1403 er->avctx = h->avctx;
1405 er->decode_mb = h264_er_decode_mb;
1407 er->quarter_sample = 1;
1409 er->mb_num = h->mb_num;
1410 er->mb_width = h->mb_width;
1411 er->mb_height = h->mb_height;
1412 er->mb_stride = h->mb_stride;
1413 er->b8_stride = h->mb_width * 2 + 1;
1415 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1416 fail); // error ressilience code looks cleaner with this
1417 for (y = 0; y < h->mb_height; y++)
1418 for (x = 0; x < h->mb_width; x++)
1419 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1421 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1422 h->mb_stride + h->mb_width;
1424 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1425 mb_array_size * sizeof(uint8_t), fail);
1427 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1428 memset(er->mbintra_table, 1, mb_array_size);
1430 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1432 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1435 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1436 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1437 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1438 er->dc_val[2] = er->dc_val[1] + c_size;
1439 for (i = 0; i < yc_size; i++)
1440 h->dc_val_base[i] = 1024;
1446 return AVERROR(ENOMEM); // free_tables will clean up for us
1449 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1450 int parse_extradata);
1452 int ff_h264_decode_extradata(H264Context *h)
1454 AVCodecContext *avctx = h->avctx;
1457 if (avctx->extradata[0] == 1) {
1458 int i, cnt, nalsize;
1459 unsigned char *p = avctx->extradata;
1463 if (avctx->extradata_size < 7) {
1464 av_log(avctx, AV_LOG_ERROR,
1465 "avcC %d too short\n", avctx->extradata_size);
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 h->recovery_frame = -1;
1564 h->frame_recovered = 0;
1565 if (avctx->codec_id == AV_CODEC_ID_H264) {
1566 if (avctx->ticks_per_frame == 1)
1567 h->avctx->time_base.den *= 2;
1568 avctx->ticks_per_frame = 2;
1571 if (avctx->extradata_size > 0 && avctx->extradata) {
1572 ret = ff_h264_decode_extradata(h);
1577 if (h->sps.bitstream_restriction_flag &&
1578 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1579 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1583 avctx->internal->allocate_progress = 1;
1588 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1589 #undef REBASE_PICTURE
1590 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1591 ((pic && pic >= old_ctx->DPB && \
1592 pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
1593 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1595 static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
1596 H264Context *new_base,
1597 H264Context *old_base)
1601 for (i = 0; i < count; i++) {
1602 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1603 IN_RANGE(from[i], old_base->DPB,
1604 sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
1606 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1610 static int copy_parameter_set(void **to, void **from, int count, int size)
1614 for (i = 0; i < count; i++) {
1615 if (to[i] && !from[i]) {
1617 } else if (from[i] && !to[i]) {
1618 to[i] = av_malloc(size);
1620 return AVERROR(ENOMEM);
1624 memcpy(to[i], from[i], size);
1630 static int decode_init_thread_copy(AVCodecContext *avctx)
1632 H264Context *h = avctx->priv_data;
1634 if (!avctx->internal->is_copy)
1636 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1637 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1639 h->context_initialized = 0;
1644 #define copy_fields(to, from, start_field, end_field) \
1645 memcpy(&to->start_field, &from->start_field, \
1646 (char *)&to->end_field - (char *)&to->start_field)
1648 static int h264_slice_header_init(H264Context *, int);
1650 static int h264_set_parameter_from_sps(H264Context *h);
1652 static int decode_update_thread_context(AVCodecContext *dst,
1653 const AVCodecContext *src)
1655 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1656 int inited = h->context_initialized, err = 0;
1657 int context_reinitialized = 0;
1660 if (dst == src || !h1->context_initialized)
1664 (h->width != h1->width ||
1665 h->height != h1->height ||
1666 h->mb_width != h1->mb_width ||
1667 h->mb_height != h1->mb_height ||
1668 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1669 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1670 h->sps.colorspace != h1->sps.colorspace)) {
1672 /* set bits_per_raw_sample to the previous value. the check for changed
1673 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1674 * the current value */
1675 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1677 av_freep(&h->bipred_scratchpad);
1679 h->width = h1->width;
1680 h->height = h1->height;
1681 h->mb_height = h1->mb_height;
1682 h->mb_width = h1->mb_width;
1683 h->mb_num = h1->mb_num;
1684 h->mb_stride = h1->mb_stride;
1685 h->b_stride = h1->b_stride;
1687 if ((err = h264_slice_header_init(h, 1)) < 0) {
1688 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1691 context_reinitialized = 1;
1693 /* update linesize on resize. The decoder doesn't
1694 * necessarily call h264_frame_start in the new thread */
1695 h->linesize = h1->linesize;
1696 h->uvlinesize = h1->uvlinesize;
1698 /* copy block_offset since frame_start may not be called */
1699 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1703 for (i = 0; i < MAX_SPS_COUNT; i++)
1704 av_freep(h->sps_buffers + i);
1706 for (i = 0; i < MAX_PPS_COUNT; i++)
1707 av_freep(h->pps_buffers + i);
1709 memcpy(h, h1, sizeof(*h1));
1710 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1711 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1712 memset(&h->er, 0, sizeof(h->er));
1713 memset(&h->mb, 0, sizeof(h->mb));
1714 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1715 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1716 h->context_initialized = 0;
1718 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1719 av_frame_unref(&h->cur_pic.f);
1720 h->cur_pic.tf.f = &h->cur_pic.f;
1724 h->qscale_table_pool = NULL;
1725 h->mb_type_pool = NULL;
1726 h->ref_index_pool = NULL;
1727 h->motion_val_pool = NULL;
1729 ret = ff_h264_alloc_tables(h);
1731 av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n");
1734 ret = context_init(h);
1736 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1740 for (i = 0; i < 2; i++) {
1741 h->rbsp_buffer[i] = NULL;
1742 h->rbsp_buffer_size[i] = 0;
1744 h->bipred_scratchpad = NULL;
1745 h->edge_emu_buffer = NULL;
1747 h->thread_context[0] = h;
1749 h->context_initialized = 1;
1752 h->avctx->coded_height = h1->avctx->coded_height;
1753 h->avctx->coded_width = h1->avctx->coded_width;
1754 h->avctx->width = h1->avctx->width;
1755 h->avctx->height = h1->avctx->height;
1756 h->coded_picture_number = h1->coded_picture_number;
1757 h->first_field = h1->first_field;
1758 h->picture_structure = h1->picture_structure;
1759 h->qscale = h1->qscale;
1760 h->droppable = h1->droppable;
1761 h->low_delay = h1->low_delay;
1763 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
1764 unref_picture(h, &h->DPB[i]);
1765 if (h1->DPB[i].f.buf[0] &&
1766 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1770 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1771 unref_picture(h, &h->cur_pic);
1772 if ((ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1775 h->workaround_bugs = h1->workaround_bugs;
1776 h->low_delay = h1->low_delay;
1777 h->droppable = h1->droppable;
1779 /* frame_start may not be called for the next thread (if it's decoding
1780 * a bottom field) so this has to be allocated here */
1781 err = alloc_scratch_buffers(h, h1->linesize);
1785 // extradata/NAL handling
1786 h->is_avc = h1->is_avc;
1789 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1790 (void **)h1->sps_buffers,
1791 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1794 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1795 (void **)h1->pps_buffers,
1796 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1800 // Dequantization matrices
1801 // FIXME these are big - can they be only copied when PPS changes?
1802 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1804 for (i = 0; i < 6; i++)
1805 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1806 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1808 for (i = 0; i < 6; i++)
1809 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1810 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1812 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1815 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1818 copy_fields(h, h1, short_ref, cabac_init_idc);
1820 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1821 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1822 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1823 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1825 h->last_slice_type = h1->last_slice_type;
1827 if (context_reinitialized)
1828 h264_set_parameter_from_sps(h);
1830 if (!h->cur_pic_ptr)
1833 if (!h->droppable) {
1834 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1835 h->prev_poc_msb = h->poc_msb;
1836 h->prev_poc_lsb = h->poc_lsb;
1838 h->prev_frame_num_offset = h->frame_num_offset;
1839 h->prev_frame_num = h->frame_num;
1840 h->outputed_poc = h->next_outputed_poc;
1842 h->recovery_frame = h1->recovery_frame;
1843 h->frame_recovered = h1->frame_recovered;
1848 static int h264_frame_start(H264Context *h)
1852 const int pixel_shift = h->pixel_shift;
1854 release_unused_pictures(h, 1);
1855 h->cur_pic_ptr = NULL;
1857 i = find_unused_picture(h);
1859 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1864 pic->reference = h->droppable ? 0 : h->picture_structure;
1865 pic->f.coded_picture_number = h->coded_picture_number++;
1866 pic->field_picture = h->picture_structure != PICT_FRAME;
1868 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1870 * See decode_nal_units().
1872 pic->f.key_frame = 0;
1873 pic->mmco_reset = 0;
1876 if ((ret = alloc_picture(h, pic)) < 0)
1879 h->cur_pic_ptr = pic;
1880 unref_picture(h, &h->cur_pic);
1881 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1884 if (CONFIG_ERROR_RESILIENCE)
1885 ff_er_frame_start(&h->er);
1887 assert(h->linesize && h->uvlinesize);
1889 for (i = 0; i < 16; i++) {
1890 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1891 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1893 for (i = 0; i < 16; i++) {
1894 h->block_offset[16 + i] =
1895 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1896 h->block_offset[48 + 16 + i] =
1897 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1900 /* can't be in alloc_tables because linesize isn't known there.
1901 * FIXME: redo bipred weight to not require extra buffer? */
1902 for (i = 0; i < h->slice_context_count; i++)
1903 if (h->thread_context[i]) {
1904 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1909 /* Some macroblocks can be accessed before they're available in case
1910 * of lost slices, MBAFF or threading. */
1911 memset(h->slice_table, -1,
1912 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1914 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1915 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1917 /* We mark the current picture as non-reference after allocating it, so
1918 * that if we break out due to an error it can be released automatically
1919 * in the next ff_MPV_frame_start().
1921 h->cur_pic_ptr->reference = 0;
1923 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1925 h->next_output_pic = NULL;
1927 assert(h->cur_pic_ptr->long_ref == 0);
1933 * Run setup operations that must be run after slice header decoding.
1934 * This includes finding the next displayed frame.
1936 * @param h h264 master context
1937 * @param setup_finished enough NALs have been read that we can call
1938 * ff_thread_finish_setup()
1940 static void decode_postinit(H264Context *h, int setup_finished)
1942 H264Picture *out = h->cur_pic_ptr;
1943 H264Picture *cur = h->cur_pic_ptr;
1944 int i, pics, out_of_order, out_idx;
1945 int invalid = 0, cnt = 0;
1947 h->cur_pic_ptr->f.pict_type = h->pict_type;
1949 if (h->next_output_pic)
1952 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1953 /* FIXME: if we have two PAFF fields in one packet, we can't start
1954 * the next thread here. If we have one field per packet, we can.
1955 * The check in decode_nal_units() is not good enough to find this
1956 * yet, so we assume the worst for now. */
1957 // if (setup_finished)
1958 // ff_thread_finish_setup(h->avctx);
1962 cur->f.interlaced_frame = 0;
1963 cur->f.repeat_pict = 0;
1965 /* Signal interlacing information externally. */
1966 /* Prioritize picture timing SEI information over used
1967 * decoding process if it exists. */
1969 if (h->sps.pic_struct_present_flag) {
1970 switch (h->sei_pic_struct) {
1971 case SEI_PIC_STRUCT_FRAME:
1973 case SEI_PIC_STRUCT_TOP_FIELD:
1974 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1975 cur->f.interlaced_frame = 1;
1977 case SEI_PIC_STRUCT_TOP_BOTTOM:
1978 case SEI_PIC_STRUCT_BOTTOM_TOP:
1979 if (FIELD_OR_MBAFF_PICTURE(h))
1980 cur->f.interlaced_frame = 1;
1982 // try to flag soft telecine progressive
1983 cur->f.interlaced_frame = h->prev_interlaced_frame;
1985 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1986 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1987 /* Signal the possibility of telecined film externally
1988 * (pic_struct 5,6). From these hints, let the applications
1989 * decide if they apply deinterlacing. */
1990 cur->f.repeat_pict = 1;
1992 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1993 cur->f.repeat_pict = 2;
1995 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1996 cur->f.repeat_pict = 4;
2000 if ((h->sei_ct_type & 3) &&
2001 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2002 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2004 /* Derive interlacing flag from used decoding process. */
2005 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2007 h->prev_interlaced_frame = cur->f.interlaced_frame;
2009 if (cur->field_poc[0] != cur->field_poc[1]) {
2010 /* Derive top_field_first from field pocs. */
2011 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2013 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2014 /* Use picture timing SEI information. Even if it is a
2015 * information of a past frame, better than nothing. */
2016 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2017 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2018 cur->f.top_field_first = 1;
2020 cur->f.top_field_first = 0;
2022 /* Most likely progressive */
2023 cur->f.top_field_first = 0;
2027 if (h->sei_frame_packing_present &&
2028 h->frame_packing_arrangement_type >= 0 &&
2029 h->frame_packing_arrangement_type <= 6 &&
2030 h->content_interpretation_type > 0 &&
2031 h->content_interpretation_type < 3) {
2032 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
2036 switch (h->frame_packing_arrangement_type) {
2038 stereo->type = AV_STEREO3D_CHECKERBOARD;
2041 stereo->type = AV_STEREO3D_LINES;
2044 stereo->type = AV_STEREO3D_COLUMNS;
2047 if (h->quincunx_subsampling)
2048 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2050 stereo->type = AV_STEREO3D_SIDEBYSIDE;
2053 stereo->type = AV_STEREO3D_TOPBOTTOM;
2056 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
2059 stereo->type = AV_STEREO3D_2D;
2063 if (h->content_interpretation_type == 2)
2064 stereo->flags = AV_STEREO3D_FLAG_INVERT;
2067 // FIXME do something with unavailable reference frames
2069 /* Sort B-frames into display order */
2071 if (h->sps.bitstream_restriction_flag &&
2072 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2073 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2077 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2078 !h->sps.bitstream_restriction_flag) {
2079 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2084 while (h->delayed_pic[pics])
2087 assert(pics <= MAX_DELAYED_PIC_COUNT);
2089 h->delayed_pic[pics++] = cur;
2090 if (cur->reference == 0)
2091 cur->reference = DELAYED_PIC_REF;
2093 /* Frame reordering. This code takes pictures from coding order and sorts
2094 * them by their incremental POC value into display order. It supports POC
2095 * gaps, MMCO reset codes and random resets.
2096 * A "display group" can start either with a IDR frame (f.key_frame = 1),
2097 * and/or can be closed down with a MMCO reset code. In sequences where
2098 * there is no delay, we can't detect that (since the frame was already
2099 * output to the user), so we also set h->mmco_reset to detect the MMCO
2101 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
2102 * we increase the delay between input and output. All frames affected by
2103 * the lag (e.g. those that should have been output before another frame
2104 * that we already returned to the user) will be dropped. This is a bug
2105 * that we will fix later. */
2106 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2107 cnt += out->poc < h->last_pocs[i];
2108 invalid += out->poc == INT_MIN;
2110 if (!h->mmco_reset && !cur->f.key_frame &&
2111 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
2114 h->delayed_pic[pics - 2]->mmco_reset = 2;
2116 if (h->mmco_reset || cur->f.key_frame) {
2117 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2118 h->last_pocs[i] = INT_MIN;
2120 invalid = MAX_DELAYED_PIC_COUNT;
2122 out = h->delayed_pic[0];
2124 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
2125 h->delayed_pic[i] &&
2126 !h->delayed_pic[i - 1]->mmco_reset &&
2127 !h->delayed_pic[i]->f.key_frame;
2129 if (h->delayed_pic[i]->poc < out->poc) {
2130 out = h->delayed_pic[i];
2133 if (h->avctx->has_b_frames == 0 &&
2134 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
2135 h->next_outputed_poc = INT_MIN;
2136 out_of_order = !out->f.key_frame && !h->mmco_reset &&
2137 (out->poc < h->next_outputed_poc);
2139 if (h->sps.bitstream_restriction_flag &&
2140 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
2141 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
2142 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
2143 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
2144 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
2147 } else if (h->low_delay &&
2148 ((h->next_outputed_poc != INT_MIN &&
2149 out->poc > h->next_outputed_poc + 2) ||
2150 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
2152 h->avctx->has_b_frames++;
2155 if (pics > h->avctx->has_b_frames) {
2156 out->reference &= ~DELAYED_PIC_REF;
2157 // for frame threading, the owner must be the second field's thread or
2158 // else the first thread can release the picture and reuse it unsafely
2159 for (i = out_idx; h->delayed_pic[i]; i++)
2160 h->delayed_pic[i] = h->delayed_pic[i + 1];
2162 memmove(h->last_pocs, &h->last_pocs[1],
2163 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
2164 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
2165 if (!out_of_order && pics > h->avctx->has_b_frames) {
2166 h->next_output_pic = out;
2167 if (out->mmco_reset) {
2169 h->next_outputed_poc = out->poc;
2170 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
2172 h->next_outputed_poc = INT_MIN;
2175 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
2176 h->next_outputed_poc = INT_MIN;
2178 h->next_outputed_poc = out->poc;
2183 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
2186 if (h->next_output_pic) {
2187 if (h->next_output_pic->recovered) {
2188 // We have reached an recovery point and all frames after it in
2189 // display order are "recovered".
2190 h->frame_recovered |= FRAME_RECOVERED_SEI;
2192 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2195 if (setup_finished && !h->avctx->hwaccel)
2196 ff_thread_finish_setup(h->avctx);
2199 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2200 uint8_t *src_cb, uint8_t *src_cr,
2201 int linesize, int uvlinesize,
2204 uint8_t *top_border;
2206 const int pixel_shift = h->pixel_shift;
2207 int chroma444 = CHROMA444(h);
2208 int chroma422 = CHROMA422(h);
2211 src_cb -= uvlinesize;
2212 src_cr -= uvlinesize;
2214 if (!simple && FRAME_MBAFF(h)) {
2217 top_border = h->top_borders[0][h->mb_x];
2218 AV_COPY128(top_border, src_y + 15 * linesize);
2220 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2221 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2224 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2225 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2226 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2227 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2229 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2230 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2232 } else if (chroma422) {
2234 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2235 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2237 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2238 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2242 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2243 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2245 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2246 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2251 } else if (MB_MBAFF(h)) {
2257 top_border = h->top_borders[top_idx][h->mb_x];
2258 /* There are two lines saved, the line above the top macroblock
2259 * of a pair, and the line above the bottom macroblock. */
2260 AV_COPY128(top_border, src_y + 16 * linesize);
2262 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2264 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2267 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2268 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2269 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2270 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2272 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2273 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2275 } else if (chroma422) {
2277 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2278 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2280 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2281 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2285 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2286 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2288 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2289 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2295 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2296 uint8_t *src_cb, uint8_t *src_cr,
2297 int linesize, int uvlinesize,
2298 int xchg, int chroma444,
2299 int simple, int pixel_shift)
2301 int deblock_topleft;
2304 uint8_t *top_border_m1;
2305 uint8_t *top_border;
2307 if (!simple && FRAME_MBAFF(h)) {
2312 top_idx = MB_MBAFF(h) ? 0 : 1;
2316 if (h->deblocking_filter == 2) {
2317 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2318 deblock_top = h->top_type;
2320 deblock_topleft = (h->mb_x > 0);
2321 deblock_top = (h->mb_y > !!MB_FIELD(h));
2324 src_y -= linesize + 1 + pixel_shift;
2325 src_cb -= uvlinesize + 1 + pixel_shift;
2326 src_cr -= uvlinesize + 1 + pixel_shift;
2328 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2329 top_border = h->top_borders[top_idx][h->mb_x];
2331 #define XCHG(a, b, xchg) \
2332 if (pixel_shift) { \
2334 AV_SWAP64(b + 0, a + 0); \
2335 AV_SWAP64(b + 8, a + 8); \
2345 if (deblock_topleft) {
2346 XCHG(top_border_m1 + (8 << pixel_shift),
2347 src_y - (7 << pixel_shift), 1);
2349 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2350 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2351 if (h->mb_x + 1 < h->mb_width) {
2352 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2353 src_y + (17 << pixel_shift), 1);
2356 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2359 if (deblock_topleft) {
2360 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2361 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2363 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2364 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2365 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2366 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2367 if (h->mb_x + 1 < h->mb_width) {
2368 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2369 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2374 if (deblock_topleft) {
2375 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2376 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2378 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2379 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2385 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2388 if (high_bit_depth) {
2389 return AV_RN32A(((int32_t *)mb) + index);
2391 return AV_RN16A(mb + index);
2394 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2395 int index, int value)
2397 if (high_bit_depth) {
2398 AV_WN32A(((int32_t *)mb) + index, value);
2400 AV_WN16A(mb + index, value);
2403 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2404 int mb_type, int is_h264,
2406 int transform_bypass,
2410 uint8_t *dest_y, int p)
2412 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2413 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2415 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2416 block_offset += 16 * p;
2417 if (IS_INTRA4x4(mb_type)) {
2418 if (IS_8x8DCT(mb_type)) {
2419 if (transform_bypass) {
2421 idct_add = h->h264dsp.h264_add_pixels8_clear;
2423 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2424 idct_add = h->h264dsp.h264_idct8_add;
2426 for (i = 0; i < 16; i += 4) {
2427 uint8_t *const ptr = dest_y + block_offset[i];
2428 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2429 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2430 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2432 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2433 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2434 (h->topright_samples_available << i) & 0x4000, linesize);
2436 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2437 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2439 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2444 if (transform_bypass) {
2446 idct_add = h->h264dsp.h264_add_pixels4_clear;
2448 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2449 idct_add = h->h264dsp.h264_idct_add;
2451 for (i = 0; i < 16; i++) {
2452 uint8_t *const ptr = dest_y + block_offset[i];
2453 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2455 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2456 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2461 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2462 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2463 assert(h->mb_y || linesize <= block_offset[i]);
2464 if (!topright_avail) {
2466 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2467 topright = (uint8_t *)&tr_high;
2469 tr = ptr[3 - linesize] * 0x01010101u;
2470 topright = (uint8_t *)&tr;
2473 topright = ptr + (4 << pixel_shift) - linesize;
2477 h->hpc.pred4x4[dir](ptr, topright, linesize);
2478 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2481 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2482 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2484 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2485 } else if (CONFIG_SVQ3_DECODER)
2486 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2492 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2494 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2495 if (!transform_bypass)
2496 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2498 h->dequant4_coeff[p][qscale][0]);
2500 static const uint8_t dc_mapping[16] = {
2501 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2502 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2503 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2504 10 * 16, 11 * 16, 14 * 16, 15 * 16
2506 for (i = 0; i < 16; i++)
2507 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2508 pixel_shift, dc_mapping[i],
2509 dctcoef_get(h->mb_luma_dc[p],
2513 } else if (CONFIG_SVQ3_DECODER)
2514 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2515 h->mb_luma_dc[p], qscale);
2519 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2520 int is_h264, int simple,
2521 int transform_bypass,
2525 uint8_t *dest_y, int p)
2527 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2529 block_offset += 16 * p;
2530 if (!IS_INTRA4x4(mb_type)) {
2532 if (IS_INTRA16x16(mb_type)) {
2533 if (transform_bypass) {
2534 if (h->sps.profile_idc == 244 &&
2535 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2536 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2537 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2538 h->mb + (p * 256 << pixel_shift),
2541 for (i = 0; i < 16; i++)
2542 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2543 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2544 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2545 h->mb + (i * 16 + p * 256 << pixel_shift),
2549 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2550 h->mb + (p * 256 << pixel_shift),
2552 h->non_zero_count_cache + p * 5 * 8);
2554 } else if (h->cbp & 15) {
2555 if (transform_bypass) {
2556 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2557 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2558 : h->h264dsp.h264_add_pixels4_clear;
2559 for (i = 0; i < 16; i += di)
2560 if (h->non_zero_count_cache[scan8[i + p * 16]])
2561 idct_add(dest_y + block_offset[i],
2562 h->mb + (i * 16 + p * 256 << pixel_shift),
2565 if (IS_8x8DCT(mb_type))
2566 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2567 h->mb + (p * 256 << pixel_shift),
2569 h->non_zero_count_cache + p * 5 * 8);
2571 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2572 h->mb + (p * 256 << pixel_shift),
2574 h->non_zero_count_cache + p * 5 * 8);
2577 } else if (CONFIG_SVQ3_DECODER) {
2578 for (i = 0; i < 16; i++)
2579 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2580 // FIXME benchmark weird rule, & below
2581 uint8_t *const ptr = dest_y + block_offset[i];
2582 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2583 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2591 #include "h264_mb_template.c"
2595 #include "h264_mb_template.c"
2599 #include "h264_mb_template.c"
2601 void ff_h264_hl_decode_mb(H264Context *h)
2603 const int mb_xy = h->mb_xy;
2604 const int mb_type = h->cur_pic.mb_type[mb_xy];
2605 int is_complex = CONFIG_SMALL || h->is_complex ||
2606 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2609 if (is_complex || h->pixel_shift)
2610 hl_decode_mb_444_complex(h);
2612 hl_decode_mb_444_simple_8(h);
2613 } else if (is_complex) {
2614 hl_decode_mb_complex(h);
2615 } else if (h->pixel_shift) {
2616 hl_decode_mb_simple_16(h);
2618 hl_decode_mb_simple_8(h);
2621 int ff_pred_weight_table(H264Context *h)
2624 int luma_def, chroma_def;
2627 h->use_weight_chroma = 0;
2628 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2629 if (h->sps.chroma_format_idc)
2630 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2631 luma_def = 1 << h->luma_log2_weight_denom;
2632 chroma_def = 1 << h->chroma_log2_weight_denom;
2634 for (list = 0; list < 2; list++) {
2635 h->luma_weight_flag[list] = 0;
2636 h->chroma_weight_flag[list] = 0;
2637 for (i = 0; i < h->ref_count[list]; i++) {
2638 int luma_weight_flag, chroma_weight_flag;
2640 luma_weight_flag = get_bits1(&h->gb);
2641 if (luma_weight_flag) {
2642 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2643 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2644 if (h->luma_weight[i][list][0] != luma_def ||
2645 h->luma_weight[i][list][1] != 0) {
2647 h->luma_weight_flag[list] = 1;
2650 h->luma_weight[i][list][0] = luma_def;
2651 h->luma_weight[i][list][1] = 0;
2654 if (h->sps.chroma_format_idc) {
2655 chroma_weight_flag = get_bits1(&h->gb);
2656 if (chroma_weight_flag) {
2658 for (j = 0; j < 2; j++) {
2659 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2660 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2661 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2662 h->chroma_weight[i][list][j][1] != 0) {
2663 h->use_weight_chroma = 1;
2664 h->chroma_weight_flag[list] = 1;
2669 for (j = 0; j < 2; j++) {
2670 h->chroma_weight[i][list][j][0] = chroma_def;
2671 h->chroma_weight[i][list][j][1] = 0;
2676 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2679 h->use_weight = h->use_weight || h->use_weight_chroma;
2684 * Initialize implicit_weight table.
2685 * @param field 0/1 initialize the weight for interlaced MBAFF
2686 * -1 initializes the rest
2688 static void implicit_weight_table(H264Context *h, int field)
2690 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2692 for (i = 0; i < 2; i++) {
2693 h->luma_weight_flag[i] = 0;
2694 h->chroma_weight_flag[i] = 0;
2698 if (h->picture_structure == PICT_FRAME) {
2699 cur_poc = h->cur_pic_ptr->poc;
2701 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2703 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2704 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2706 h->use_weight_chroma = 0;
2710 ref_count0 = h->ref_count[0];
2711 ref_count1 = h->ref_count[1];
2713 cur_poc = h->cur_pic_ptr->field_poc[field];
2715 ref_count0 = 16 + 2 * h->ref_count[0];
2716 ref_count1 = 16 + 2 * h->ref_count[1];
2720 h->use_weight_chroma = 2;
2721 h->luma_log2_weight_denom = 5;
2722 h->chroma_log2_weight_denom = 5;
2724 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2725 int poc0 = h->ref_list[0][ref0].poc;
2726 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2728 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2729 int poc1 = h->ref_list[1][ref1].poc;
2730 int td = av_clip(poc1 - poc0, -128, 127);
2732 int tb = av_clip(cur_poc - poc0, -128, 127);
2733 int tx = (16384 + (FFABS(td) >> 1)) / td;
2734 int dist_scale_factor = (tb * tx + 32) >> 8;
2735 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2736 w = 64 - dist_scale_factor;
2740 h->implicit_weight[ref0][ref1][0] =
2741 h->implicit_weight[ref0][ref1][1] = w;
2743 h->implicit_weight[ref0][ref1][field] = w;
2750 * instantaneous decoder refresh.
2752 static void idr(H264Context *h)
2754 ff_h264_remove_all_refs(h);
2755 h->prev_frame_num = 0;
2756 h->prev_frame_num_offset = 0;
2758 h->prev_poc_lsb = 0;
2761 /* forget old pics after a seek */
2762 static void flush_change(H264Context *h)
2765 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2766 h->last_pocs[i] = INT_MIN;
2767 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2768 h->prev_interlaced_frame = 1;
2771 h->cur_pic_ptr->reference = 0;
2773 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2774 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2775 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2776 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2777 ff_h264_reset_sei(h);
2778 h->recovery_frame = -1;
2779 h->frame_recovered = 0;
2782 /* forget old pics after a seek */
2783 static void flush_dpb(AVCodecContext *avctx)
2785 H264Context *h = avctx->priv_data;
2788 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2789 if (h->delayed_pic[i])
2790 h->delayed_pic[i]->reference = 0;
2791 h->delayed_pic[i] = NULL;
2797 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
2798 unref_picture(h, &h->DPB[i]);
2799 h->cur_pic_ptr = NULL;
2800 unref_picture(h, &h->cur_pic);
2802 h->mb_x = h->mb_y = 0;
2804 h->parse_context.state = -1;
2805 h->parse_context.frame_start_found = 0;
2806 h->parse_context.overread = 0;
2807 h->parse_context.overread_index = 0;
2808 h->parse_context.index = 0;
2809 h->parse_context.last_index = 0;
2812 h->context_initialized = 0;
2815 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2817 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2820 h->frame_num_offset = h->prev_frame_num_offset;
2821 if (h->frame_num < h->prev_frame_num)
2822 h->frame_num_offset += max_frame_num;
2824 if (h->sps.poc_type == 0) {
2825 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2827 if (h->poc_lsb < h->prev_poc_lsb &&
2828 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2829 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2830 else if (h->poc_lsb > h->prev_poc_lsb &&
2831 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2832 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2834 h->poc_msb = h->prev_poc_msb;
2836 field_poc[1] = h->poc_msb + h->poc_lsb;
2837 if (h->picture_structure == PICT_FRAME)
2838 field_poc[1] += h->delta_poc_bottom;
2839 } else if (h->sps.poc_type == 1) {
2840 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2843 if (h->sps.poc_cycle_length != 0)
2844 abs_frame_num = h->frame_num_offset + h->frame_num;
2848 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2851 expected_delta_per_poc_cycle = 0;
2852 for (i = 0; i < h->sps.poc_cycle_length; i++)
2853 // FIXME integrate during sps parse
2854 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2856 if (abs_frame_num > 0) {
2857 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2858 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2860 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2861 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2862 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2866 if (h->nal_ref_idc == 0)
2867 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2869 field_poc[0] = expectedpoc + h->delta_poc[0];
2870 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2872 if (h->picture_structure == PICT_FRAME)
2873 field_poc[1] += h->delta_poc[1];
2875 int poc = 2 * (h->frame_num_offset + h->frame_num);
2877 if (!h->nal_ref_idc)
2884 if (h->picture_structure != PICT_BOTTOM_FIELD)
2885 pic_field_poc[0] = field_poc[0];
2886 if (h->picture_structure != PICT_TOP_FIELD)
2887 pic_field_poc[1] = field_poc[1];
2888 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2894 * initialize scan tables
2896 static void init_scan_tables(H264Context *h)
2899 for (i = 0; i < 16; i++) {
2900 #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
2901 h->zigzag_scan[i] = TRANSPOSE(zigzag_scan[i]);
2902 h->field_scan[i] = TRANSPOSE(field_scan[i]);
2905 for (i = 0; i < 64; i++) {
2906 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
2907 h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
2908 h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
2909 h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
2910 h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
2913 if (h->sps.transform_bypass) { // FIXME same ugly
2914 h->zigzag_scan_q0 = zigzag_scan;
2915 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2916 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2917 h->field_scan_q0 = field_scan;
2918 h->field_scan8x8_q0 = field_scan8x8;
2919 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2921 h->zigzag_scan_q0 = h->zigzag_scan;
2922 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2923 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2924 h->field_scan_q0 = h->field_scan;
2925 h->field_scan8x8_q0 = h->field_scan8x8;
2926 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2930 #if CONFIG_ERROR_RESILIENCE
2931 static void h264_set_erpic(ERPicture *dst, H264Picture *src)
2941 for (i = 0; i < 2; i++) {
2942 dst->motion_val[i] = src->motion_val[i];
2943 dst->ref_index[i] = src->ref_index[i];
2946 dst->mb_type = src->mb_type;
2947 dst->field_picture = src->field_picture;
2949 #endif /* CONFIG_ERROR_RESILIENCE */
2951 static int field_end(H264Context *h, int in_setup)
2953 AVCodecContext *const avctx = h->avctx;
2957 if (!in_setup && !h->droppable)
2958 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2959 h->picture_structure == PICT_BOTTOM_FIELD);
2961 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2962 if (!h->droppable) {
2963 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2964 h->prev_poc_msb = h->poc_msb;
2965 h->prev_poc_lsb = h->poc_lsb;
2967 h->prev_frame_num_offset = h->frame_num_offset;
2968 h->prev_frame_num = h->frame_num;
2969 h->outputed_poc = h->next_outputed_poc;
2972 if (avctx->hwaccel) {
2973 if (avctx->hwaccel->end_frame(avctx) < 0)
2974 av_log(avctx, AV_LOG_ERROR,
2975 "hardware accelerator failed to decode picture\n");
2979 * FIXME: Error handling code does not seem to support interlaced
2980 * when slices span multiple rows
2981 * The ff_er_add_slice calls don't work right for bottom
2982 * fields; they cause massive erroneous error concealing
2983 * Error marking covers both fields (top and bottom).
2984 * This causes a mismatched s->error_count
2985 * and a bad error table. Further, the error count goes to
2986 * INT_MAX when called for bottom field, because mb_y is
2987 * past end by one (callers fault) and resync_mb_y != 0
2988 * causes problems for the first MB line, too.
2990 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h)) {
2991 h264_set_erpic(&h->er.cur_pic, h->cur_pic_ptr);
2992 h264_set_erpic(&h->er.last_pic,
2993 h->ref_count[0] ? &h->ref_list[0][0] : NULL);
2994 h264_set_erpic(&h->er.next_pic,
2995 h->ref_count[1] ? &h->ref_list[1][0] : NULL);
2996 ff_er_frame_end(&h->er);
3000 h->current_slice = 0;
3006 * Replicate H264 "master" context to thread contexts.
3008 static int clone_slice(H264Context *dst, H264Context *src)
3010 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
3011 dst->cur_pic_ptr = src->cur_pic_ptr;
3012 dst->cur_pic = src->cur_pic;
3013 dst->linesize = src->linesize;
3014 dst->uvlinesize = src->uvlinesize;
3015 dst->first_field = src->first_field;
3017 dst->prev_poc_msb = src->prev_poc_msb;
3018 dst->prev_poc_lsb = src->prev_poc_lsb;
3019 dst->prev_frame_num_offset = src->prev_frame_num_offset;
3020 dst->prev_frame_num = src->prev_frame_num;
3021 dst->short_ref_count = src->short_ref_count;
3023 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
3024 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
3025 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3027 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
3028 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
3034 * Compute profile from profile_idc and constraint_set?_flags.
3038 * @return profile as defined by FF_PROFILE_H264_*
3040 int ff_h264_get_profile(SPS *sps)
3042 int profile = sps->profile_idc;
3044 switch (sps->profile_idc) {
3045 case FF_PROFILE_H264_BASELINE:
3046 // constraint_set1_flag set to 1
3047 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3049 case FF_PROFILE_H264_HIGH_10:
3050 case FF_PROFILE_H264_HIGH_422:
3051 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3052 // constraint_set3_flag set to 1
3053 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3060 static int h264_set_parameter_from_sps(H264Context *h)
3062 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3063 (h->sps.bitstream_restriction_flag &&
3064 !h->sps.num_reorder_frames)) {
3065 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3066 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3067 "Reenabling low delay requires a codec flush.\n");
3072 if (h->avctx->has_b_frames < 2)
3073 h->avctx->has_b_frames = !h->low_delay;
3075 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3076 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
3077 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
3078 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3079 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
3080 h->pixel_shift = h->sps.bit_depth_luma > 8;
3082 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3083 h->sps.chroma_format_idc);
3084 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3085 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3086 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3087 h->sps.chroma_format_idc);
3088 if (CONFIG_ERROR_RESILIENCE)
3089 ff_dsputil_init(&h->dsp, h->avctx);
3090 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3092 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
3093 h->sps.bit_depth_luma);
3094 return AVERROR_INVALIDDATA;
3100 static enum AVPixelFormat get_pixel_format(H264Context *h)
3102 switch (h->sps.bit_depth_luma) {
3105 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3106 return AV_PIX_FMT_GBRP9;
3108 return AV_PIX_FMT_YUV444P9;
3109 } else if (CHROMA422(h))
3110 return AV_PIX_FMT_YUV422P9;
3112 return AV_PIX_FMT_YUV420P9;
3116 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3117 return AV_PIX_FMT_GBRP10;
3119 return AV_PIX_FMT_YUV444P10;
3120 } else if (CHROMA422(h))
3121 return AV_PIX_FMT_YUV422P10;
3123 return AV_PIX_FMT_YUV420P10;
3127 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3128 return AV_PIX_FMT_GBRP;
3130 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3131 : AV_PIX_FMT_YUV444P;
3132 } else if (CHROMA422(h)) {
3133 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3134 : AV_PIX_FMT_YUV422P;
3136 return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
3137 h->avctx->codec->pix_fmts :
3138 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3139 h264_hwaccel_pixfmt_list_jpeg_420 :
3140 h264_hwaccel_pixfmt_list_420);
3144 av_log(h->avctx, AV_LOG_ERROR,
3145 "Unsupported bit depth %d\n", h->sps.bit_depth_luma);
3146 return AVERROR_INVALIDDATA;
3150 /* export coded and cropped frame dimensions to AVCodecContext */
3151 static int init_dimensions(H264Context *h)
3153 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3154 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3156 /* handle container cropping */
3158 FFALIGN(h->avctx->width, 16) == h->width &&
3159 FFALIGN(h->avctx->height, 16) == h->height) {
3160 width = h->avctx->width;
3161 height = h->avctx->height;
3164 if (width <= 0 || height <= 0) {
3165 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3167 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3168 return AVERROR_INVALIDDATA;
3170 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3171 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3178 h->avctx->coded_width = h->width;
3179 h->avctx->coded_height = h->height;
3180 h->avctx->width = width;
3181 h->avctx->height = height;
3186 static int h264_slice_header_init(H264Context *h, int reinit)
3188 int nb_slices = (HAVE_THREADS &&
3189 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3190 h->avctx->thread_count : 1;
3193 h->avctx->sample_aspect_ratio = h->sps.sar;
3194 av_assert0(h->avctx->sample_aspect_ratio.den);
3195 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3196 &h->chroma_x_shift, &h->chroma_y_shift);
3198 if (h->sps.timing_info_present_flag) {
3199 int64_t den = h->sps.time_scale;
3200 if (h->x264_build < 44U)
3202 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3203 h->sps.num_units_in_tick, den, 1 << 30);
3206 h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3211 h->prev_interlaced_frame = 1;
3213 init_scan_tables(h);
3214 ret = ff_h264_alloc_tables(h);
3216 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
3220 if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3223 max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);
3225 max_slices = H264_MAX_THREADS;
3226 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"
3227 " reducing to %d\n", nb_slices, max_slices);
3228 nb_slices = max_slices;
3230 h->slice_context_count = nb_slices;
3232 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3233 ret = context_init(h);
3235 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3239 for (i = 1; i < h->slice_context_count; i++) {
3241 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3243 return AVERROR(ENOMEM);
3244 c->avctx = h->avctx;
3247 c->h264dsp = h->h264dsp;
3248 c->h264qpel = h->h264qpel;
3249 c->h264chroma = h->h264chroma;
3252 c->pixel_shift = h->pixel_shift;
3253 c->width = h->width;
3254 c->height = h->height;
3255 c->linesize = h->linesize;
3256 c->uvlinesize = h->uvlinesize;
3257 c->chroma_x_shift = h->chroma_x_shift;
3258 c->chroma_y_shift = h->chroma_y_shift;
3259 c->qscale = h->qscale;
3260 c->droppable = h->droppable;
3261 c->data_partitioning = h->data_partitioning;
3262 c->low_delay = h->low_delay;
3263 c->mb_width = h->mb_width;
3264 c->mb_height = h->mb_height;
3265 c->mb_stride = h->mb_stride;
3266 c->mb_num = h->mb_num;
3267 c->flags = h->flags;
3268 c->workaround_bugs = h->workaround_bugs;
3269 c->pict_type = h->pict_type;
3271 init_scan_tables(c);
3272 clone_tables(c, h, i);
3273 c->context_initialized = 1;
3276 for (i = 0; i < h->slice_context_count; i++)
3277 if ((ret = context_init(h->thread_context[i])) < 0) {
3278 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3283 h->context_initialized = 1;
3288 int ff_set_ref_count(H264Context *h)
3290 int ref_count[2], list_count;
3291 int num_ref_idx_active_override_flag, max_refs;
3293 // set defaults, might be overridden a few lines later
3294 ref_count[0] = h->pps.ref_count[0];
3295 ref_count[1] = h->pps.ref_count[1];
3297 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3298 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3299 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3300 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3302 if (num_ref_idx_active_override_flag) {
3303 ref_count[0] = get_ue_golomb(&h->gb) + 1;
3304 if (ref_count[0] < 1)
3305 return AVERROR_INVALIDDATA;
3306 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3307 ref_count[1] = get_ue_golomb(&h->gb) + 1;
3308 if (ref_count[1] < 1)
3309 return AVERROR_INVALIDDATA;
3313 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3319 ref_count[0] = ref_count[1] = 0;
3322 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
3324 if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
3325 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
3326 h->ref_count[0] = h->ref_count[1] = 0;
3327 return AVERROR_INVALIDDATA;
3330 if (list_count != h->list_count ||
3331 ref_count[0] != h->ref_count[0] ||
3332 ref_count[1] != h->ref_count[1]) {
3333 h->ref_count[0] = ref_count[0];
3334 h->ref_count[1] = ref_count[1];
3335 h->list_count = list_count;
3343 * Decode a slice header.
3344 * This will (re)intialize the decoder and call h264_frame_start() as needed.
3346 * @param h h264context
3347 * @param h0 h264 master context (differs from 'h' when doing sliced based
3348 * parallel decoding)
3350 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3352 static int decode_slice_header(H264Context *h, H264Context *h0)
3354 unsigned int first_mb_in_slice;
3355 unsigned int pps_id;
3357 unsigned int slice_type, tmp, i, j;
3358 int default_ref_list_done = 0;
3359 int last_pic_structure, last_pic_droppable;
3360 int needs_reinit = 0;
3361 int field_pic_flag, bottom_field_flag;
3363 h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3364 h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3366 first_mb_in_slice = get_ue_golomb(&h->gb);
3368 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3369 if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
3373 h0->current_slice = 0;
3374 if (!h0->first_field) {
3375 if (h->cur_pic_ptr && !h->droppable) {
3376 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3377 h->picture_structure == PICT_BOTTOM_FIELD);
3379 h->cur_pic_ptr = NULL;
3383 slice_type = get_ue_golomb_31(&h->gb);
3384 if (slice_type > 9) {
3385 av_log(h->avctx, AV_LOG_ERROR,
3386 "slice type %d too large at %d %d\n",
3387 slice_type, h->mb_x, h->mb_y);
3388 return AVERROR_INVALIDDATA;
3390 if (slice_type > 4) {
3392 h->slice_type_fixed = 1;
3394 h->slice_type_fixed = 0;
3396 slice_type = golomb_to_pict_type[slice_type];
3397 if (slice_type == AV_PICTURE_TYPE_I ||
3398 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3399 default_ref_list_done = 1;
3401 h->slice_type = slice_type;
3402 h->slice_type_nos = slice_type & 3;
3404 if (h->nal_unit_type == NAL_IDR_SLICE &&
3405 h->slice_type_nos != AV_PICTURE_TYPE_I) {
3406 av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
3407 return AVERROR_INVALIDDATA;
3410 // to make a few old functions happy, it's wrong though
3411 h->pict_type = h->slice_type;
3413 pps_id = get_ue_golomb(&h->gb);
3414 if (pps_id >= MAX_PPS_COUNT) {
3415 av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
3416 return AVERROR_INVALIDDATA;
3418 if (!h0->pps_buffers[pps_id]) {
3419 av_log(h->avctx, AV_LOG_ERROR,
3420 "non-existing PPS %u referenced\n",
3422 return AVERROR_INVALIDDATA;
3424 h->pps = *h0->pps_buffers[pps_id];
3426 if (!h0->sps_buffers[h->pps.sps_id]) {
3427 av_log(h->avctx, AV_LOG_ERROR,
3428 "non-existing SPS %u referenced\n",
3430 return AVERROR_INVALIDDATA;
3433 if (h->pps.sps_id != h->sps.sps_id ||
3434 h0->sps_buffers[h->pps.sps_id]->new) {
3435 h0->sps_buffers[h->pps.sps_id]->new = 0;
3437 h->sps = *h0->sps_buffers[h->pps.sps_id];
3439 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3440 h->chroma_format_idc != h->sps.chroma_format_idc) {
3441 h->bit_depth_luma = h->sps.bit_depth_luma;
3442 h->chroma_format_idc = h->sps.chroma_format_idc;
3445 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3449 h->avctx->profile = ff_h264_get_profile(&h->sps);
3450 h->avctx->level = h->sps.level_idc;
3451 h->avctx->refs = h->sps.ref_frame_count;
3453 if (h->mb_width != h->sps.mb_width ||
3454 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
3457 h->mb_width = h->sps.mb_width;
3458 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3459 h->mb_num = h->mb_width * h->mb_height;
3460 h->mb_stride = h->mb_width + 1;
3462 h->b_stride = h->mb_width * 4;
3464 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3466 h->width = 16 * h->mb_width;
3467 h->height = 16 * h->mb_height;
3469 ret = init_dimensions(h);
3473 if (h->sps.video_signal_type_present_flag) {
3474 h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
3476 if (h->sps.colour_description_present_flag) {
3477 if (h->avctx->colorspace != h->sps.colorspace)
3479 h->avctx->color_primaries = h->sps.color_primaries;
3480 h->avctx->color_trc = h->sps.color_trc;
3481 h->avctx->colorspace = h->sps.colorspace;
3485 if (h->context_initialized &&
3486 (h->width != h->avctx->coded_width ||
3487 h->height != h->avctx->coded_height ||
3490 av_log(h->avctx, AV_LOG_ERROR,
3491 "changing width %d -> %d / height %d -> %d on "
3493 h->width, h->avctx->coded_width,
3494 h->height, h->avctx->coded_height,
3495 h0->current_slice + 1);
3496 return AVERROR_INVALIDDATA;
3501 if ((ret = get_pixel_format(h)) < 0)
3503 h->avctx->pix_fmt = ret;
3505 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3506 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3508 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3509 av_log(h->avctx, AV_LOG_ERROR,
3510 "h264_slice_header_init() failed\n");
3514 if (!h->context_initialized) {
3516 av_log(h->avctx, AV_LOG_ERROR,
3517 "Cannot (re-)initialize context during parallel decoding.\n");
3518 return AVERROR_PATCHWELCOME;
3521 if ((ret = get_pixel_format(h)) < 0)
3523 h->avctx->pix_fmt = ret;
3525 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3526 av_log(h->avctx, AV_LOG_ERROR,
3527 "h264_slice_header_init() failed\n");
3532 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3533 h->dequant_coeff_pps = pps_id;
3534 init_dequant_tables(h);
3537 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3540 h->mb_aff_frame = 0;
3541 last_pic_structure = h0->picture_structure;
3542 last_pic_droppable = h0->droppable;
3543 h->droppable = h->nal_ref_idc == 0;
3544 if (h->sps.frame_mbs_only_flag) {
3545 h->picture_structure = PICT_FRAME;
3547 field_pic_flag = get_bits1(&h->gb);
3548 if (field_pic_flag) {
3549 bottom_field_flag = get_bits1(&h->gb);
3550 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3552 h->picture_structure = PICT_FRAME;
3553 h->mb_aff_frame = h->sps.mb_aff;
3556 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3558 if (h0->current_slice != 0) {
3559 if (last_pic_structure != h->picture_structure ||
3560 last_pic_droppable != h->droppable) {
3561 av_log(h->avctx, AV_LOG_ERROR,
3562 "Changing field mode (%d -> %d) between slices is not allowed\n",
3563 last_pic_structure, h->picture_structure);
3564 h->picture_structure = last_pic_structure;
3565 h->droppable = last_pic_droppable;
3566 return AVERROR_INVALIDDATA;
3567 } else if (!h0->cur_pic_ptr) {
3568 av_log(h->avctx, AV_LOG_ERROR,
3569 "unset cur_pic_ptr on slice %d\n",
3570 h0->current_slice + 1);
3571 return AVERROR_INVALIDDATA;
3574 /* Shorten frame num gaps so we don't have to allocate reference
3575 * frames just to throw them away */
3576 if (h->frame_num != h->prev_frame_num) {
3577 int unwrap_prev_frame_num = h->prev_frame_num;
3578 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3580 if (unwrap_prev_frame_num > h->frame_num)
3581 unwrap_prev_frame_num -= max_frame_num;
3583 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3584 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3585 if (unwrap_prev_frame_num < 0)
3586 unwrap_prev_frame_num += max_frame_num;
3588 h->prev_frame_num = unwrap_prev_frame_num;
3592 /* See if we have a decoded first field looking for a pair...
3593 * Here, we're using that to see if we should mark previously
3594 * decode frames as "finished".
3595 * We have to do that before the "dummy" in-between frame allocation,
3596 * since that can modify s->current_picture_ptr. */
3597 if (h0->first_field) {
3598 assert(h0->cur_pic_ptr);
3599 assert(h0->cur_pic_ptr->f.buf[0]);
3600 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3602 /* figure out if we have a complementary field pair */
3603 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3604 /* Previous field is unmatched. Don't display it, but let it
3605 * remain for reference if marked as such. */
3606 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3607 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3608 last_pic_structure == PICT_TOP_FIELD);
3611 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3612 /* This and previous field were reference, but had
3613 * different frame_nums. Consider this field first in
3614 * pair. Throw away previous field except for reference
3616 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3617 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3618 last_pic_structure == PICT_TOP_FIELD);
3621 /* Second field in complementary pair */
3622 if (!((last_pic_structure == PICT_TOP_FIELD &&
3623 h->picture_structure == PICT_BOTTOM_FIELD) ||
3624 (last_pic_structure == PICT_BOTTOM_FIELD &&
3625 h->picture_structure == PICT_TOP_FIELD))) {
3626 av_log(h->avctx, AV_LOG_ERROR,
3627 "Invalid field mode combination %d/%d\n",
3628 last_pic_structure, h->picture_structure);
3629 h->picture_structure = last_pic_structure;
3630 h->droppable = last_pic_droppable;
3631 return AVERROR_INVALIDDATA;
3632 } else if (last_pic_droppable != h->droppable) {
3633 avpriv_request_sample(h->avctx,
3634 "Found reference and non-reference fields in the same frame, which");
3635 h->picture_structure = last_pic_structure;
3636 h->droppable = last_pic_droppable;
3637 return AVERROR_PATCHWELCOME;
3643 while (h->frame_num != h->prev_frame_num &&
3644 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3645 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3646 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3647 h->frame_num, h->prev_frame_num);
3648 ret = h264_frame_start(h);
3650 h0->first_field = 0;
3654 h->prev_frame_num++;
3655 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3656 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3657 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3658 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3659 ret = ff_generate_sliding_window_mmcos(h, 1);
3660 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3662 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3663 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3665 /* Error concealment: If a ref is missing, copy the previous ref
3667 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3668 * many assumptions about there being no actual duplicates.
3669 * FIXME: This does not copy padding for out-of-frame motion
3670 * vectors. Given we are concealing a lost frame, this probably
3671 * is not noticeable by comparison, but it should be fixed. */
3672 if (h->short_ref_count) {
3674 av_image_copy(h->short_ref[0]->f.data,
3675 h->short_ref[0]->f.linesize,
3676 (const uint8_t **)prev->f.data,
3681 h->short_ref[0]->poc = prev->poc + 2;
3683 h->short_ref[0]->frame_num = h->prev_frame_num;
3687 /* See if we have a decoded first field looking for a pair...
3688 * We're using that to see whether to continue decoding in that
3689 * frame, or to allocate a new one. */
3690 if (h0->first_field) {
3691 assert(h0->cur_pic_ptr);
3692 assert(h0->cur_pic_ptr->f.buf[0]);
3693 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3695 /* figure out if we have a complementary field pair */
3696 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3697 /* Previous field is unmatched. Don't display it, but let it
3698 * remain for reference if marked as such. */
3699 h0->cur_pic_ptr = NULL;
3700 h0->first_field = FIELD_PICTURE(h);
3702 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3703 /* This and the previous field had different frame_nums.
3704 * Consider this field first in pair. Throw away previous
3705 * one except for reference purposes. */
3706 h0->first_field = 1;
3707 h0->cur_pic_ptr = NULL;
3709 /* Second field in complementary pair */
3710 h0->first_field = 0;
3714 /* Frame or first field in a potentially complementary pair */
3715 h0->first_field = FIELD_PICTURE(h);
3718 if (!FIELD_PICTURE(h) || h0->first_field) {
3719 if (h264_frame_start(h) < 0) {
3720 h0->first_field = 0;
3721 return AVERROR_INVALIDDATA;
3724 release_unused_pictures(h, 0);
3727 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3730 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3732 assert(h->mb_num == h->mb_width * h->mb_height);
3733 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3734 first_mb_in_slice >= h->mb_num) {
3735 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3736 return AVERROR_INVALIDDATA;
3738 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3739 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3740 FIELD_OR_MBAFF_PICTURE(h);
3741 if (h->picture_structure == PICT_BOTTOM_FIELD)
3742 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3743 assert(h->mb_y < h->mb_height);
3745 if (h->picture_structure == PICT_FRAME) {
3746 h->curr_pic_num = h->frame_num;
3747 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3749 h->curr_pic_num = 2 * h->frame_num + 1;
3750 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3753 if (h->nal_unit_type == NAL_IDR_SLICE)
3754 get_ue_golomb(&h->gb); /* idr_pic_id */
3756 if (h->sps.poc_type == 0) {
3757 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3759 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3760 h->delta_poc_bottom = get_se_golomb(&h->gb);
3763 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3764 h->delta_poc[0] = get_se_golomb(&h->gb);
3766 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3767 h->delta_poc[1] = get_se_golomb(&h->gb);
3770 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3772 if (h->pps.redundant_pic_cnt_present)
3773 h->redundant_pic_count = get_ue_golomb(&h->gb);
3775 ret = ff_set_ref_count(h);
3779 default_ref_list_done = 0;
3781 if (!default_ref_list_done)
3782 ff_h264_fill_default_ref_list(h);
3784 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3785 ret = ff_h264_decode_ref_pic_list_reordering(h);
3787 h->ref_count[1] = h->ref_count[0] = 0;
3792 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3793 (h->pps.weighted_bipred_idc == 1 &&
3794 h->slice_type_nos == AV_PICTURE_TYPE_B))
3795 ff_pred_weight_table(h);
3796 else if (h->pps.weighted_bipred_idc == 2 &&
3797 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3798 implicit_weight_table(h, -1);
3801 for (i = 0; i < 2; i++) {
3802 h->luma_weight_flag[i] = 0;
3803 h->chroma_weight_flag[i] = 0;
3807 // If frame-mt is enabled, only update mmco tables for the first slice
3808 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3809 // or h->mmco, which will cause ref list mix-ups and decoding errors
3810 // further down the line. This may break decoding if the first slice is
3811 // corrupt, thus we only do this if frame-mt is enabled.
3812 if (h->nal_ref_idc) {
3813 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3814 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3815 h0->current_slice == 0);
3816 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3817 return AVERROR_INVALIDDATA;
3820 if (FRAME_MBAFF(h)) {
3821 ff_h264_fill_mbaff_ref_list(h);
3823 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3824 implicit_weight_table(h, 0);
3825 implicit_weight_table(h, 1);
3829 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3830 ff_h264_direct_dist_scale_factor(h);
3831 ff_h264_direct_ref_list_init(h);
3833 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3834 tmp = get_ue_golomb_31(&h->gb);
3836 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
3837 return AVERROR_INVALIDDATA;
3839 h->cabac_init_idc = tmp;
3842 h->last_qscale_diff = 0;
3843 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3844 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3845 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3846 return AVERROR_INVALIDDATA;
3849 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3850 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3851 // FIXME qscale / qp ... stuff
3852 if (h->slice_type == AV_PICTURE_TYPE_SP)
3853 get_bits1(&h->gb); /* sp_for_switch_flag */
3854 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3855 h->slice_type == AV_PICTURE_TYPE_SI)
3856 get_se_golomb(&h->gb); /* slice_qs_delta */
3858 h->deblocking_filter = 1;
3859 h->slice_alpha_c0_offset = 0;
3860 h->slice_beta_offset = 0;
3861 if (h->pps.deblocking_filter_parameters_present) {
3862 tmp = get_ue_golomb_31(&h->gb);
3864 av_log(h->avctx, AV_LOG_ERROR,
3865 "deblocking_filter_idc %u out of range\n", tmp);
3866 return AVERROR_INVALIDDATA;
3868 h->deblocking_filter = tmp;
3869 if (h->deblocking_filter < 2)
3870 h->deblocking_filter ^= 1; // 1<->0
3872 if (h->deblocking_filter) {
3873 h->slice_alpha_c0_offset = get_se_golomb(&h->gb) * 2;
3874 h->slice_beta_offset = get_se_golomb(&h->gb) * 2;
3875 if (h->slice_alpha_c0_offset > 12 ||
3876 h->slice_alpha_c0_offset < -12 ||
3877 h->slice_beta_offset > 12 ||
3878 h->slice_beta_offset < -12) {
3879 av_log(h->avctx, AV_LOG_ERROR,
3880 "deblocking filter parameters %d %d out of range\n",
3881 h->slice_alpha_c0_offset, h->slice_beta_offset);
3882 return AVERROR_INVALIDDATA;
3887 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3888 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3889 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3890 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3891 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3892 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3893 h->nal_ref_idc == 0))
3894 h->deblocking_filter = 0;
3896 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3897 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3898 /* Cheat slightly for speed:
3899 * Do not bother to deblock across slices. */
3900 h->deblocking_filter = 2;
3902 h0->max_contexts = 1;
3903 if (!h0->single_decode_warning) {
3904 av_log(h->avctx, AV_LOG_INFO,
3905 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3906 h0->single_decode_warning = 1;
3909 av_log(h->avctx, AV_LOG_ERROR,
3910 "Deblocking switched inside frame.\n");
3916 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3918 h->pps.chroma_qp_index_offset[0],
3919 h->pps.chroma_qp_index_offset[1]) +
3920 6 * (h->sps.bit_depth_luma - 8);
3922 h0->last_slice_type = slice_type;
3923 h->slice_num = ++h0->current_slice;
3924 if (h->slice_num >= MAX_SLICES) {
3925 av_log(h->avctx, AV_LOG_ERROR,
3926 "Too many slices, increase MAX_SLICES and recompile\n");
3929 for (j = 0; j < 2; j++) {
3931 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3932 for (i = 0; i < 16; i++) {
3934 if (j < h->list_count && i < h->ref_count[j] &&
3935 h->ref_list[j][i].f.buf[0]) {
3937 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
3938 for (k = 0; k < h->short_ref_count; k++)
3939 if (h->short_ref[k]->f.buf[0]->buffer == buf) {
3943 for (k = 0; k < h->long_ref_count; k++)
3944 if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
3945 id_list[i] = h->short_ref_count + k;
3953 for (i = 0; i < 16; i++)
3954 ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
3956 ref2frm[18 + 1] = -1;
3957 for (i = 16; i < 48; i++)
3958 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3959 (h->ref_list[j][i].reference & 3);
3962 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
3963 av_log(h->avctx, AV_LOG_DEBUG,
3964 "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",
3966 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3968 av_get_picture_type_char(h->slice_type),
3969 h->slice_type_fixed ? " fix" : "",
3970 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3971 pps_id, h->frame_num,
3972 h->cur_pic_ptr->field_poc[0],
3973 h->cur_pic_ptr->field_poc[1],
3974 h->ref_count[0], h->ref_count[1],
3976 h->deblocking_filter,
3977 h->slice_alpha_c0_offset, h->slice_beta_offset,
3979 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3980 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3986 int ff_h264_get_slice_type(const H264Context *h)
3988 switch (h->slice_type) {
3989 case AV_PICTURE_TYPE_P:
3991 case AV_PICTURE_TYPE_B:
3993 case AV_PICTURE_TYPE_I:
3995 case AV_PICTURE_TYPE_SP:
3997 case AV_PICTURE_TYPE_SI:
4000 return AVERROR_INVALIDDATA;
4004 static av_always_inline void fill_filter_caches_inter(H264Context *h,
4005 int mb_type, int top_xy,
4006 int left_xy[LEFT_MBS],
4008 int left_type[LEFT_MBS],
4009 int mb_xy, int list)
4011 int b_stride = h->b_stride;
4012 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4013 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4014 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4015 if (USES_LIST(top_type, list)) {
4016 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
4017 const int b8_xy = 4 * top_xy + 2;
4018 int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
4019 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4020 ref_cache[0 - 1 * 8] =
4021 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4022 ref_cache[2 - 1 * 8] =
4023 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4025 AV_ZERO128(mv_dst - 1 * 8);
4026 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4029 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4030 if (USES_LIST(left_type[LTOP], list)) {
4031 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
4032 const int b8_xy = 4 * left_xy[LTOP] + 1;
4033 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
4034 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4035 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4036 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4037 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4039 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4040 ref_cache[-1 + 16] =
4041 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4043 AV_ZERO32(mv_dst - 1 + 0);
4044 AV_ZERO32(mv_dst - 1 + 8);
4045 AV_ZERO32(mv_dst - 1 + 16);
4046 AV_ZERO32(mv_dst - 1 + 24);
4049 ref_cache[-1 + 16] =
4050 ref_cache[-1 + 24] = LIST_NOT_USED;
4055 if (!USES_LIST(mb_type, list)) {
4056 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4057 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4058 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4059 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4060 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4065 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4066 int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
4067 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4068 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4069 AV_WN32A(&ref_cache[0 * 8], ref01);
4070 AV_WN32A(&ref_cache[1 * 8], ref01);
4071 AV_WN32A(&ref_cache[2 * 8], ref23);
4072 AV_WN32A(&ref_cache[3 * 8], ref23);
4076 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4077 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4078 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4079 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4080 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4086 * @return non zero if the loop filter can be skipped
4088 static int fill_filter_caches(H264Context *h, int mb_type)
4090 const int mb_xy = h->mb_xy;
4091 int top_xy, left_xy[LEFT_MBS];
4092 int top_type, left_type[LEFT_MBS];
4096 top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4098 /* Wow, what a mess, why didn't they simplify the interlacing & intra
4099 * stuff, I can't imagine that these complex rules are worth it. */
4101 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4102 if (FRAME_MBAFF(h)) {
4103 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4104 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4106 if (left_mb_field_flag != curr_mb_field_flag)
4107 left_xy[LTOP] -= h->mb_stride;
4109 if (curr_mb_field_flag)
4110 top_xy += h->mb_stride &
4111 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4112 if (left_mb_field_flag != curr_mb_field_flag)
4113 left_xy[LBOT] += h->mb_stride;
4117 h->top_mb_xy = top_xy;
4118 h->left_mb_xy[LTOP] = left_xy[LTOP];
4119 h->left_mb_xy[LBOT] = left_xy[LBOT];
4121 /* For sufficiently low qp, filtering wouldn't do anything.
4122 * This is a conservative estimate: could also check beta_offset
4123 * and more accurate chroma_qp. */
4124 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4125 int qp = h->cur_pic.qscale_table[mb_xy];
4126 if (qp <= qp_thresh &&
4127 (left_xy[LTOP] < 0 ||
4128 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4130 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4131 if (!FRAME_MBAFF(h))
4133 if ((left_xy[LTOP] < 0 ||
4134 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4135 (top_xy < h->mb_stride ||
4136 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4141 top_type = h->cur_pic.mb_type[top_xy];
4142 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4143 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4144 if (h->deblocking_filter == 2) {
4145 if (h->slice_table[top_xy] != h->slice_num)
4147 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4148 left_type[LTOP] = left_type[LBOT] = 0;
4150 if (h->slice_table[top_xy] == 0xFFFF)
4152 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4153 left_type[LTOP] = left_type[LBOT] = 0;
4155 h->top_type = top_type;
4156 h->left_type[LTOP] = left_type[LTOP];
4157 h->left_type[LBOT] = left_type[LBOT];
4159 if (IS_INTRA(mb_type))
4162 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4163 top_type, left_type, mb_xy, 0);
4164 if (h->list_count == 2)
4165 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4166 top_type, left_type, mb_xy, 1);
4168 nnz = h->non_zero_count[mb_xy];
4169 nnz_cache = h->non_zero_count_cache;
4170 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4171 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4172 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4173 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4174 h->cbp = h->cbp_table[mb_xy];
4177 nnz = h->non_zero_count[top_xy];
4178 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4181 if (left_type[LTOP]) {
4182 nnz = h->non_zero_count[left_xy[LTOP]];
4183 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4184 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4185 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4186 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4189 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4190 * from what the loop filter needs */
4191 if (!CABAC(h) && h->pps.transform_8x8_mode) {
4192 if (IS_8x8DCT(top_type)) {
4193 nnz_cache[4 + 8 * 0] =
4194 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4195 nnz_cache[6 + 8 * 0] =
4196 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4198 if (IS_8x8DCT(left_type[LTOP])) {
4199 nnz_cache[3 + 8 * 1] =
4200 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4202 if (IS_8x8DCT(left_type[LBOT])) {
4203 nnz_cache[3 + 8 * 3] =
4204 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4207 if (IS_8x8DCT(mb_type)) {
4208 nnz_cache[scan8[0]] =
4209 nnz_cache[scan8[1]] =
4210 nnz_cache[scan8[2]] =
4211 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4213 nnz_cache[scan8[0 + 4]] =
4214 nnz_cache[scan8[1 + 4]] =
4215 nnz_cache[scan8[2 + 4]] =
4216 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4218 nnz_cache[scan8[0 + 8]] =
4219 nnz_cache[scan8[1 + 8]] =
4220 nnz_cache[scan8[2 + 8]] =
4221 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4223 nnz_cache[scan8[0 + 12]] =
4224 nnz_cache[scan8[1 + 12]] =
4225 nnz_cache[scan8[2 + 12]] =
4226 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4233 static void loop_filter(H264Context *h, int start_x, int end_x)
4235 uint8_t *dest_y, *dest_cb, *dest_cr;
4236 int linesize, uvlinesize, mb_x, mb_y;
4237 const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4238 const int old_slice_type = h->slice_type;
4239 const int pixel_shift = h->pixel_shift;
4240 const int block_h = 16 >> h->chroma_y_shift;
4242 if (h->deblocking_filter) {
4243 for (mb_x = start_x; mb_x < end_x; mb_x++)
4244 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4246 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4247 h->slice_num = h->slice_table[mb_xy];
4248 mb_type = h->cur_pic.mb_type[mb_xy];
4249 h->list_count = h->list_counts[mb_xy];
4253 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4257 dest_y = h->cur_pic.f.data[0] +
4258 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4259 dest_cb = h->cur_pic.f.data[1] +
4260 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4261 mb_y * h->uvlinesize * block_h;
4262 dest_cr = h->cur_pic.f.data[2] +
4263 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4264 mb_y * h->uvlinesize * block_h;
4265 // FIXME simplify above
4268 linesize = h->mb_linesize = h->linesize * 2;
4269 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4270 if (mb_y & 1) { // FIXME move out of this function?
4271 dest_y -= h->linesize * 15;
4272 dest_cb -= h->uvlinesize * (block_h - 1);
4273 dest_cr -= h->uvlinesize * (block_h - 1);
4276 linesize = h->mb_linesize = h->linesize;
4277 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4279 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4281 if (fill_filter_caches(h, mb_type))
4283 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4284 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4286 if (FRAME_MBAFF(h)) {
4287 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4288 linesize, uvlinesize);
4290 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4291 dest_cr, linesize, uvlinesize);
4295 h->slice_type = old_slice_type;
4297 h->mb_y = end_mb_y - FRAME_MBAFF(h);
4298 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4299 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4302 static void predict_field_decoding_flag(H264Context *h)
4304 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4305 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4306 h->cur_pic.mb_type[mb_xy - 1] :
4307 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4308 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4309 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4313 * Draw edges and report progress for the last MB row.
4315 static void decode_finish_row(H264Context *h)
4317 int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4318 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4319 int height = 16 << FRAME_MBAFF(h);
4320 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4322 if (h->deblocking_filter) {
4323 if ((top + height) >= pic_height)
4324 height += deblock_border;
4325 top -= deblock_border;
4328 if (top >= pic_height || (top + height) < 0)
4331 height = FFMIN(height, pic_height - top);
4333 height = top + height;
4337 ff_h264_draw_horiz_band(h, top, height);
4342 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4343 h->picture_structure == PICT_BOTTOM_FIELD);
4346 static void er_add_slice(H264Context *h, int startx, int starty,
4347 int endx, int endy, int status)
4349 #if CONFIG_ERROR_RESILIENCE
4350 ERContext *er = &h->er;
4352 er->ref_count = h->ref_count[0];
4353 ff_er_add_slice(er, startx, starty, endx, endy, status);
4357 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4359 H264Context *h = *(void **)arg;
4360 int lf_x_start = h->mb_x;
4362 h->mb_skip_run = -1;
4364 h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4365 avctx->codec_id != AV_CODEC_ID_H264 ||
4366 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4370 align_get_bits(&h->gb);
4373 ff_init_cabac_decoder(&h->cabac,
4374 h->gb.buffer + get_bits_count(&h->gb) / 8,
4375 (get_bits_left(&h->gb) + 7) / 8);
4377 ff_h264_init_cabac_states(h);
4381 int ret = ff_h264_decode_mb_cabac(h);
4383 // STOP_TIMER("decode_mb_cabac")
4386 ff_h264_hl_decode_mb(h);
4388 // FIXME optimal? or let mb_decode decode 16x32 ?
4389 if (ret >= 0 && FRAME_MBAFF(h)) {
4392 ret = ff_h264_decode_mb_cabac(h);
4395 ff_h264_hl_decode_mb(h);
4398 eos = get_cabac_terminate(&h->cabac);
4400 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4401 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4402 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4403 h->mb_y, ER_MB_END);
4404 if (h->mb_x >= lf_x_start)
4405 loop_filter(h, lf_x_start, h->mb_x + 1);
4408 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4409 av_log(h->avctx, AV_LOG_ERROR,
4410 "error while decoding MB %d %d, bytestream %td\n",
4412 h->cabac.bytestream_end - h->cabac.bytestream);
4413 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4414 h->mb_y, ER_MB_ERROR);
4415 return AVERROR_INVALIDDATA;
4418 if (++h->mb_x >= h->mb_width) {
4419 loop_filter(h, lf_x_start, h->mb_x);
4420 h->mb_x = lf_x_start = 0;
4421 decode_finish_row(h);
4423 if (FIELD_OR_MBAFF_PICTURE(h)) {
4425 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4426 predict_field_decoding_flag(h);
4430 if (eos || h->mb_y >= h->mb_height) {
4431 tprintf(h->avctx, "slice end %d %d\n",
4432 get_bits_count(&h->gb), h->gb.size_in_bits);
4433 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4434 h->mb_y, ER_MB_END);
4435 if (h->mb_x > lf_x_start)
4436 loop_filter(h, lf_x_start, h->mb_x);
4442 int ret = ff_h264_decode_mb_cavlc(h);
4445 ff_h264_hl_decode_mb(h);
4447 // FIXME optimal? or let mb_decode decode 16x32 ?
4448 if (ret >= 0 && FRAME_MBAFF(h)) {
4450 ret = ff_h264_decode_mb_cavlc(h);
4453 ff_h264_hl_decode_mb(h);
4458 av_log(h->avctx, AV_LOG_ERROR,
4459 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4460 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4461 h->mb_y, ER_MB_ERROR);
4465 if (++h->mb_x >= h->mb_width) {
4466 loop_filter(h, lf_x_start, h->mb_x);
4467 h->mb_x = lf_x_start = 0;
4468 decode_finish_row(h);
4470 if (FIELD_OR_MBAFF_PICTURE(h)) {
4472 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4473 predict_field_decoding_flag(h);
4475 if (h->mb_y >= h->mb_height) {
4476 tprintf(h->avctx, "slice end %d %d\n",
4477 get_bits_count(&h->gb), h->gb.size_in_bits);
4479 if (get_bits_left(&h->gb) == 0) {
4480 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4481 h->mb_x - 1, h->mb_y,
4486 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4487 h->mb_x - 1, h->mb_y,
4490 return AVERROR_INVALIDDATA;
4495 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4496 tprintf(h->avctx, "slice end %d %d\n",
4497 get_bits_count(&h->gb), h->gb.size_in_bits);
4499 if (get_bits_left(&h->gb) == 0) {
4500 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4501 h->mb_x - 1, h->mb_y,
4503 if (h->mb_x > lf_x_start)
4504 loop_filter(h, lf_x_start, h->mb_x);
4508 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4509 h->mb_y, ER_MB_ERROR);
4511 return AVERROR_INVALIDDATA;
4519 * Call decode_slice() for each context.
4521 * @param h h264 master context
4522 * @param context_count number of contexts to execute
4524 static int execute_decode_slices(H264Context *h, unsigned context_count)
4526 AVCodecContext *const avctx = h->avctx;
4530 if (h->mb_y >= h->mb_height) {
4531 av_log(h->avctx, AV_LOG_ERROR,
4532 "Input contains more MB rows than the frame height.\n");
4533 return AVERROR_INVALIDDATA;
4536 if (h->avctx->hwaccel)
4538 if (context_count == 1) {
4539 return decode_slice(avctx, &h);
4541 for (i = 1; i < context_count; i++) {
4542 hx = h->thread_context[i];
4543 hx->er.error_count = 0;
4546 avctx->execute(avctx, decode_slice, h->thread_context,
4547 NULL, context_count, sizeof(void *));
4549 /* pull back stuff from slices to master context */
4550 hx = h->thread_context[context_count - 1];
4553 h->droppable = hx->droppable;
4554 h->picture_structure = hx->picture_structure;
4555 for (i = 1; i < context_count; i++)
4556 h->er.error_count += h->thread_context[i]->er.error_count;
4562 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4563 int parse_extradata)
4565 AVCodecContext *const avctx = h->avctx;
4566 H264Context *hx; ///< thread context
4568 unsigned context_count;
4570 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4571 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4575 h->max_contexts = h->slice_context_count;
4576 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4577 h->current_slice = 0;
4578 if (!h->first_field)
4579 h->cur_pic_ptr = NULL;
4580 ff_h264_reset_sei(h);
4583 for (; pass <= 1; pass++) {
4586 next_avc = h->is_avc ? 0 : buf_size;
4596 if (buf_index >= next_avc) {
4597 if (buf_index >= buf_size - h->nal_length_size)
4600 for (i = 0; i < h->nal_length_size; i++)
4601 nalsize = (nalsize << 8) | buf[buf_index++];
4602 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4603 av_log(h->avctx, AV_LOG_ERROR,
4604 "AVC: nal size %d\n", nalsize);
4607 next_avc = buf_index + nalsize;
4609 // start code prefix search
4610 for (; buf_index + 3 < next_avc; buf_index++)
4611 // This should always succeed in the first iteration.
4612 if (buf[buf_index] == 0 &&
4613 buf[buf_index + 1] == 0 &&
4614 buf[buf_index + 2] == 1)
4617 if (buf_index + 3 >= buf_size) {
4618 buf_index = buf_size;
4623 if (buf_index >= next_avc)
4627 hx = h->thread_context[context_count];
4629 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4630 &consumed, next_avc - buf_index);
4631 if (ptr == NULL || dst_length < 0) {
4635 i = buf_index + consumed;
4636 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4637 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4638 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4639 h->workaround_bugs |= FF_BUG_TRUNCATED;
4641 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4642 while (dst_length > 0 && ptr[dst_length - 1] == 0)
4644 bit_length = !dst_length ? 0
4646 decode_rbsp_trailing(h, ptr + dst_length - 1));
4648 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4649 av_log(h->avctx, AV_LOG_DEBUG,
4650 "NAL %d at %d/%d length %d\n",
4651 hx->nal_unit_type, buf_index, buf_size, dst_length);
4653 if (h->is_avc && (nalsize != consumed) && nalsize)
4654 av_log(h->avctx, AV_LOG_DEBUG,
4655 "AVC: Consumed only %d bytes instead of %d\n",
4658 buf_index += consumed;
4662 /* packets can sometimes contain multiple PPS/SPS,
4663 * e.g. two PAFF field pictures in one packet, or a demuxer
4664 * which splits NALs strangely if so, when frame threading we
4665 * can't start the next thread until we've read all of them */
4666 switch (hx->nal_unit_type) {
4669 nals_needed = nal_index;
4674 init_get_bits(&hx->gb, ptr, bit_length);
4675 if (!get_ue_golomb(&hx->gb))
4676 nals_needed = nal_index;
4681 if (avctx->skip_frame >= AVDISCARD_NONREF &&
4682 h->nal_ref_idc == 0 &&
4683 h->nal_unit_type != NAL_SEI)
4687 /* Ignore every NAL unit type except PPS and SPS during extradata
4688 * parsing. Decoding slices is not possible in codec init
4690 if (parse_extradata && HAVE_THREADS &&
4691 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
4692 (hx->nal_unit_type != NAL_PPS &&
4693 hx->nal_unit_type != NAL_SPS)) {
4694 if (hx->nal_unit_type < NAL_AUD ||
4695 hx->nal_unit_type > NAL_AUXILIARY_SLICE)
4696 av_log(avctx, AV_LOG_INFO,
4697 "Ignoring NAL unit %d during extradata parsing\n",
4699 hx->nal_unit_type = NAL_FF_IGNORE;
4702 switch (hx->nal_unit_type) {
4704 if (h->nal_unit_type != NAL_IDR_SLICE) {
4705 av_log(h->avctx, AV_LOG_ERROR,
4706 "Invalid mix of idr and non-idr slices\n");
4710 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4712 init_get_bits(&hx->gb, ptr, bit_length);
4714 hx->inter_gb_ptr = &hx->gb;
4715 hx->data_partitioning = 0;
4717 if ((err = decode_slice_header(hx, h)))
4720 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
4721 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4722 ((1 << h->sps.log2_max_frame_num) - 1);
4725 h->cur_pic_ptr->f.key_frame |=
4726 (hx->nal_unit_type == NAL_IDR_SLICE) ||
4727 (h->sei_recovery_frame_cnt >= 0);
4729 if (hx->nal_unit_type == NAL_IDR_SLICE ||
4730 h->recovery_frame == h->frame_num) {
4731 h->recovery_frame = -1;
4732 h->cur_pic_ptr->recovered = 1;
4734 // If we have an IDR, all frames after it in decoded order are
4736 if (hx->nal_unit_type == NAL_IDR_SLICE)
4737 h->frame_recovered |= FRAME_RECOVERED_IDR;
4738 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
4740 if (h->current_slice == 1) {
4741 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4742 decode_postinit(h, nal_index >= nals_needed);
4744 if (h->avctx->hwaccel &&
4745 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4749 if (hx->redundant_pic_count == 0 &&
4750 (avctx->skip_frame < AVDISCARD_NONREF ||
4752 (avctx->skip_frame < AVDISCARD_BIDIR ||
4753 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4754 (avctx->skip_frame < AVDISCARD_NONKEY ||
4755 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4756 avctx->skip_frame < AVDISCARD_ALL) {
4757 if (avctx->hwaccel) {
4758 ret = avctx->hwaccel->decode_slice(avctx,
4759 &buf[buf_index - consumed],
4768 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
4769 av_log(h->avctx, AV_LOG_ERROR,
4770 "Decoding in chunks is not supported for "
4771 "partitioned slices.\n");
4772 return AVERROR(ENOSYS);
4775 init_get_bits(&hx->gb, ptr, bit_length);
4777 hx->inter_gb_ptr = NULL;
4779 if ((err = decode_slice_header(hx, h)) < 0) {
4780 /* make sure data_partitioning is cleared if it was set
4781 * before, so we don't try decoding a slice without a valid
4782 * slice header later */
4783 h->data_partitioning = 0;
4787 hx->data_partitioning = 1;
4790 init_get_bits(&hx->intra_gb, ptr, bit_length);
4791 hx->intra_gb_ptr = &hx->intra_gb;
4794 init_get_bits(&hx->inter_gb, ptr, bit_length);
4795 hx->inter_gb_ptr = &hx->inter_gb;
4797 if (hx->redundant_pic_count == 0 &&
4799 hx->data_partitioning &&
4800 h->cur_pic_ptr && h->context_initialized &&
4801 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4802 (avctx->skip_frame < AVDISCARD_BIDIR ||
4803 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4804 (avctx->skip_frame < AVDISCARD_NONKEY ||
4805 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4806 avctx->skip_frame < AVDISCARD_ALL)
4810 init_get_bits(&h->gb, ptr, bit_length);
4811 ff_h264_decode_sei(h);
4814 init_get_bits(&h->gb, ptr, bit_length);
4815 ret = ff_h264_decode_seq_parameter_set(h);
4816 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
4817 av_log(h->avctx, AV_LOG_DEBUG,
4818 "SPS decoding failure, trying again with the complete NAL\n");
4819 init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
4821 ff_h264_decode_seq_parameter_set(h);
4824 ret = h264_set_parameter_from_sps(h);
4830 init_get_bits(&h->gb, ptr, bit_length);
4831 ff_h264_decode_picture_parameter_set(h, bit_length);
4834 case NAL_END_SEQUENCE:
4835 case NAL_END_STREAM:
4836 case NAL_FILLER_DATA:
4838 case NAL_AUXILIARY_SLICE:
4843 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4844 hx->nal_unit_type, bit_length);
4847 if (context_count == h->max_contexts) {
4848 execute_decode_slices(h, context_count);
4853 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4854 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
4855 } else if (err == 1) {
4856 /* Slice could not be decoded in parallel mode, copy down
4857 * NAL unit stuff to context 0 and restart. Note that
4858 * rbsp_buffer is not transferred, but since we no longer
4859 * run in parallel mode this should not be an issue. */
4860 h->nal_unit_type = hx->nal_unit_type;
4861 h->nal_ref_idc = hx->nal_ref_idc;
4868 execute_decode_slices(h, context_count);
4872 if (h->cur_pic_ptr && !h->droppable) {
4873 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
4874 h->picture_structure == PICT_BOTTOM_FIELD);
4877 return (ret < 0) ? ret : buf_index;
4881 * Return the number of bytes consumed for building the current frame.
4883 static int get_consumed_bytes(int pos, int buf_size)
4886 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4887 if (pos + 10 > buf_size)
4888 pos = buf_size; // oops ;)
4893 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
4896 int ret = av_frame_ref(dst, src);
4903 for (i = 0; i < 3; i++) {
4904 int hshift = (i > 0) ? h->chroma_x_shift : 0;
4905 int vshift = (i > 0) ? h->chroma_y_shift : 0;
4906 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
4907 (h->sps.crop_top >> vshift) * dst->linesize[i];
4908 dst->data[i] += off;
4913 static int h264_decode_frame(AVCodecContext *avctx, void *data,
4914 int *got_frame, AVPacket *avpkt)
4916 const uint8_t *buf = avpkt->data;
4917 int buf_size = avpkt->size;
4918 H264Context *h = avctx->priv_data;
4919 AVFrame *pict = data;
4923 h->flags = avctx->flags;
4924 /* reset data partitioning here, to ensure GetBitContexts from previous
4925 * packets do not get used. */
4926 h->data_partitioning = 0;
4928 /* end of stream, output what is still in the buffers */
4930 if (buf_size == 0) {
4934 h->cur_pic_ptr = NULL;
4936 // FIXME factorize this with the output code below
4937 out = h->delayed_pic[0];
4940 h->delayed_pic[i] &&
4941 !h->delayed_pic[i]->f.key_frame &&
4942 !h->delayed_pic[i]->mmco_reset;
4944 if (h->delayed_pic[i]->poc < out->poc) {
4945 out = h->delayed_pic[i];
4949 for (i = out_idx; h->delayed_pic[i]; i++)
4950 h->delayed_pic[i] = h->delayed_pic[i + 1];
4953 ret = output_frame(h, pict, &out->f);
4962 buf_index = decode_nal_units(h, buf, buf_size, 0);
4964 return AVERROR_INVALIDDATA;
4966 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4971 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
4972 if (avctx->skip_frame >= AVDISCARD_NONREF)
4974 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4975 return AVERROR_INVALIDDATA;
4978 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
4979 (h->mb_y >= h->mb_height && h->mb_height)) {
4980 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
4981 decode_postinit(h, 1);
4986 if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
4987 h->next_output_pic->recovered)) {
4988 if (!h->next_output_pic->recovered)
4989 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
4991 ret = output_frame(h, pict, &h->next_output_pic->f);
4998 assert(pict->buf[0] || !*got_frame);
5000 return get_consumed_bytes(buf_index, buf_size);
5003 av_cold void ff_h264_free_context(H264Context *h)
5007 free_tables(h, 1); // FIXME cleanup init stuff perhaps
5009 for (i = 0; i < MAX_SPS_COUNT; i++)
5010 av_freep(h->sps_buffers + i);
5012 for (i = 0; i < MAX_PPS_COUNT; i++)
5013 av_freep(h->pps_buffers + i);
5016 static av_cold int h264_decode_end(AVCodecContext *avctx)
5018 H264Context *h = avctx->priv_data;
5020 ff_h264_free_context(h);
5022 unref_picture(h, &h->cur_pic);
5027 static const AVProfile profiles[] = {
5028 { FF_PROFILE_H264_BASELINE, "Baseline" },
5029 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
5030 { FF_PROFILE_H264_MAIN, "Main" },
5031 { FF_PROFILE_H264_EXTENDED, "Extended" },
5032 { FF_PROFILE_H264_HIGH, "High" },
5033 { FF_PROFILE_H264_HIGH_10, "High 10" },
5034 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
5035 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
5036 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
5037 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
5038 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
5039 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
5040 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
5041 { FF_PROFILE_UNKNOWN },
5044 AVCodec ff_h264_decoder = {
5046 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5047 .type = AVMEDIA_TYPE_VIDEO,
5048 .id = AV_CODEC_ID_H264,
5049 .priv_data_size = sizeof(H264Context),
5050 .init = ff_h264_decode_init,
5051 .close = h264_decode_end,
5052 .decode = h264_decode_frame,
5053 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5054 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
5055 CODEC_CAP_FRAME_THREADS,
5057 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
5058 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5059 .profiles = NULL_IF_CONFIG_SMALL(profiles),