2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/avassert.h"
29 #include "libavutil/imgutils.h"
32 #include "cabac_functions.h"
34 #include "error_resilience.h"
36 #include "mpegvideo.h"
39 #include "h264chroma.h"
40 #include "h264_mvpred.h"
43 #include "rectangle.h"
49 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
51 static const uint8_t rem6[QP_MAX_NUM + 1] = {
52 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
53 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
54 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3,
57 static const uint8_t div6[QP_MAX_NUM + 1] = {
58 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
59 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
60 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10,
63 static const uint8_t field_scan[16] = {
64 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
65 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
66 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
67 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
70 static const uint8_t field_scan8x8[64] = {
71 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
72 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
73 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
74 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
75 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
76 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
77 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
78 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
79 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
80 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
81 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
82 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
83 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
84 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
85 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
86 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
89 static const uint8_t field_scan8x8_cavlc[64] = {
90 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
91 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
92 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
93 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
94 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
95 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
96 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
97 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
98 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
99 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
100 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
101 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
102 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
103 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
104 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
105 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
108 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
109 static const uint8_t zigzag_scan8x8_cavlc[64] = {
110 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
111 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
112 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
113 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
114 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
115 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
116 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
117 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
118 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
119 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
120 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
121 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
122 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
123 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
124 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
125 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
128 static const uint8_t dequant4_coeff_init[6][3] = {
137 static const uint8_t dequant8_coeff_init_scan[16] = {
138 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
141 static const uint8_t dequant8_coeff_init[6][6] = {
142 { 20, 18, 32, 19, 25, 24 },
143 { 22, 19, 35, 21, 28, 26 },
144 { 26, 23, 42, 24, 33, 31 },
145 { 28, 25, 45, 26, 35, 33 },
146 { 32, 28, 51, 30, 40, 38 },
147 { 36, 32, 58, 34, 46, 43 },
150 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
151 #if CONFIG_H264_DXVA2_HWACCEL
152 AV_PIX_FMT_DXVA2_VLD,
154 #if CONFIG_H264_VAAPI_HWACCEL
155 AV_PIX_FMT_VAAPI_VLD,
157 #if CONFIG_H264_VDA_HWACCEL
160 #if CONFIG_H264_VDPAU_HWACCEL
167 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
168 #if CONFIG_H264_DXVA2_HWACCEL
169 AV_PIX_FMT_DXVA2_VLD,
171 #if CONFIG_H264_VAAPI_HWACCEL
172 AV_PIX_FMT_VAAPI_VLD,
174 #if CONFIG_H264_VDA_HWACCEL
177 #if CONFIG_H264_VDPAU_HWACCEL
184 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
186 int mb_x, int mb_y, int mb_intra, int mb_skipped)
188 H264Context *h = opaque;
192 h->mb_xy = mb_x + mb_y * h->mb_stride;
193 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
195 /* FIXME: It is possible albeit uncommon that slice references
196 * differ between slices. We take the easy approach and ignore
197 * it for now. If this turns out to have any relevance in
198 * practice then correct remapping should be added. */
199 if (ref >= h->ref_count[0])
201 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
203 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
204 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
205 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
206 assert(!FRAME_MBAFF(h));
207 ff_h264_hl_decode_mb(h);
210 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
212 AVCodecContext *avctx = h->avctx;
213 Picture *cur = &h->cur_pic;
214 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
215 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
216 int vshift = desc->log2_chroma_h;
217 const int field_pic = h->picture_structure != PICT_FRAME;
223 height = FFMIN(height, avctx->height - y);
225 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
228 if (avctx->draw_horiz_band) {
230 int offset[AV_NUM_DATA_POINTERS];
233 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
234 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
241 offset[0] = y * src->linesize[0];
243 offset[2] = (y >> vshift) * src->linesize[1];
244 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
249 avctx->draw_horiz_band(avctx, src, offset,
250 y, h->picture_structure, height);
254 static void unref_picture(H264Context *h, Picture *pic)
256 int off = offsetof(Picture, tf) + sizeof(pic->tf);
262 ff_thread_release_buffer(h->avctx, &pic->tf);
263 av_buffer_unref(&pic->hwaccel_priv_buf);
265 av_buffer_unref(&pic->qscale_table_buf);
266 av_buffer_unref(&pic->mb_type_buf);
267 for (i = 0; i < 2; i++) {
268 av_buffer_unref(&pic->motion_val_buf[i]);
269 av_buffer_unref(&pic->ref_index_buf[i]);
272 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
275 static void release_unused_pictures(H264Context *h, int remove_current)
279 /* release non reference frames */
280 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
281 if (h->DPB[i].f.data[0] && !h->DPB[i].reference &&
282 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
283 unref_picture(h, &h->DPB[i]);
288 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
292 av_assert0(!dst->f.buf[0]);
293 av_assert0(src->f.buf[0]);
297 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
301 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
302 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
303 if (!dst->qscale_table_buf || !dst->mb_type_buf)
305 dst->qscale_table = src->qscale_table;
306 dst->mb_type = src->mb_type;
308 for (i = 0; i < 2; i++) {
309 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
310 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
311 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
313 dst->motion_val[i] = src->motion_val[i];
314 dst->ref_index[i] = src->ref_index[i];
317 if (src->hwaccel_picture_private) {
318 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
319 if (!dst->hwaccel_priv_buf)
321 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
324 for (i = 0; i < 2; i++)
325 dst->field_poc[i] = src->field_poc[i];
327 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
328 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
331 dst->frame_num = src->frame_num;
332 dst->mmco_reset = src->mmco_reset;
333 dst->pic_id = src->pic_id;
334 dst->long_ref = src->long_ref;
335 dst->mbaff = src->mbaff;
336 dst->field_picture = src->field_picture;
337 dst->needs_realloc = src->needs_realloc;
338 dst->reference = src->reference;
339 dst->recovered = src->recovered;
343 unref_picture(h, dst);
347 static int alloc_scratch_buffers(H264Context *h, int linesize)
349 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
351 if (h->bipred_scratchpad)
354 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
355 // edge emu needs blocksize + filter length - 1
356 // (= 21x21 for h264)
357 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
358 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
360 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
361 av_freep(&h->bipred_scratchpad);
362 av_freep(&h->edge_emu_buffer);
363 av_freep(&h->me.scratchpad);
364 return AVERROR(ENOMEM);
367 h->me.temp = h->me.scratchpad;
372 static int init_table_pools(H264Context *h)
374 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
375 const int mb_array_size = h->mb_stride * h->mb_height;
376 const int b4_stride = h->mb_width * 4 + 1;
377 const int b4_array_size = b4_stride * h->mb_height * 4;
379 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
381 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
382 sizeof(uint32_t), av_buffer_allocz);
383 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
384 sizeof(int16_t), av_buffer_allocz);
385 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
387 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
388 !h->ref_index_pool) {
389 av_buffer_pool_uninit(&h->qscale_table_pool);
390 av_buffer_pool_uninit(&h->mb_type_pool);
391 av_buffer_pool_uninit(&h->motion_val_pool);
392 av_buffer_pool_uninit(&h->ref_index_pool);
393 return AVERROR(ENOMEM);
399 static int alloc_picture(H264Context *h, Picture *pic)
403 av_assert0(!pic->f.data[0]);
406 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
407 AV_GET_BUFFER_FLAG_REF : 0);
411 h->linesize = pic->f.linesize[0];
412 h->uvlinesize = pic->f.linesize[1];
414 if (h->avctx->hwaccel) {
415 const AVHWAccel *hwaccel = h->avctx->hwaccel;
416 av_assert0(!pic->hwaccel_picture_private);
417 if (hwaccel->priv_data_size) {
418 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
419 if (!pic->hwaccel_priv_buf)
420 return AVERROR(ENOMEM);
421 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
425 if (!h->qscale_table_pool) {
426 ret = init_table_pools(h);
431 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
432 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
433 if (!pic->qscale_table_buf || !pic->mb_type_buf)
436 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
437 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
439 for (i = 0; i < 2; i++) {
440 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
441 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
442 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
445 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
446 pic->ref_index[i] = pic->ref_index_buf[i]->data;
451 unref_picture(h, pic);
452 return (ret < 0) ? ret : AVERROR(ENOMEM);
455 static inline int pic_is_unused(H264Context *h, Picture *pic)
457 if (pic->f.data[0] == NULL)
459 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
464 static int find_unused_picture(H264Context *h)
468 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
469 if (pic_is_unused(h, &h->DPB[i]))
472 if (i == MAX_PICTURE_COUNT)
473 return AVERROR_INVALIDDATA;
475 if (h->DPB[i].needs_realloc) {
476 h->DPB[i].needs_realloc = 0;
477 unref_picture(h, &h->DPB[i]);
484 * Check if the top & left blocks are available if needed and
485 * change the dc mode so it only uses the available blocks.
487 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
489 static const int8_t top[12] = {
490 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
492 static const int8_t left[12] = {
493 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
497 if (!(h->top_samples_available & 0x8000)) {
498 for (i = 0; i < 4; i++) {
499 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
501 av_log(h->avctx, AV_LOG_ERROR,
502 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
503 status, h->mb_x, h->mb_y);
504 return AVERROR_INVALIDDATA;
506 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
511 if ((h->left_samples_available & 0x8888) != 0x8888) {
512 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
513 for (i = 0; i < 4; i++)
514 if (!(h->left_samples_available & mask[i])) {
515 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
517 av_log(h->avctx, AV_LOG_ERROR,
518 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
519 status, h->mb_x, h->mb_y);
520 return AVERROR_INVALIDDATA;
522 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
528 } // FIXME cleanup like ff_h264_check_intra_pred_mode
531 * Check if the top & left blocks are available if needed and
532 * change the dc mode so it only uses the available blocks.
534 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
536 static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
537 static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
540 av_log(h->avctx, AV_LOG_ERROR,
541 "out of range intra chroma pred mode at %d %d\n",
543 return AVERROR_INVALIDDATA;
546 if (!(h->top_samples_available & 0x8000)) {
549 av_log(h->avctx, AV_LOG_ERROR,
550 "top block unavailable for requested intra mode at %d %d\n",
552 return AVERROR_INVALIDDATA;
556 if ((h->left_samples_available & 0x8080) != 0x8080) {
558 if (is_chroma && (h->left_samples_available & 0x8080)) {
559 // mad cow disease mode, aka MBAFF + constrained_intra_pred
560 mode = ALZHEIMER_DC_L0T_PRED8x8 +
561 (!(h->left_samples_available & 0x8000)) +
562 2 * (mode == DC_128_PRED8x8);
565 av_log(h->avctx, AV_LOG_ERROR,
566 "left block unavailable for requested intra mode at %d %d\n",
568 return AVERROR_INVALIDDATA;
575 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
576 int *dst_length, int *consumed, int length)
582 // src[0]&0x80; // forbidden bit
583 h->nal_ref_idc = src[0] >> 5;
584 h->nal_unit_type = src[0] & 0x1F;
589 #define STARTCODE_TEST \
590 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
591 if (src[i + 2] != 3) { \
592 /* startcode, so we must be past the end */ \
598 #if HAVE_FAST_UNALIGNED
599 #define FIND_FIRST_ZERO \
600 if (i > 0 && !src[i]) \
606 for (i = 0; i + 1 < length; i += 9) {
607 if (!((~AV_RN64A(src + i) &
608 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
609 0x8000800080008080ULL))
616 for (i = 0; i + 1 < length; i += 5) {
617 if (!((~AV_RN32A(src + i) &
618 (AV_RN32A(src + i) - 0x01000101U)) &
627 for (i = 0; i + 1 < length; i += 2) {
630 if (i > 0 && src[i - 1] == 0)
636 if (i >= length - 1) { // no escaped 0
637 *dst_length = length;
638 *consumed = length + 1; // +1 for the header
642 // use second escape buffer for inter data
643 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
644 av_fast_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx],
645 length + FF_INPUT_BUFFER_PADDING_SIZE);
646 dst = h->rbsp_buffer[bufidx];
653 while (si + 2 < length) {
654 // remove escapes (very rare 1:2^22)
655 if (src[si + 2] > 3) {
656 dst[di++] = src[si++];
657 dst[di++] = src[si++];
658 } else if (src[si] == 0 && src[si + 1] == 0) {
659 if (src[si + 2] == 3) { // escape
664 } else // next start code
668 dst[di++] = src[si++];
671 dst[di++] = src[si++];
674 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
677 *consumed = si + 1; // +1 for the header
678 /* FIXME store exact number of bits in the getbitcontext
679 * (it is needed for decoding) */
684 * Identify the exact end of the bitstream
685 * @return the length of the trailing, or 0 if damaged
687 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
692 tprintf(h->avctx, "rbsp trailing %X\n", v);
694 for (r = 1; r < 9; r++) {
702 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
703 int height, int y_offset, int list)
705 int raw_my = h->mv_cache[list][scan8[n]][1];
706 int filter_height_up = (raw_my & 3) ? 2 : 0;
707 int filter_height_down = (raw_my & 3) ? 3 : 0;
708 int full_my = (raw_my >> 2) + y_offset;
709 int top = full_my - filter_height_up;
710 int bottom = full_my + filter_height_down + height;
712 return FFMAX(abs(top), bottom);
715 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
716 int height, int y_offset, int list0,
717 int list1, int *nrefs)
721 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
724 int ref_n = h->ref_cache[0][scan8[n]];
725 Picture *ref = &h->ref_list[0][ref_n];
727 // Error resilience puts the current picture in the ref list.
728 // Don't try to wait on these as it will cause a deadlock.
729 // Fields can wait on each other, though.
730 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
731 (ref->reference & 3) != h->picture_structure) {
732 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
733 if (refs[0][ref_n] < 0)
735 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
740 int ref_n = h->ref_cache[1][scan8[n]];
741 Picture *ref = &h->ref_list[1][ref_n];
743 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
744 (ref->reference & 3) != h->picture_structure) {
745 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
746 if (refs[1][ref_n] < 0)
748 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
754 * Wait until all reference frames are available for MC operations.
756 * @param h the H264 context
758 static void await_references(H264Context *h)
760 const int mb_xy = h->mb_xy;
761 const int mb_type = h->cur_pic.mb_type[mb_xy];
763 int nrefs[2] = { 0 };
766 memset(refs, -1, sizeof(refs));
768 if (IS_16X16(mb_type)) {
769 get_lowest_part_y(h, refs, 0, 16, 0,
770 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
771 } else if (IS_16X8(mb_type)) {
772 get_lowest_part_y(h, refs, 0, 8, 0,
773 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
774 get_lowest_part_y(h, refs, 8, 8, 8,
775 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
776 } else if (IS_8X16(mb_type)) {
777 get_lowest_part_y(h, refs, 0, 16, 0,
778 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
779 get_lowest_part_y(h, refs, 4, 16, 0,
780 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
784 assert(IS_8X8(mb_type));
786 for (i = 0; i < 4; i++) {
787 const int sub_mb_type = h->sub_mb_type[i];
789 int y_offset = (i & 2) << 2;
791 if (IS_SUB_8X8(sub_mb_type)) {
792 get_lowest_part_y(h, refs, n, 8, y_offset,
793 IS_DIR(sub_mb_type, 0, 0),
794 IS_DIR(sub_mb_type, 0, 1),
796 } else if (IS_SUB_8X4(sub_mb_type)) {
797 get_lowest_part_y(h, refs, n, 4, y_offset,
798 IS_DIR(sub_mb_type, 0, 0),
799 IS_DIR(sub_mb_type, 0, 1),
801 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
802 IS_DIR(sub_mb_type, 0, 0),
803 IS_DIR(sub_mb_type, 0, 1),
805 } else if (IS_SUB_4X8(sub_mb_type)) {
806 get_lowest_part_y(h, refs, n, 8, y_offset,
807 IS_DIR(sub_mb_type, 0, 0),
808 IS_DIR(sub_mb_type, 0, 1),
810 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
811 IS_DIR(sub_mb_type, 0, 0),
812 IS_DIR(sub_mb_type, 0, 1),
816 assert(IS_SUB_4X4(sub_mb_type));
817 for (j = 0; j < 4; j++) {
818 int sub_y_offset = y_offset + 2 * (j & 2);
819 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
820 IS_DIR(sub_mb_type, 0, 0),
821 IS_DIR(sub_mb_type, 0, 1),
828 for (list = h->list_count - 1; list >= 0; list--)
829 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
830 int row = refs[list][ref];
832 Picture *ref_pic = &h->ref_list[list][ref];
833 int ref_field = ref_pic->reference - 1;
834 int ref_field_picture = ref_pic->field_picture;
835 int pic_height = 16 * h->mb_height >> ref_field_picture;
840 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
841 ff_thread_await_progress(&ref_pic->tf,
842 FFMIN((row >> 1) - !(row & 1),
845 ff_thread_await_progress(&ref_pic->tf,
846 FFMIN((row >> 1), pic_height - 1),
848 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
849 ff_thread_await_progress(&ref_pic->tf,
850 FFMIN(row * 2 + ref_field,
853 } else if (FIELD_PICTURE(h)) {
854 ff_thread_await_progress(&ref_pic->tf,
855 FFMIN(row, pic_height - 1),
858 ff_thread_await_progress(&ref_pic->tf,
859 FFMIN(row, pic_height - 1),
866 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
867 int n, int square, int height,
869 uint8_t *dest_y, uint8_t *dest_cb,
871 int src_x_offset, int src_y_offset,
872 qpel_mc_func *qpix_op,
873 h264_chroma_mc_func chroma_op,
874 int pixel_shift, int chroma_idc)
876 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
877 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
878 const int luma_xy = (mx & 3) + ((my & 3) << 2);
879 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
880 uint8_t *src_y = pic->f.data[0] + offset;
881 uint8_t *src_cb, *src_cr;
883 int extra_height = 0;
885 const int full_mx = mx >> 2;
886 const int full_my = my >> 2;
887 const int pic_width = 16 * h->mb_width;
888 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
896 if (full_mx < 0 - extra_width ||
897 full_my < 0 - extra_height ||
898 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
899 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
900 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
901 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
902 h->mb_linesize, h->mb_linesize,
903 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
904 full_my - 2, pic_width, pic_height);
905 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
909 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
911 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
913 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
916 if (chroma_idc == 3 /* yuv444 */) {
917 src_cb = pic->f.data[1] + offset;
919 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
920 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
921 h->mb_linesize, h->mb_linesize,
922 16 + 5, 16 + 5 /*FIXME*/,
923 full_mx - 2, full_my - 2,
924 pic_width, pic_height);
925 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
927 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
929 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
931 src_cr = pic->f.data[2] + offset;
933 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
934 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
935 h->mb_linesize, h->mb_linesize,
936 16 + 5, 16 + 5 /*FIXME*/,
937 full_mx - 2, full_my - 2,
938 pic_width, pic_height);
939 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
941 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
943 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
947 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
948 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
949 // chroma offset when predicting from a field of opposite parity
950 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
951 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
954 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
955 (my >> ysh) * h->mb_uvlinesize;
956 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
957 (my >> ysh) * h->mb_uvlinesize;
960 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
961 h->mb_uvlinesize, h->mb_uvlinesize,
962 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
963 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
964 src_cb = h->edge_emu_buffer;
966 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
967 height >> (chroma_idc == 1 /* yuv420 */),
968 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
971 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
972 h->mb_uvlinesize, h->mb_uvlinesize,
973 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
974 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
975 src_cr = h->edge_emu_buffer;
977 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
978 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
981 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
982 int height, int delta,
983 uint8_t *dest_y, uint8_t *dest_cb,
985 int x_offset, int y_offset,
986 qpel_mc_func *qpix_put,
987 h264_chroma_mc_func chroma_put,
988 qpel_mc_func *qpix_avg,
989 h264_chroma_mc_func chroma_avg,
990 int list0, int list1,
991 int pixel_shift, int chroma_idc)
993 qpel_mc_func *qpix_op = qpix_put;
994 h264_chroma_mc_func chroma_op = chroma_put;
996 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
997 if (chroma_idc == 3 /* yuv444 */) {
998 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
999 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1000 } else if (chroma_idc == 2 /* yuv422 */) {
1001 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1002 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1003 } else { /* yuv420 */
1004 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1005 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1007 x_offset += 8 * h->mb_x;
1008 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1011 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1012 mc_dir_part(h, ref, n, square, height, delta, 0,
1013 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1014 qpix_op, chroma_op, pixel_shift, chroma_idc);
1017 chroma_op = chroma_avg;
1021 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1022 mc_dir_part(h, ref, n, square, height, delta, 1,
1023 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1024 qpix_op, chroma_op, pixel_shift, chroma_idc);
1028 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1029 int height, int delta,
1030 uint8_t *dest_y, uint8_t *dest_cb,
1032 int x_offset, int y_offset,
1033 qpel_mc_func *qpix_put,
1034 h264_chroma_mc_func chroma_put,
1035 h264_weight_func luma_weight_op,
1036 h264_weight_func chroma_weight_op,
1037 h264_biweight_func luma_weight_avg,
1038 h264_biweight_func chroma_weight_avg,
1039 int list0, int list1,
1040 int pixel_shift, int chroma_idc)
1044 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1045 if (chroma_idc == 3 /* yuv444 */) {
1046 chroma_height = height;
1047 chroma_weight_avg = luma_weight_avg;
1048 chroma_weight_op = luma_weight_op;
1049 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1050 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1051 } else if (chroma_idc == 2 /* yuv422 */) {
1052 chroma_height = height;
1053 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1054 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1055 } else { /* yuv420 */
1056 chroma_height = height >> 1;
1057 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1058 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1060 x_offset += 8 * h->mb_x;
1061 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1063 if (list0 && list1) {
1064 /* don't optimize for luma-only case, since B-frames usually
1065 * use implicit weights => chroma too. */
1066 uint8_t *tmp_cb = h->bipred_scratchpad;
1067 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1068 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1069 int refn0 = h->ref_cache[0][scan8[n]];
1070 int refn1 = h->ref_cache[1][scan8[n]];
1072 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1073 dest_y, dest_cb, dest_cr,
1074 x_offset, y_offset, qpix_put, chroma_put,
1075 pixel_shift, chroma_idc);
1076 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1077 tmp_y, tmp_cb, tmp_cr,
1078 x_offset, y_offset, qpix_put, chroma_put,
1079 pixel_shift, chroma_idc);
1081 if (h->use_weight == 2) {
1082 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1083 int weight1 = 64 - weight0;
1084 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1085 height, 5, weight0, weight1, 0);
1086 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1087 chroma_height, 5, weight0, weight1, 0);
1088 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1089 chroma_height, 5, weight0, weight1, 0);
1091 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1092 h->luma_log2_weight_denom,
1093 h->luma_weight[refn0][0][0],
1094 h->luma_weight[refn1][1][0],
1095 h->luma_weight[refn0][0][1] +
1096 h->luma_weight[refn1][1][1]);
1097 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1098 h->chroma_log2_weight_denom,
1099 h->chroma_weight[refn0][0][0][0],
1100 h->chroma_weight[refn1][1][0][0],
1101 h->chroma_weight[refn0][0][0][1] +
1102 h->chroma_weight[refn1][1][0][1]);
1103 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1104 h->chroma_log2_weight_denom,
1105 h->chroma_weight[refn0][0][1][0],
1106 h->chroma_weight[refn1][1][1][0],
1107 h->chroma_weight[refn0][0][1][1] +
1108 h->chroma_weight[refn1][1][1][1]);
1111 int list = list1 ? 1 : 0;
1112 int refn = h->ref_cache[list][scan8[n]];
1113 Picture *ref = &h->ref_list[list][refn];
1114 mc_dir_part(h, ref, n, square, height, delta, list,
1115 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1116 qpix_put, chroma_put, pixel_shift, chroma_idc);
1118 luma_weight_op(dest_y, h->mb_linesize, height,
1119 h->luma_log2_weight_denom,
1120 h->luma_weight[refn][list][0],
1121 h->luma_weight[refn][list][1]);
1122 if (h->use_weight_chroma) {
1123 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1124 h->chroma_log2_weight_denom,
1125 h->chroma_weight[refn][list][0][0],
1126 h->chroma_weight[refn][list][0][1]);
1127 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1128 h->chroma_log2_weight_denom,
1129 h->chroma_weight[refn][list][1][0],
1130 h->chroma_weight[refn][list][1][1]);
1135 static av_always_inline void prefetch_motion(H264Context *h, int list,
1136 int pixel_shift, int chroma_idc)
1138 /* fetch pixels for estimated mv 4 macroblocks ahead
1139 * optimized for 64byte cache lines */
1140 const int refn = h->ref_cache[list][scan8[0]];
1142 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1143 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1144 uint8_t **src = h->ref_list[list][refn].f.data;
1145 int off = (mx << pixel_shift) +
1146 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1147 (64 << pixel_shift);
1148 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1149 if (chroma_idc == 3 /* yuv444 */) {
1150 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1151 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1153 off = ((mx >> 1) << pixel_shift) +
1154 ((my >> 1) + (h->mb_x & 7)) * h->uvlinesize +
1155 (64 << pixel_shift);
1156 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1161 static void free_tables(H264Context *h, int free_rbsp)
1166 av_freep(&h->intra4x4_pred_mode);
1167 av_freep(&h->chroma_pred_mode_table);
1168 av_freep(&h->cbp_table);
1169 av_freep(&h->mvd_table[0]);
1170 av_freep(&h->mvd_table[1]);
1171 av_freep(&h->direct_table);
1172 av_freep(&h->non_zero_count);
1173 av_freep(&h->slice_table_base);
1174 h->slice_table = NULL;
1175 av_freep(&h->list_counts);
1177 av_freep(&h->mb2b_xy);
1178 av_freep(&h->mb2br_xy);
1180 av_buffer_pool_uninit(&h->qscale_table_pool);
1181 av_buffer_pool_uninit(&h->mb_type_pool);
1182 av_buffer_pool_uninit(&h->motion_val_pool);
1183 av_buffer_pool_uninit(&h->ref_index_pool);
1185 if (free_rbsp && h->DPB) {
1186 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1187 unref_picture(h, &h->DPB[i]);
1189 } else if (h->DPB) {
1190 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1191 h->DPB[i].needs_realloc = 1;
1194 h->cur_pic_ptr = NULL;
1196 for (i = 0; i < MAX_THREADS; i++) {
1197 hx = h->thread_context[i];
1200 av_freep(&hx->top_borders[1]);
1201 av_freep(&hx->top_borders[0]);
1202 av_freep(&hx->bipred_scratchpad);
1203 av_freep(&hx->edge_emu_buffer);
1204 av_freep(&hx->dc_val_base);
1205 av_freep(&hx->me.scratchpad);
1206 av_freep(&hx->er.mb_index2xy);
1207 av_freep(&hx->er.error_status_table);
1208 av_freep(&hx->er.er_temp_buffer);
1209 av_freep(&hx->er.mbintra_table);
1210 av_freep(&hx->er.mbskip_table);
1213 av_freep(&hx->rbsp_buffer[1]);
1214 av_freep(&hx->rbsp_buffer[0]);
1215 hx->rbsp_buffer_size[0] = 0;
1216 hx->rbsp_buffer_size[1] = 0;
1219 av_freep(&h->thread_context[i]);
1223 static void init_dequant8_coeff_table(H264Context *h)
1226 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1228 for (i = 0; i < 6; i++) {
1229 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1230 for (j = 0; j < i; j++)
1231 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1232 64 * sizeof(uint8_t))) {
1233 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1239 for (q = 0; q < max_qp + 1; q++) {
1240 int shift = div6[q];
1242 for (x = 0; x < 64; x++)
1243 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1244 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1245 h->pps.scaling_matrix8[i][x]) << shift;
1250 static void init_dequant4_coeff_table(H264Context *h)
1253 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1254 for (i = 0; i < 6; i++) {
1255 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1256 for (j = 0; j < i; j++)
1257 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1258 16 * sizeof(uint8_t))) {
1259 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1265 for (q = 0; q < max_qp + 1; q++) {
1266 int shift = div6[q] + 2;
1268 for (x = 0; x < 16; x++)
1269 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1270 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1271 h->pps.scaling_matrix4[i][x]) << shift;
1276 static void init_dequant_tables(H264Context *h)
1279 init_dequant4_coeff_table(h);
1280 if (h->pps.transform_8x8_mode)
1281 init_dequant8_coeff_table(h);
1282 if (h->sps.transform_bypass) {
1283 for (i = 0; i < 6; i++)
1284 for (x = 0; x < 16; x++)
1285 h->dequant4_coeff[i][0][x] = 1 << 6;
1286 if (h->pps.transform_8x8_mode)
1287 for (i = 0; i < 6; i++)
1288 for (x = 0; x < 64; x++)
1289 h->dequant8_coeff[i][0][x] = 1 << 6;
1293 int ff_h264_alloc_tables(H264Context *h)
1295 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1296 const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
1299 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1300 row_mb_num * 8 * sizeof(uint8_t), fail)
1301 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1302 big_mb_num * 48 * sizeof(uint8_t), fail)
1303 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1304 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1305 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1306 big_mb_num * sizeof(uint16_t), fail)
1307 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1308 big_mb_num * sizeof(uint8_t), fail)
1309 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1310 16 * row_mb_num * sizeof(uint8_t), fail);
1311 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1312 16 * row_mb_num * sizeof(uint8_t), fail);
1313 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1314 4 * big_mb_num * sizeof(uint8_t), fail);
1315 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1316 big_mb_num * sizeof(uint8_t), fail)
1318 memset(h->slice_table_base, -1,
1319 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1320 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1322 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1323 big_mb_num * sizeof(uint32_t), fail);
1324 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1325 big_mb_num * sizeof(uint32_t), fail);
1326 for (y = 0; y < h->mb_height; y++)
1327 for (x = 0; x < h->mb_width; x++) {
1328 const int mb_xy = x + y * h->mb_stride;
1329 const int b_xy = 4 * x + 4 * y * h->b_stride;
1331 h->mb2b_xy[mb_xy] = b_xy;
1332 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1335 if (!h->dequant4_coeff[0])
1336 init_dequant_tables(h);
1339 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1341 return AVERROR(ENOMEM);
1342 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1343 avcodec_get_frame_defaults(&h->DPB[i].f);
1344 avcodec_get_frame_defaults(&h->cur_pic.f);
1351 return AVERROR(ENOMEM);
1355 * Mimic alloc_tables(), but for every context thread.
1357 static void clone_tables(H264Context *dst, H264Context *src, int i)
1359 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1360 dst->non_zero_count = src->non_zero_count;
1361 dst->slice_table = src->slice_table;
1362 dst->cbp_table = src->cbp_table;
1363 dst->mb2b_xy = src->mb2b_xy;
1364 dst->mb2br_xy = src->mb2br_xy;
1365 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1366 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1367 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1368 dst->direct_table = src->direct_table;
1369 dst->list_counts = src->list_counts;
1370 dst->DPB = src->DPB;
1371 dst->cur_pic_ptr = src->cur_pic_ptr;
1372 dst->cur_pic = src->cur_pic;
1373 dst->bipred_scratchpad = NULL;
1374 dst->edge_emu_buffer = NULL;
1375 dst->me.scratchpad = NULL;
1376 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1377 src->sps.chroma_format_idc);
1382 * Allocate buffers which are not shared amongst multiple threads.
1384 static int context_init(H264Context *h)
1386 ERContext *er = &h->er;
1387 int mb_array_size = h->mb_height * h->mb_stride;
1388 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1389 int c_size = h->mb_stride * (h->mb_height + 1);
1390 int yc_size = y_size + 2 * c_size;
1393 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1394 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1395 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1396 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1398 h->ref_cache[0][scan8[5] + 1] =
1399 h->ref_cache[0][scan8[7] + 1] =
1400 h->ref_cache[0][scan8[13] + 1] =
1401 h->ref_cache[1][scan8[5] + 1] =
1402 h->ref_cache[1][scan8[7] + 1] =
1403 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1405 if (CONFIG_ERROR_RESILIENCE) {
1407 er->avctx = h->avctx;
1409 er->decode_mb = h264_er_decode_mb;
1411 er->quarter_sample = 1;
1413 er->mb_num = h->mb_num;
1414 er->mb_width = h->mb_width;
1415 er->mb_height = h->mb_height;
1416 er->mb_stride = h->mb_stride;
1417 er->b8_stride = h->mb_width * 2 + 1;
1419 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1420 fail); // error ressilience code looks cleaner with this
1421 for (y = 0; y < h->mb_height; y++)
1422 for (x = 0; x < h->mb_width; x++)
1423 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1425 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1426 h->mb_stride + h->mb_width;
1428 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1429 mb_array_size * sizeof(uint8_t), fail);
1431 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1432 memset(er->mbintra_table, 1, mb_array_size);
1434 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1436 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1439 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1440 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1441 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1442 er->dc_val[2] = er->dc_val[1] + c_size;
1443 for (i = 0; i < yc_size; i++)
1444 h->dc_val_base[i] = 1024;
1450 return AVERROR(ENOMEM); // free_tables will clean up for us
1453 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1454 int parse_extradata);
1456 int ff_h264_decode_extradata(H264Context *h)
1458 AVCodecContext *avctx = h->avctx;
1461 if (avctx->extradata[0] == 1) {
1462 int i, cnt, nalsize;
1463 unsigned char *p = avctx->extradata;
1467 if (avctx->extradata_size < 7) {
1468 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1469 return AVERROR_INVALIDDATA;
1471 /* sps and pps in the avcC always have length coded with 2 bytes,
1472 * so put a fake nal_length_size = 2 while parsing them */
1473 h->nal_length_size = 2;
1474 // Decode sps from avcC
1475 cnt = *(p + 5) & 0x1f; // Number of sps
1477 for (i = 0; i < cnt; i++) {
1478 nalsize = AV_RB16(p) + 2;
1479 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1480 return AVERROR_INVALIDDATA;
1481 ret = decode_nal_units(h, p, nalsize, 1);
1483 av_log(avctx, AV_LOG_ERROR,
1484 "Decoding sps %d from avcC failed\n", i);
1489 // Decode pps from avcC
1490 cnt = *(p++); // Number of pps
1491 for (i = 0; i < cnt; i++) {
1492 nalsize = AV_RB16(p) + 2;
1493 if (p - avctx->extradata + nalsize > avctx->extradata_size)
1494 return AVERROR_INVALIDDATA;
1495 ret = decode_nal_units(h, p, nalsize, 1);
1497 av_log(avctx, AV_LOG_ERROR,
1498 "Decoding pps %d from avcC failed\n", i);
1503 // Now store right nal length size, that will be used to parse all other nals
1504 h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
1507 ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
1514 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1516 H264Context *h = avctx->priv_data;
1522 h->bit_depth_luma = 8;
1523 h->chroma_format_idc = 1;
1525 ff_h264dsp_init(&h->h264dsp, 8, 1);
1526 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1527 ff_h264qpel_init(&h->h264qpel, 8);
1528 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1530 h->dequant_coeff_pps = -1;
1532 /* needed so that IDCT permutation is known early */
1533 if (CONFIG_ERROR_RESILIENCE)
1534 ff_dsputil_init(&h->dsp, h->avctx);
1535 ff_videodsp_init(&h->vdsp, 8);
1537 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1538 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1540 h->picture_structure = PICT_FRAME;
1541 h->slice_context_count = 1;
1542 h->workaround_bugs = avctx->workaround_bugs;
1543 h->flags = avctx->flags;
1546 // s->decode_mb = ff_h263_decode_mb;
1547 if (!avctx->has_b_frames)
1550 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1552 ff_h264_decode_init_vlc();
1554 ff_init_cabac_states();
1557 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1559 h->thread_context[0] = h;
1560 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1561 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1562 h->last_pocs[i] = INT_MIN;
1563 h->prev_poc_msb = 1 << 16;
1565 ff_h264_reset_sei(h);
1566 h->recovery_frame = -1;
1567 h->frame_recovered = 0;
1568 if (avctx->codec_id == AV_CODEC_ID_H264) {
1569 if (avctx->ticks_per_frame == 1)
1570 h->avctx->time_base.den *= 2;
1571 avctx->ticks_per_frame = 2;
1574 if (avctx->extradata_size > 0 && avctx->extradata) {
1575 ret = ff_h264_decode_extradata(h);
1580 if (h->sps.bitstream_restriction_flag &&
1581 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1582 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1586 avctx->internal->allocate_progress = 1;
1591 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1592 #undef REBASE_PICTURE
1593 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1594 ((pic && pic >= old_ctx->DPB && \
1595 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1596 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1598 static void copy_picture_range(Picture **to, Picture **from, int count,
1599 H264Context *new_base,
1600 H264Context *old_base)
1604 for (i = 0; i < count; i++) {
1605 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1606 IN_RANGE(from[i], old_base->DPB,
1607 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1609 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1613 static int copy_parameter_set(void **to, void **from, int count, int size)
1617 for (i = 0; i < count; i++) {
1618 if (to[i] && !from[i]) {
1620 } else if (from[i] && !to[i]) {
1621 to[i] = av_malloc(size);
1623 return AVERROR(ENOMEM);
1627 memcpy(to[i], from[i], size);
1633 static int decode_init_thread_copy(AVCodecContext *avctx)
1635 H264Context *h = avctx->priv_data;
1637 if (!avctx->internal->is_copy)
1639 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1640 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1642 h->context_initialized = 0;
1647 #define copy_fields(to, from, start_field, end_field) \
1648 memcpy(&to->start_field, &from->start_field, \
1649 (char *)&to->end_field - (char *)&to->start_field)
1651 static int h264_slice_header_init(H264Context *, int);
1653 static int h264_set_parameter_from_sps(H264Context *h);
1655 static int decode_update_thread_context(AVCodecContext *dst,
1656 const AVCodecContext *src)
1658 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1659 int inited = h->context_initialized, err = 0;
1660 int context_reinitialized = 0;
1663 if (dst == src || !h1->context_initialized)
1667 (h->width != h1->width ||
1668 h->height != h1->height ||
1669 h->mb_width != h1->mb_width ||
1670 h->mb_height != h1->mb_height ||
1671 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1672 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1673 h->sps.colorspace != h1->sps.colorspace)) {
1675 /* set bits_per_raw_sample to the previous value. the check for changed
1676 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1677 * the current value */
1678 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1680 av_freep(&h->bipred_scratchpad);
1682 h->width = h1->width;
1683 h->height = h1->height;
1684 h->mb_height = h1->mb_height;
1685 h->mb_width = h1->mb_width;
1686 h->mb_num = h1->mb_num;
1687 h->mb_stride = h1->mb_stride;
1688 h->b_stride = h1->b_stride;
1690 if ((err = h264_slice_header_init(h, 1)) < 0) {
1691 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1694 context_reinitialized = 1;
1696 /* update linesize on resize. The decoder doesn't
1697 * necessarily call h264_frame_start in the new thread */
1698 h->linesize = h1->linesize;
1699 h->uvlinesize = h1->uvlinesize;
1701 /* copy block_offset since frame_start may not be called */
1702 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1706 for (i = 0; i < MAX_SPS_COUNT; i++)
1707 av_freep(h->sps_buffers + i);
1709 for (i = 0; i < MAX_PPS_COUNT; i++)
1710 av_freep(h->pps_buffers + i);
1712 memcpy(h, h1, sizeof(*h1));
1713 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1714 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1715 memset(&h->er, 0, sizeof(h->er));
1716 memset(&h->me, 0, sizeof(h->me));
1717 memset(&h->mb, 0, sizeof(h->mb));
1718 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1719 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1720 h->context_initialized = 0;
1722 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1723 avcodec_get_frame_defaults(&h->cur_pic.f);
1724 h->cur_pic.tf.f = &h->cur_pic.f;
1728 h->qscale_table_pool = NULL;
1729 h->mb_type_pool = NULL;
1730 h->ref_index_pool = NULL;
1731 h->motion_val_pool = NULL;
1733 ret = ff_h264_alloc_tables(h);
1735 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1738 ret = context_init(h);
1740 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1744 for (i = 0; i < 2; i++) {
1745 h->rbsp_buffer[i] = NULL;
1746 h->rbsp_buffer_size[i] = 0;
1748 h->bipred_scratchpad = NULL;
1749 h->edge_emu_buffer = NULL;
1751 h->thread_context[0] = h;
1753 h->context_initialized = 1;
1756 h->avctx->coded_height = h1->avctx->coded_height;
1757 h->avctx->coded_width = h1->avctx->coded_width;
1758 h->avctx->width = h1->avctx->width;
1759 h->avctx->height = h1->avctx->height;
1760 h->coded_picture_number = h1->coded_picture_number;
1761 h->first_field = h1->first_field;
1762 h->picture_structure = h1->picture_structure;
1763 h->qscale = h1->qscale;
1764 h->droppable = h1->droppable;
1765 h->data_partitioning = h1->data_partitioning;
1766 h->low_delay = h1->low_delay;
1768 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
1769 unref_picture(h, &h->DPB[i]);
1770 if (h1->DPB[i].f.data[0] &&
1771 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1775 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1776 unref_picture(h, &h->cur_pic);
1777 if ((ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1780 h->workaround_bugs = h1->workaround_bugs;
1781 h->low_delay = h1->low_delay;
1782 h->droppable = h1->droppable;
1784 /* frame_start may not be called for the next thread (if it's decoding
1785 * a bottom field) so this has to be allocated here */
1786 err = alloc_scratch_buffers(h, h1->linesize);
1790 // extradata/NAL handling
1791 h->is_avc = h1->is_avc;
1794 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1795 (void **)h1->sps_buffers,
1796 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1799 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1800 (void **)h1->pps_buffers,
1801 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1805 // Dequantization matrices
1806 // FIXME these are big - can they be only copied when PPS changes?
1807 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1809 for (i = 0; i < 6; i++)
1810 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1811 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1813 for (i = 0; i < 6; i++)
1814 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1815 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1817 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1820 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1823 copy_fields(h, h1, short_ref, cabac_init_idc);
1825 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1826 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1827 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1828 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1830 h->last_slice_type = h1->last_slice_type;
1832 if (context_reinitialized)
1833 h264_set_parameter_from_sps(h);
1835 if (!h->cur_pic_ptr)
1838 if (!h->droppable) {
1839 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1840 h->prev_poc_msb = h->poc_msb;
1841 h->prev_poc_lsb = h->poc_lsb;
1843 h->prev_frame_num_offset = h->frame_num_offset;
1844 h->prev_frame_num = h->frame_num;
1845 h->outputed_poc = h->next_outputed_poc;
1847 h->recovery_frame = h1->recovery_frame;
1848 h->frame_recovered = h1->frame_recovered;
1853 static int h264_frame_start(H264Context *h)
1857 const int pixel_shift = h->pixel_shift;
1859 release_unused_pictures(h, 1);
1860 h->cur_pic_ptr = NULL;
1862 i = find_unused_picture(h);
1864 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1869 pic->reference = h->droppable ? 0 : h->picture_structure;
1870 pic->f.coded_picture_number = h->coded_picture_number++;
1871 pic->field_picture = h->picture_structure != PICT_FRAME;
1873 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1875 * See decode_nal_units().
1877 pic->f.key_frame = 0;
1878 pic->mmco_reset = 0;
1881 if ((ret = alloc_picture(h, pic)) < 0)
1884 h->cur_pic_ptr = pic;
1885 unref_picture(h, &h->cur_pic);
1886 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1889 if (CONFIG_ERROR_RESILIENCE)
1890 ff_er_frame_start(&h->er);
1892 assert(h->linesize && h->uvlinesize);
1894 for (i = 0; i < 16; i++) {
1895 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1896 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1898 for (i = 0; i < 16; i++) {
1899 h->block_offset[16 + i] =
1900 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1901 h->block_offset[48 + 16 + i] =
1902 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1905 /* can't be in alloc_tables because linesize isn't known there.
1906 * FIXME: redo bipred weight to not require extra buffer? */
1907 for (i = 0; i < h->slice_context_count; i++)
1908 if (h->thread_context[i]) {
1909 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
1914 /* Some macroblocks can be accessed before they're available in case
1915 * of lost slices, MBAFF or threading. */
1916 memset(h->slice_table, -1,
1917 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1919 // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1920 // s->current_picture.f.reference /* || h->contains_intra */ || 1;
1922 /* We mark the current picture as non-reference after allocating it, so
1923 * that if we break out due to an error it can be released automatically
1924 * in the next ff_MPV_frame_start().
1926 h->cur_pic_ptr->reference = 0;
1928 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
1930 h->next_output_pic = NULL;
1932 assert(h->cur_pic_ptr->long_ref == 0);
1938 * Run setup operations that must be run after slice header decoding.
1939 * This includes finding the next displayed frame.
1941 * @param h h264 master context
1942 * @param setup_finished enough NALs have been read that we can call
1943 * ff_thread_finish_setup()
1945 static void decode_postinit(H264Context *h, int setup_finished)
1947 Picture *out = h->cur_pic_ptr;
1948 Picture *cur = h->cur_pic_ptr;
1949 int i, pics, out_of_order, out_idx;
1950 int invalid = 0, cnt = 0;
1952 h->cur_pic_ptr->f.pict_type = h->pict_type;
1954 if (h->next_output_pic)
1957 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
1958 /* FIXME: if we have two PAFF fields in one packet, we can't start
1959 * the next thread here. If we have one field per packet, we can.
1960 * The check in decode_nal_units() is not good enough to find this
1961 * yet, so we assume the worst for now. */
1962 // if (setup_finished)
1963 // ff_thread_finish_setup(h->avctx);
1967 cur->f.interlaced_frame = 0;
1968 cur->f.repeat_pict = 0;
1970 /* Signal interlacing information externally. */
1971 /* Prioritize picture timing SEI information over used
1972 * decoding process if it exists. */
1974 if (h->sps.pic_struct_present_flag) {
1975 switch (h->sei_pic_struct) {
1976 case SEI_PIC_STRUCT_FRAME:
1978 case SEI_PIC_STRUCT_TOP_FIELD:
1979 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1980 cur->f.interlaced_frame = 1;
1982 case SEI_PIC_STRUCT_TOP_BOTTOM:
1983 case SEI_PIC_STRUCT_BOTTOM_TOP:
1984 if (FIELD_OR_MBAFF_PICTURE(h))
1985 cur->f.interlaced_frame = 1;
1987 // try to flag soft telecine progressive
1988 cur->f.interlaced_frame = h->prev_interlaced_frame;
1990 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1991 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1992 /* Signal the possibility of telecined film externally
1993 * (pic_struct 5,6). From these hints, let the applications
1994 * decide if they apply deinterlacing. */
1995 cur->f.repeat_pict = 1;
1997 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1998 cur->f.repeat_pict = 2;
2000 case SEI_PIC_STRUCT_FRAME_TRIPLING:
2001 cur->f.repeat_pict = 4;
2005 if ((h->sei_ct_type & 3) &&
2006 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2007 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2009 /* Derive interlacing flag from used decoding process. */
2010 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2012 h->prev_interlaced_frame = cur->f.interlaced_frame;
2014 if (cur->field_poc[0] != cur->field_poc[1]) {
2015 /* Derive top_field_first from field pocs. */
2016 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2018 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2019 /* Use picture timing SEI information. Even if it is a
2020 * information of a past frame, better than nothing. */
2021 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2022 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2023 cur->f.top_field_first = 1;
2025 cur->f.top_field_first = 0;
2027 /* Most likely progressive */
2028 cur->f.top_field_first = 0;
2032 // FIXME do something with unavailable reference frames
2034 /* Sort B-frames into display order */
2036 if (h->sps.bitstream_restriction_flag &&
2037 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2038 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2042 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2043 !h->sps.bitstream_restriction_flag) {
2044 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2049 while (h->delayed_pic[pics])
2052 assert(pics <= MAX_DELAYED_PIC_COUNT);
2054 h->delayed_pic[pics++] = cur;
2055 if (cur->reference == 0)
2056 cur->reference = DELAYED_PIC_REF;
2058 /* Frame reordering. This code takes pictures from coding order and sorts
2059 * them by their incremental POC value into display order. It supports POC
2060 * gaps, MMCO reset codes and random resets.
2061 * A "display group" can start either with a IDR frame (f.key_frame = 1),
2062 * and/or can be closed down with a MMCO reset code. In sequences where
2063 * there is no delay, we can't detect that (since the frame was already
2064 * output to the user), so we also set h->mmco_reset to detect the MMCO
2066 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
2067 * we increase the delay between input and output. All frames affected by
2068 * the lag (e.g. those that should have been output before another frame
2069 * that we already returned to the user) will be dropped. This is a bug
2070 * that we will fix later. */
2071 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2072 cnt += out->poc < h->last_pocs[i];
2073 invalid += out->poc == INT_MIN;
2075 if (!h->mmco_reset && !cur->f.key_frame &&
2076 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
2079 h->delayed_pic[pics - 2]->mmco_reset = 2;
2081 if (h->mmco_reset || cur->f.key_frame) {
2082 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2083 h->last_pocs[i] = INT_MIN;
2085 invalid = MAX_DELAYED_PIC_COUNT;
2087 out = h->delayed_pic[0];
2089 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
2090 h->delayed_pic[i] &&
2091 !h->delayed_pic[i - 1]->mmco_reset &&
2092 !h->delayed_pic[i]->f.key_frame;
2094 if (h->delayed_pic[i]->poc < out->poc) {
2095 out = h->delayed_pic[i];
2098 if (h->avctx->has_b_frames == 0 &&
2099 (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
2100 h->next_outputed_poc = INT_MIN;
2101 out_of_order = !out->f.key_frame && !h->mmco_reset &&
2102 (out->poc < h->next_outputed_poc);
2104 if (h->sps.bitstream_restriction_flag &&
2105 h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
2106 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
2107 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
2108 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
2109 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
2112 } else if (h->low_delay &&
2113 ((h->next_outputed_poc != INT_MIN &&
2114 out->poc > h->next_outputed_poc + 2) ||
2115 cur->f.pict_type == AV_PICTURE_TYPE_B)) {
2117 h->avctx->has_b_frames++;
2120 if (pics > h->avctx->has_b_frames) {
2121 out->reference &= ~DELAYED_PIC_REF;
2122 // for frame threading, the owner must be the second field's thread or
2123 // else the first thread can release the picture and reuse it unsafely
2124 for (i = out_idx; h->delayed_pic[i]; i++)
2125 h->delayed_pic[i] = h->delayed_pic[i + 1];
2127 memmove(h->last_pocs, &h->last_pocs[1],
2128 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
2129 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
2130 if (!out_of_order && pics > h->avctx->has_b_frames) {
2131 h->next_output_pic = out;
2132 if (out->mmco_reset) {
2134 h->next_outputed_poc = out->poc;
2135 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
2137 h->next_outputed_poc = INT_MIN;
2140 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
2141 h->next_outputed_poc = INT_MIN;
2143 h->next_outputed_poc = out->poc;
2148 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
2151 if (h->next_output_pic) {
2152 if (h->next_output_pic->recovered) {
2153 // We have reached an recovery point and all frames after it in
2154 // display order are "recovered".
2155 h->frame_recovered |= FRAME_RECOVERED_SEI;
2157 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2160 if (setup_finished && !h->avctx->hwaccel)
2161 ff_thread_finish_setup(h->avctx);
2164 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2165 uint8_t *src_cb, uint8_t *src_cr,
2166 int linesize, int uvlinesize,
2169 uint8_t *top_border;
2171 const int pixel_shift = h->pixel_shift;
2172 int chroma444 = CHROMA444(h);
2173 int chroma422 = CHROMA422(h);
2176 src_cb -= uvlinesize;
2177 src_cr -= uvlinesize;
2179 if (!simple && FRAME_MBAFF(h)) {
2182 top_border = h->top_borders[0][h->mb_x];
2183 AV_COPY128(top_border, src_y + 15 * linesize);
2185 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2186 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2189 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2190 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2191 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2192 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2194 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2195 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2197 } else if (chroma422) {
2199 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2200 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2202 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2203 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2207 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2208 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2210 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2211 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2216 } else if (MB_MBAFF(h)) {
2222 top_border = h->top_borders[top_idx][h->mb_x];
2223 /* There are two lines saved, the line above the top macroblock
2224 * of a pair, and the line above the bottom macroblock. */
2225 AV_COPY128(top_border, src_y + 16 * linesize);
2227 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2229 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2232 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2233 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2234 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2235 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2237 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2238 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2240 } else if (chroma422) {
2242 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2243 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2245 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2246 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2250 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2251 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2253 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2254 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2260 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2261 uint8_t *src_cb, uint8_t *src_cr,
2262 int linesize, int uvlinesize,
2263 int xchg, int chroma444,
2264 int simple, int pixel_shift)
2266 int deblock_topleft;
2269 uint8_t *top_border_m1;
2270 uint8_t *top_border;
2272 if (!simple && FRAME_MBAFF(h)) {
2277 top_idx = MB_MBAFF(h) ? 0 : 1;
2281 if (h->deblocking_filter == 2) {
2282 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2283 deblock_top = h->top_type;
2285 deblock_topleft = (h->mb_x > 0);
2286 deblock_top = (h->mb_y > !!MB_FIELD(h));
2289 src_y -= linesize + 1 + pixel_shift;
2290 src_cb -= uvlinesize + 1 + pixel_shift;
2291 src_cr -= uvlinesize + 1 + pixel_shift;
2293 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2294 top_border = h->top_borders[top_idx][h->mb_x];
2296 #define XCHG(a, b, xchg) \
2297 if (pixel_shift) { \
2299 AV_SWAP64(b + 0, a + 0); \
2300 AV_SWAP64(b + 8, a + 8); \
2310 if (deblock_topleft) {
2311 XCHG(top_border_m1 + (8 << pixel_shift),
2312 src_y - (7 << pixel_shift), 1);
2314 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2315 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2316 if (h->mb_x + 1 < h->mb_width) {
2317 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2318 src_y + (17 << pixel_shift), 1);
2321 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2323 if (deblock_topleft) {
2324 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2325 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2327 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2328 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2329 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2330 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2331 if (h->mb_x + 1 < h->mb_width) {
2332 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2333 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2337 if (deblock_topleft) {
2338 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2339 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2341 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2342 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2348 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2351 if (high_bit_depth) {
2352 return AV_RN32A(((int32_t *)mb) + index);
2354 return AV_RN16A(mb + index);
2357 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2358 int index, int value)
2360 if (high_bit_depth) {
2361 AV_WN32A(((int32_t *)mb) + index, value);
2363 AV_WN16A(mb + index, value);
2366 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2367 int mb_type, int is_h264,
2369 int transform_bypass,
2373 uint8_t *dest_y, int p)
2375 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2376 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2378 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2379 block_offset += 16 * p;
2380 if (IS_INTRA4x4(mb_type)) {
2381 if (IS_8x8DCT(mb_type)) {
2382 if (transform_bypass) {
2384 idct_add = h->h264dsp.h264_add_pixels8_clear;
2386 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2387 idct_add = h->h264dsp.h264_idct8_add;
2389 for (i = 0; i < 16; i += 4) {
2390 uint8_t *const ptr = dest_y + block_offset[i];
2391 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2392 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2393 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2395 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2396 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2397 (h->topright_samples_available << i) & 0x4000, linesize);
2399 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2400 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2402 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2407 if (transform_bypass) {
2409 idct_add = h->h264dsp.h264_add_pixels4_clear;
2411 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2412 idct_add = h->h264dsp.h264_idct_add;
2414 for (i = 0; i < 16; i++) {
2415 uint8_t *const ptr = dest_y + block_offset[i];
2416 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2418 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2419 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2424 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2425 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2426 assert(h->mb_y || linesize <= block_offset[i]);
2427 if (!topright_avail) {
2429 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2430 topright = (uint8_t *)&tr_high;
2432 tr = ptr[3 - linesize] * 0x01010101u;
2433 topright = (uint8_t *)&tr;
2436 topright = ptr + (4 << pixel_shift) - linesize;
2440 h->hpc.pred4x4[dir](ptr, topright, linesize);
2441 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2444 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2445 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2447 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2448 } else if (CONFIG_SVQ3_DECODER)
2449 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2455 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2457 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2458 if (!transform_bypass)
2459 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2461 h->dequant4_coeff[p][qscale][0]);
2463 static const uint8_t dc_mapping[16] = {
2464 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2465 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2466 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2467 10 * 16, 11 * 16, 14 * 16, 15 * 16
2469 for (i = 0; i < 16; i++)
2470 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2471 pixel_shift, dc_mapping[i],
2472 dctcoef_get(h->mb_luma_dc[p],
2476 } else if (CONFIG_SVQ3_DECODER)
2477 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2478 h->mb_luma_dc[p], qscale);
2482 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2483 int is_h264, int simple,
2484 int transform_bypass,
2488 uint8_t *dest_y, int p)
2490 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2492 block_offset += 16 * p;
2493 if (!IS_INTRA4x4(mb_type)) {
2495 if (IS_INTRA16x16(mb_type)) {
2496 if (transform_bypass) {
2497 if (h->sps.profile_idc == 244 &&
2498 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2499 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2500 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2501 h->mb + (p * 256 << pixel_shift),
2504 for (i = 0; i < 16; i++)
2505 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2506 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2507 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2508 h->mb + (i * 16 + p * 256 << pixel_shift),
2512 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2513 h->mb + (p * 256 << pixel_shift),
2515 h->non_zero_count_cache + p * 5 * 8);
2517 } else if (h->cbp & 15) {
2518 if (transform_bypass) {
2519 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2520 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2521 : h->h264dsp.h264_add_pixels4_clear;
2522 for (i = 0; i < 16; i += di)
2523 if (h->non_zero_count_cache[scan8[i + p * 16]])
2524 idct_add(dest_y + block_offset[i],
2525 h->mb + (i * 16 + p * 256 << pixel_shift),
2528 if (IS_8x8DCT(mb_type))
2529 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2530 h->mb + (p * 256 << pixel_shift),
2532 h->non_zero_count_cache + p * 5 * 8);
2534 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2535 h->mb + (p * 256 << pixel_shift),
2537 h->non_zero_count_cache + p * 5 * 8);
2540 } else if (CONFIG_SVQ3_DECODER) {
2541 for (i = 0; i < 16; i++)
2542 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2543 // FIXME benchmark weird rule, & below
2544 uint8_t *const ptr = dest_y + block_offset[i];
2545 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2546 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2554 #include "h264_mb_template.c"
2558 #include "h264_mb_template.c"
2562 #include "h264_mb_template.c"
2564 void ff_h264_hl_decode_mb(H264Context *h)
2566 const int mb_xy = h->mb_xy;
2567 const int mb_type = h->cur_pic.mb_type[mb_xy];
2568 int is_complex = CONFIG_SMALL || h->is_complex ||
2569 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2572 if (is_complex || h->pixel_shift)
2573 hl_decode_mb_444_complex(h);
2575 hl_decode_mb_444_simple_8(h);
2576 } else if (is_complex) {
2577 hl_decode_mb_complex(h);
2578 } else if (h->pixel_shift) {
2579 hl_decode_mb_simple_16(h);
2581 hl_decode_mb_simple_8(h);
2584 int ff_pred_weight_table(H264Context *h)
2587 int luma_def, chroma_def;
2590 h->use_weight_chroma = 0;
2591 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2592 if (h->sps.chroma_format_idc)
2593 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2594 luma_def = 1 << h->luma_log2_weight_denom;
2595 chroma_def = 1 << h->chroma_log2_weight_denom;
2597 for (list = 0; list < 2; list++) {
2598 h->luma_weight_flag[list] = 0;
2599 h->chroma_weight_flag[list] = 0;
2600 for (i = 0; i < h->ref_count[list]; i++) {
2601 int luma_weight_flag, chroma_weight_flag;
2603 luma_weight_flag = get_bits1(&h->gb);
2604 if (luma_weight_flag) {
2605 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2606 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2607 if (h->luma_weight[i][list][0] != luma_def ||
2608 h->luma_weight[i][list][1] != 0) {
2610 h->luma_weight_flag[list] = 1;
2613 h->luma_weight[i][list][0] = luma_def;
2614 h->luma_weight[i][list][1] = 0;
2617 if (h->sps.chroma_format_idc) {
2618 chroma_weight_flag = get_bits1(&h->gb);
2619 if (chroma_weight_flag) {
2621 for (j = 0; j < 2; j++) {
2622 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2623 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2624 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2625 h->chroma_weight[i][list][j][1] != 0) {
2626 h->use_weight_chroma = 1;
2627 h->chroma_weight_flag[list] = 1;
2632 for (j = 0; j < 2; j++) {
2633 h->chroma_weight[i][list][j][0] = chroma_def;
2634 h->chroma_weight[i][list][j][1] = 0;
2639 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2642 h->use_weight = h->use_weight || h->use_weight_chroma;
2647 * Initialize implicit_weight table.
2648 * @param field 0/1 initialize the weight for interlaced MBAFF
2649 * -1 initializes the rest
2651 static void implicit_weight_table(H264Context *h, int field)
2653 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2655 for (i = 0; i < 2; i++) {
2656 h->luma_weight_flag[i] = 0;
2657 h->chroma_weight_flag[i] = 0;
2661 if (h->picture_structure == PICT_FRAME) {
2662 cur_poc = h->cur_pic_ptr->poc;
2664 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2666 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2667 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2669 h->use_weight_chroma = 0;
2673 ref_count0 = h->ref_count[0];
2674 ref_count1 = h->ref_count[1];
2676 cur_poc = h->cur_pic_ptr->field_poc[field];
2678 ref_count0 = 16 + 2 * h->ref_count[0];
2679 ref_count1 = 16 + 2 * h->ref_count[1];
2683 h->use_weight_chroma = 2;
2684 h->luma_log2_weight_denom = 5;
2685 h->chroma_log2_weight_denom = 5;
2687 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2688 int poc0 = h->ref_list[0][ref0].poc;
2689 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2691 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2692 int poc1 = h->ref_list[1][ref1].poc;
2693 int td = av_clip(poc1 - poc0, -128, 127);
2695 int tb = av_clip(cur_poc - poc0, -128, 127);
2696 int tx = (16384 + (FFABS(td) >> 1)) / td;
2697 int dist_scale_factor = (tb * tx + 32) >> 8;
2698 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2699 w = 64 - dist_scale_factor;
2703 h->implicit_weight[ref0][ref1][0] =
2704 h->implicit_weight[ref0][ref1][1] = w;
2706 h->implicit_weight[ref0][ref1][field] = w;
2713 * instantaneous decoder refresh.
2715 static void idr(H264Context *h)
2717 ff_h264_remove_all_refs(h);
2718 h->prev_frame_num = 0;
2719 h->prev_frame_num_offset = 0;
2721 h->prev_poc_lsb = 0;
2724 /* forget old pics after a seek */
2725 static void flush_change(H264Context *h)
2728 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2729 h->last_pocs[i] = INT_MIN;
2730 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2731 h->prev_interlaced_frame = 1;
2734 h->cur_pic_ptr->reference = 0;
2736 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2737 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2738 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2739 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2740 ff_h264_reset_sei(h);
2741 h->recovery_frame = -1;
2742 h->frame_recovered = 0;
2745 /* forget old pics after a seek */
2746 static void flush_dpb(AVCodecContext *avctx)
2748 H264Context *h = avctx->priv_data;
2751 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
2752 if (h->delayed_pic[i])
2753 h->delayed_pic[i]->reference = 0;
2754 h->delayed_pic[i] = NULL;
2760 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2761 unref_picture(h, &h->DPB[i]);
2762 h->cur_pic_ptr = NULL;
2763 unref_picture(h, &h->cur_pic);
2765 h->mb_x = h->mb_y = 0;
2767 h->parse_context.state = -1;
2768 h->parse_context.frame_start_found = 0;
2769 h->parse_context.overread = 0;
2770 h->parse_context.overread_index = 0;
2771 h->parse_context.index = 0;
2772 h->parse_context.last_index = 0;
2775 h->context_initialized = 0;
2778 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2780 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2783 h->frame_num_offset = h->prev_frame_num_offset;
2784 if (h->frame_num < h->prev_frame_num)
2785 h->frame_num_offset += max_frame_num;
2787 if (h->sps.poc_type == 0) {
2788 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2790 if (h->poc_lsb < h->prev_poc_lsb &&
2791 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2792 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2793 else if (h->poc_lsb > h->prev_poc_lsb &&
2794 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2795 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2797 h->poc_msb = h->prev_poc_msb;
2799 field_poc[1] = h->poc_msb + h->poc_lsb;
2800 if (h->picture_structure == PICT_FRAME)
2801 field_poc[1] += h->delta_poc_bottom;
2802 } else if (h->sps.poc_type == 1) {
2803 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2806 if (h->sps.poc_cycle_length != 0)
2807 abs_frame_num = h->frame_num_offset + h->frame_num;
2811 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2814 expected_delta_per_poc_cycle = 0;
2815 for (i = 0; i < h->sps.poc_cycle_length; i++)
2816 // FIXME integrate during sps parse
2817 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2819 if (abs_frame_num > 0) {
2820 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2821 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2823 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2824 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2825 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2829 if (h->nal_ref_idc == 0)
2830 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2832 field_poc[0] = expectedpoc + h->delta_poc[0];
2833 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2835 if (h->picture_structure == PICT_FRAME)
2836 field_poc[1] += h->delta_poc[1];
2838 int poc = 2 * (h->frame_num_offset + h->frame_num);
2840 if (!h->nal_ref_idc)
2847 if (h->picture_structure != PICT_BOTTOM_FIELD)
2848 pic_field_poc[0] = field_poc[0];
2849 if (h->picture_structure != PICT_TOP_FIELD)
2850 pic_field_poc[1] = field_poc[1];
2851 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2857 * initialize scan tables
2859 static void init_scan_tables(H264Context *h)
2862 for (i = 0; i < 16; i++) {
2863 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2864 h->zigzag_scan[i] = T(zigzag_scan[i]);
2865 h->field_scan[i] = T(field_scan[i]);
2868 for (i = 0; i < 64; i++) {
2869 #define T(x) (x >> 3) | ((x & 7) << 3)
2870 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2871 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2872 h->field_scan8x8[i] = T(field_scan8x8[i]);
2873 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2876 if (h->sps.transform_bypass) { // FIXME same ugly
2877 h->zigzag_scan_q0 = zigzag_scan;
2878 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
2879 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
2880 h->field_scan_q0 = field_scan;
2881 h->field_scan8x8_q0 = field_scan8x8;
2882 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
2884 h->zigzag_scan_q0 = h->zigzag_scan;
2885 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
2886 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
2887 h->field_scan_q0 = h->field_scan;
2888 h->field_scan8x8_q0 = h->field_scan8x8;
2889 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
2893 static int field_end(H264Context *h, int in_setup)
2895 AVCodecContext *const avctx = h->avctx;
2899 if (!in_setup && !h->droppable)
2900 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2901 h->picture_structure == PICT_BOTTOM_FIELD);
2903 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2904 if (!h->droppable) {
2905 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2906 h->prev_poc_msb = h->poc_msb;
2907 h->prev_poc_lsb = h->poc_lsb;
2909 h->prev_frame_num_offset = h->frame_num_offset;
2910 h->prev_frame_num = h->frame_num;
2911 h->outputed_poc = h->next_outputed_poc;
2914 if (avctx->hwaccel) {
2915 if (avctx->hwaccel->end_frame(avctx) < 0)
2916 av_log(avctx, AV_LOG_ERROR,
2917 "hardware accelerator failed to decode picture\n");
2921 * FIXME: Error handling code does not seem to support interlaced
2922 * when slices span multiple rows
2923 * The ff_er_add_slice calls don't work right for bottom
2924 * fields; they cause massive erroneous error concealing
2925 * Error marking covers both fields (top and bottom).
2926 * This causes a mismatched s->error_count
2927 * and a bad error table. Further, the error count goes to
2928 * INT_MAX when called for bottom field, because mb_y is
2929 * past end by one (callers fault) and resync_mb_y != 0
2930 * causes problems for the first MB line, too.
2932 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h)) {
2933 h->er.cur_pic = h->cur_pic_ptr;
2934 h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
2935 h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
2936 ff_er_frame_end(&h->er);
2940 h->current_slice = 0;
2946 * Replicate H264 "master" context to thread contexts.
2948 static int clone_slice(H264Context *dst, H264Context *src)
2950 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
2951 dst->cur_pic_ptr = src->cur_pic_ptr;
2952 dst->cur_pic = src->cur_pic;
2953 dst->linesize = src->linesize;
2954 dst->uvlinesize = src->uvlinesize;
2955 dst->first_field = src->first_field;
2957 dst->prev_poc_msb = src->prev_poc_msb;
2958 dst->prev_poc_lsb = src->prev_poc_lsb;
2959 dst->prev_frame_num_offset = src->prev_frame_num_offset;
2960 dst->prev_frame_num = src->prev_frame_num;
2961 dst->short_ref_count = src->short_ref_count;
2963 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
2964 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
2965 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
2967 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
2968 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
2974 * Compute profile from profile_idc and constraint_set?_flags.
2978 * @return profile as defined by FF_PROFILE_H264_*
2980 int ff_h264_get_profile(SPS *sps)
2982 int profile = sps->profile_idc;
2984 switch (sps->profile_idc) {
2985 case FF_PROFILE_H264_BASELINE:
2986 // constraint_set1_flag set to 1
2987 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
2989 case FF_PROFILE_H264_HIGH_10:
2990 case FF_PROFILE_H264_HIGH_422:
2991 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
2992 // constraint_set3_flag set to 1
2993 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3000 static int h264_set_parameter_from_sps(H264Context *h)
3002 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3003 (h->sps.bitstream_restriction_flag &&
3004 !h->sps.num_reorder_frames)) {
3005 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3006 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3007 "Reenabling low delay requires a codec flush.\n");
3012 if (h->avctx->has_b_frames < 2)
3013 h->avctx->has_b_frames = !h->low_delay;
3015 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
3016 avpriv_request_sample(h->avctx,
3017 "Different chroma and luma bit depth");
3018 return AVERROR_PATCHWELCOME;
3021 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3022 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
3023 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
3024 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3025 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
3026 h->pixel_shift = h->sps.bit_depth_luma > 8;
3028 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3029 h->sps.chroma_format_idc);
3030 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3031 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3032 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3033 h->sps.chroma_format_idc);
3034 if (CONFIG_ERROR_RESILIENCE)
3035 ff_dsputil_init(&h->dsp, h->avctx);
3036 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3038 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3039 h->sps.bit_depth_luma);
3040 return AVERROR_INVALIDDATA;
3046 static enum AVPixelFormat get_pixel_format(H264Context *h)
3048 switch (h->sps.bit_depth_luma) {
3051 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3052 return AV_PIX_FMT_GBRP9;
3054 return AV_PIX_FMT_YUV444P9;
3055 } else if (CHROMA422(h))
3056 return AV_PIX_FMT_YUV422P9;
3058 return AV_PIX_FMT_YUV420P9;
3062 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3063 return AV_PIX_FMT_GBRP10;
3065 return AV_PIX_FMT_YUV444P10;
3066 } else if (CHROMA422(h))
3067 return AV_PIX_FMT_YUV422P10;
3069 return AV_PIX_FMT_YUV420P10;
3073 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3074 return AV_PIX_FMT_GBRP;
3076 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3077 : AV_PIX_FMT_YUV444P;
3078 } else if (CHROMA422(h)) {
3079 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3080 : AV_PIX_FMT_YUV422P;
3082 return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
3083 h->avctx->codec->pix_fmts :
3084 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3085 h264_hwaccel_pixfmt_list_jpeg_420 :
3086 h264_hwaccel_pixfmt_list_420);
3090 av_log(h->avctx, AV_LOG_ERROR,
3091 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3092 return AVERROR_INVALIDDATA;
3096 /* export coded and cropped frame dimensions to AVCodecContext */
3097 static int init_dimensions(H264Context *h)
3099 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3100 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3102 /* handle container cropping */
3104 FFALIGN(h->avctx->width, 16) == h->width &&
3105 FFALIGN(h->avctx->height, 16) == h->height) {
3106 width = h->avctx->width;
3107 height = h->avctx->height;
3110 if (width <= 0 || height <= 0) {
3111 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3113 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3114 return AVERROR_INVALIDDATA;
3116 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3117 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3124 h->avctx->coded_width = h->width;
3125 h->avctx->coded_height = h->height;
3126 h->avctx->width = width;
3127 h->avctx->height = height;
3132 static int h264_slice_header_init(H264Context *h, int reinit)
3134 int nb_slices = (HAVE_THREADS &&
3135 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3136 h->avctx->thread_count : 1;
3139 h->avctx->sample_aspect_ratio = h->sps.sar;
3140 av_assert0(h->avctx->sample_aspect_ratio.den);
3141 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3142 &h->chroma_x_shift, &h->chroma_y_shift);
3144 if (h->sps.timing_info_present_flag) {
3145 int64_t den = h->sps.time_scale;
3146 if (h->x264_build < 44U)
3148 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3149 h->sps.num_units_in_tick, den, 1 << 30);
3152 h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3157 h->prev_interlaced_frame = 1;
3159 init_scan_tables(h);
3160 ret = ff_h264_alloc_tables(h);
3162 av_log(h->avctx, AV_LOG_ERROR,
3163 "Could not allocate memory for h264\n");
3167 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3170 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3172 max_slices = MAX_THREADS;
3173 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3174 " reducing to %d\n", nb_slices, max_slices);
3175 nb_slices = max_slices;
3177 h->slice_context_count = nb_slices;
3179 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3180 ret = context_init(h);
3182 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3186 for (i = 1; i < h->slice_context_count; i++) {
3188 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3190 return AVERROR(ENOMEM);
3191 c->avctx = h->avctx;
3194 c->h264dsp = h->h264dsp;
3195 c->h264qpel = h->h264qpel;
3196 c->h264chroma = h->h264chroma;
3199 c->pixel_shift = h->pixel_shift;
3200 c->width = h->width;
3201 c->height = h->height;
3202 c->linesize = h->linesize;
3203 c->uvlinesize = h->uvlinesize;
3204 c->chroma_x_shift = h->chroma_x_shift;
3205 c->chroma_y_shift = h->chroma_y_shift;
3206 c->qscale = h->qscale;
3207 c->droppable = h->droppable;
3208 c->data_partitioning = h->data_partitioning;
3209 c->low_delay = h->low_delay;
3210 c->mb_width = h->mb_width;
3211 c->mb_height = h->mb_height;
3212 c->mb_stride = h->mb_stride;
3213 c->mb_num = h->mb_num;
3214 c->flags = h->flags;
3215 c->workaround_bugs = h->workaround_bugs;
3216 c->pict_type = h->pict_type;
3218 init_scan_tables(c);
3219 clone_tables(c, h, i);
3220 c->context_initialized = 1;
3223 for (i = 0; i < h->slice_context_count; i++)
3224 if ((ret = context_init(h->thread_context[i])) < 0) {
3225 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3230 h->context_initialized = 1;
3235 int ff_set_ref_count(H264Context *h)
3237 int num_ref_idx_active_override_flag, max_refs;
3239 // set defaults, might be overridden a few lines later
3240 h->ref_count[0] = h->pps.ref_count[0];
3241 h->ref_count[1] = h->pps.ref_count[1];
3243 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3244 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3245 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3246 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3248 if (num_ref_idx_active_override_flag) {
3249 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3250 if (h->ref_count[0] < 1)
3251 return AVERROR_INVALIDDATA;
3252 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3253 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3254 if (h->ref_count[1] < 1)
3255 return AVERROR_INVALIDDATA;
3259 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3265 h->ref_count[0] = h->ref_count[1] = 0;
3268 max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
3270 if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
3271 av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
3272 h->ref_count[0] = h->ref_count[1] = 0;
3273 return AVERROR_INVALIDDATA;
3280 * Decode a slice header.
3281 * This will also call ff_MPV_common_init() and frame_start() as needed.
3283 * @param h h264context
3284 * @param h0 h264 master context (differs from 'h' when doing sliced based
3285 * parallel decoding)
3287 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3289 static int decode_slice_header(H264Context *h, H264Context *h0)
3291 unsigned int first_mb_in_slice;
3292 unsigned int pps_id;
3294 unsigned int slice_type, tmp, i, j;
3295 int default_ref_list_done = 0;
3296 int last_pic_structure, last_pic_droppable;
3297 int needs_reinit = 0;
3298 int field_pic_flag, bottom_field_flag;
3300 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3301 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3303 first_mb_in_slice = get_ue_golomb(&h->gb);
3305 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3306 if (h0->current_slice && FIELD_PICTURE(h)) {
3310 h0->current_slice = 0;
3311 if (!h0->first_field) {
3312 if (h->cur_pic_ptr && !h->droppable) {
3313 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3314 h->picture_structure == PICT_BOTTOM_FIELD);
3316 h->cur_pic_ptr = NULL;
3320 slice_type = get_ue_golomb_31(&h->gb);
3321 if (slice_type > 9) {
3322 av_log(h->avctx, AV_LOG_ERROR,
3323 "slice type too large (%d) at %d %d\n",
3324 h->slice_type, h->mb_x, h->mb_y);
3325 return AVERROR_INVALIDDATA;
3327 if (slice_type > 4) {
3329 h->slice_type_fixed = 1;
3331 h->slice_type_fixed = 0;
3333 slice_type = golomb_to_pict_type[slice_type];
3334 if (slice_type == AV_PICTURE_TYPE_I ||
3335 (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
3336 default_ref_list_done = 1;
3338 h->slice_type = slice_type;
3339 h->slice_type_nos = slice_type & 3;
3341 // to make a few old functions happy, it's wrong though
3342 h->pict_type = h->slice_type;
3344 pps_id = get_ue_golomb(&h->gb);
3345 if (pps_id >= MAX_PPS_COUNT) {
3346 av_log(h->avctx, AV_LOG_ERROR, "pps_id out of range\n");
3347 return AVERROR_INVALIDDATA;
3349 if (!h0->pps_buffers[pps_id]) {
3350 av_log(h->avctx, AV_LOG_ERROR,
3351 "non-existing PPS %u referenced\n",
3353 return AVERROR_INVALIDDATA;
3355 h->pps = *h0->pps_buffers[pps_id];
3357 if (!h0->sps_buffers[h->pps.sps_id]) {
3358 av_log(h->avctx, AV_LOG_ERROR,
3359 "non-existing SPS %u referenced\n",
3361 return AVERROR_INVALIDDATA;
3364 if (h->pps.sps_id != h->current_sps_id ||
3365 h0->sps_buffers[h->pps.sps_id]->new) {
3366 h0->sps_buffers[h->pps.sps_id]->new = 0;
3368 h->current_sps_id = h->pps.sps_id;
3369 h->sps = *h0->sps_buffers[h->pps.sps_id];
3371 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3372 h->chroma_format_idc != h->sps.chroma_format_idc) {
3373 h->bit_depth_luma = h->sps.bit_depth_luma;
3374 h->chroma_format_idc = h->sps.chroma_format_idc;
3377 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3381 h->avctx->profile = ff_h264_get_profile(&h->sps);
3382 h->avctx->level = h->sps.level_idc;
3383 h->avctx->refs = h->sps.ref_frame_count;
3385 if (h->mb_width != h->sps.mb_width ||
3386 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
3389 h->mb_width = h->sps.mb_width;
3390 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3391 h->mb_num = h->mb_width * h->mb_height;
3392 h->mb_stride = h->mb_width + 1;
3394 h->b_stride = h->mb_width * 4;
3396 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3398 h->width = 16 * h->mb_width;
3399 h->height = 16 * h->mb_height;
3401 ret = init_dimensions(h);
3405 if (h->sps.video_signal_type_present_flag) {
3406 h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
3408 if (h->sps.colour_description_present_flag) {
3409 if (h->avctx->colorspace != h->sps.colorspace)
3411 h->avctx->color_primaries = h->sps.color_primaries;
3412 h->avctx->color_trc = h->sps.color_trc;
3413 h->avctx->colorspace = h->sps.colorspace;
3417 if (h->context_initialized &&
3418 (h->width != h->avctx->coded_width ||
3419 h->height != h->avctx->coded_height ||
3422 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3423 "slice %d\n", h0->current_slice + 1);
3424 return AVERROR_INVALIDDATA;
3429 if ((ret = get_pixel_format(h)) < 0)
3431 h->avctx->pix_fmt = ret;
3433 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3434 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
3436 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3437 av_log(h->avctx, AV_LOG_ERROR,
3438 "h264_slice_header_init() failed\n");
3442 if (!h->context_initialized) {
3444 av_log(h->avctx, AV_LOG_ERROR,
3445 "Cannot (re-)initialize context during parallel decoding.\n");
3446 return AVERROR_PATCHWELCOME;
3449 if ((ret = get_pixel_format(h)) < 0)
3451 h->avctx->pix_fmt = ret;
3453 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3454 av_log(h->avctx, AV_LOG_ERROR,
3455 "h264_slice_header_init() failed\n");
3460 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3461 h->dequant_coeff_pps = pps_id;
3462 init_dequant_tables(h);
3465 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3468 h->mb_aff_frame = 0;
3469 last_pic_structure = h0->picture_structure;
3470 last_pic_droppable = h0->droppable;
3471 h->droppable = h->nal_ref_idc == 0;
3472 if (h->sps.frame_mbs_only_flag) {
3473 h->picture_structure = PICT_FRAME;
3475 field_pic_flag = get_bits1(&h->gb);
3476 if (field_pic_flag) {
3477 bottom_field_flag = get_bits1(&h->gb);
3478 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3480 h->picture_structure = PICT_FRAME;
3481 h->mb_aff_frame = h->sps.mb_aff;
3484 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3486 if (h0->current_slice != 0) {
3487 if (last_pic_structure != h->picture_structure ||
3488 last_pic_droppable != h->droppable) {
3489 av_log(h->avctx, AV_LOG_ERROR,
3490 "Changing field mode (%d -> %d) between slices is not allowed\n",
3491 last_pic_structure, h->picture_structure);
3492 h->picture_structure = last_pic_structure;
3493 h->droppable = last_pic_droppable;
3494 return AVERROR_INVALIDDATA;
3495 } else if (!h0->cur_pic_ptr) {
3496 av_log(h->avctx, AV_LOG_ERROR,
3497 "unset cur_pic_ptr on %d. slice\n",
3498 h0->current_slice + 1);
3499 return AVERROR_INVALIDDATA;
3502 /* Shorten frame num gaps so we don't have to allocate reference
3503 * frames just to throw them away */
3504 if (h->frame_num != h->prev_frame_num) {
3505 int unwrap_prev_frame_num = h->prev_frame_num;
3506 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3508 if (unwrap_prev_frame_num > h->frame_num)
3509 unwrap_prev_frame_num -= max_frame_num;
3511 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3512 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3513 if (unwrap_prev_frame_num < 0)
3514 unwrap_prev_frame_num += max_frame_num;
3516 h->prev_frame_num = unwrap_prev_frame_num;
3520 /* See if we have a decoded first field looking for a pair...
3521 * Here, we're using that to see if we should mark previously
3522 * decode frames as "finished".
3523 * We have to do that before the "dummy" in-between frame allocation,
3524 * since that can modify s->current_picture_ptr. */
3525 if (h0->first_field) {
3526 assert(h0->cur_pic_ptr);
3527 assert(h0->cur_pic_ptr->f.data[0]);
3528 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3530 /* figure out if we have a complementary field pair */
3531 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3532 /* Previous field is unmatched. Don't display it, but let it
3533 * remain for reference if marked as such. */
3534 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3535 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3536 last_pic_structure == PICT_TOP_FIELD);
3539 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3540 /* This and previous field were reference, but had
3541 * different frame_nums. Consider this field first in
3542 * pair. Throw away previous field except for reference
3544 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
3545 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3546 last_pic_structure == PICT_TOP_FIELD);
3549 /* Second field in complementary pair */
3550 if (!((last_pic_structure == PICT_TOP_FIELD &&
3551 h->picture_structure == PICT_BOTTOM_FIELD) ||
3552 (last_pic_structure == PICT_BOTTOM_FIELD &&
3553 h->picture_structure == PICT_TOP_FIELD))) {
3554 av_log(h->avctx, AV_LOG_ERROR,
3555 "Invalid field mode combination %d/%d\n",
3556 last_pic_structure, h->picture_structure);
3557 h->picture_structure = last_pic_structure;
3558 h->droppable = last_pic_droppable;
3559 return AVERROR_INVALIDDATA;
3560 } else if (last_pic_droppable != h->droppable) {
3561 avpriv_request_sample(h->avctx,
3562 "Found reference and non-reference fields in the same frame, which");
3563 h->picture_structure = last_pic_structure;
3564 h->droppable = last_pic_droppable;
3565 return AVERROR_PATCHWELCOME;
3571 while (h->frame_num != h->prev_frame_num &&
3572 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3573 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3574 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3575 h->frame_num, h->prev_frame_num);
3576 ret = h264_frame_start(h);
3579 h->prev_frame_num++;
3580 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3581 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3582 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3583 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3584 ret = ff_generate_sliding_window_mmcos(h, 1);
3585 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3587 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3588 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3590 /* Error concealment: If a ref is missing, copy the previous ref
3592 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3593 * many assumptions about there being no actual duplicates.
3594 * FIXME: This does not copy padding for out-of-frame motion
3595 * vectors. Given we are concealing a lost frame, this probably
3596 * is not noticeable by comparison, but it should be fixed. */
3597 if (h->short_ref_count) {
3599 av_image_copy(h->short_ref[0]->f.data,
3600 h->short_ref[0]->f.linesize,
3601 (const uint8_t **)prev->f.data,
3606 h->short_ref[0]->poc = prev->poc + 2;
3608 h->short_ref[0]->frame_num = h->prev_frame_num;
3612 /* See if we have a decoded first field looking for a pair...
3613 * We're using that to see whether to continue decoding in that
3614 * frame, or to allocate a new one. */
3615 if (h0->first_field) {
3616 assert(h0->cur_pic_ptr);
3617 assert(h0->cur_pic_ptr->f.data[0]);
3618 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3620 /* figure out if we have a complementary field pair */
3621 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3622 /* Previous field is unmatched. Don't display it, but let it
3623 * remain for reference if marked as such. */
3624 h0->cur_pic_ptr = NULL;
3625 h0->first_field = FIELD_PICTURE(h);
3627 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3628 /* This and the previous field had different frame_nums.
3629 * Consider this field first in pair. Throw away previous
3630 * one except for reference purposes. */
3631 h0->first_field = 1;
3632 h0->cur_pic_ptr = NULL;
3634 /* Second field in complementary pair */
3635 h0->first_field = 0;
3639 /* Frame or first field in a potentially complementary pair */
3640 h0->first_field = FIELD_PICTURE(h);
3643 if (!FIELD_PICTURE(h) || h0->first_field) {
3644 if (h264_frame_start(h) < 0) {
3645 h0->first_field = 0;
3646 return AVERROR_INVALIDDATA;
3649 release_unused_pictures(h, 0);
3652 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3655 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3657 assert(h->mb_num == h->mb_width * h->mb_height);
3658 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3659 first_mb_in_slice >= h->mb_num) {
3660 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3661 return AVERROR_INVALIDDATA;
3663 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3664 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3665 FIELD_OR_MBAFF_PICTURE(h);
3666 if (h->picture_structure == PICT_BOTTOM_FIELD)
3667 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3668 assert(h->mb_y < h->mb_height);
3670 if (h->picture_structure == PICT_FRAME) {
3671 h->curr_pic_num = h->frame_num;
3672 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3674 h->curr_pic_num = 2 * h->frame_num + 1;
3675 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3678 if (h->nal_unit_type == NAL_IDR_SLICE)
3679 get_ue_golomb(&h->gb); /* idr_pic_id */
3681 if (h->sps.poc_type == 0) {
3682 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3684 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3685 h->delta_poc_bottom = get_se_golomb(&h->gb);
3688 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3689 h->delta_poc[0] = get_se_golomb(&h->gb);
3691 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3692 h->delta_poc[1] = get_se_golomb(&h->gb);
3695 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3697 if (h->pps.redundant_pic_cnt_present)
3698 h->redundant_pic_count = get_ue_golomb(&h->gb);
3700 ret = ff_set_ref_count(h);
3704 if (!default_ref_list_done)
3705 ff_h264_fill_default_ref_list(h);
3707 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3708 ret = ff_h264_decode_ref_pic_list_reordering(h);
3710 h->ref_count[1] = h->ref_count[0] = 0;
3715 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3716 (h->pps.weighted_bipred_idc == 1 &&
3717 h->slice_type_nos == AV_PICTURE_TYPE_B))
3718 ff_pred_weight_table(h);
3719 else if (h->pps.weighted_bipred_idc == 2 &&
3720 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3721 implicit_weight_table(h, -1);
3724 for (i = 0; i < 2; i++) {
3725 h->luma_weight_flag[i] = 0;
3726 h->chroma_weight_flag[i] = 0;
3730 // If frame-mt is enabled, only update mmco tables for the first slice
3731 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3732 // or h->mmco, which will cause ref list mix-ups and decoding errors
3733 // further down the line. This may break decoding if the first slice is
3734 // corrupt, thus we only do this if frame-mt is enabled.
3735 if (h->nal_ref_idc) {
3736 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3737 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3738 h0->current_slice == 0);
3739 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3740 return AVERROR_INVALIDDATA;
3743 if (FRAME_MBAFF(h)) {
3744 ff_h264_fill_mbaff_ref_list(h);
3746 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3747 implicit_weight_table(h, 0);
3748 implicit_weight_table(h, 1);
3752 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3753 ff_h264_direct_dist_scale_factor(h);
3754 ff_h264_direct_ref_list_init(h);
3756 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3757 tmp = get_ue_golomb_31(&h->gb);
3759 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3760 return AVERROR_INVALIDDATA;
3762 h->cabac_init_idc = tmp;
3765 h->last_qscale_diff = 0;
3766 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3767 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3768 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3769 return AVERROR_INVALIDDATA;
3772 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3773 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3774 // FIXME qscale / qp ... stuff
3775 if (h->slice_type == AV_PICTURE_TYPE_SP)
3776 get_bits1(&h->gb); /* sp_for_switch_flag */
3777 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3778 h->slice_type == AV_PICTURE_TYPE_SI)
3779 get_se_golomb(&h->gb); /* slice_qs_delta */
3781 h->deblocking_filter = 1;
3782 h->slice_alpha_c0_offset = 52;
3783 h->slice_beta_offset = 52;
3784 if (h->pps.deblocking_filter_parameters_present) {
3785 tmp = get_ue_golomb_31(&h->gb);
3787 av_log(h->avctx, AV_LOG_ERROR,
3788 "deblocking_filter_idc %u out of range\n", tmp);
3789 return AVERROR_INVALIDDATA;
3791 h->deblocking_filter = tmp;
3792 if (h->deblocking_filter < 2)
3793 h->deblocking_filter ^= 1; // 1<->0
3795 if (h->deblocking_filter) {
3796 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3797 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3798 if (h->slice_alpha_c0_offset > 104U ||
3799 h->slice_beta_offset > 104U) {
3800 av_log(h->avctx, AV_LOG_ERROR,
3801 "deblocking filter parameters %d %d out of range\n",
3802 h->slice_alpha_c0_offset, h->slice_beta_offset);
3803 return AVERROR_INVALIDDATA;
3808 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3809 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3810 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3811 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3812 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3813 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3814 h->nal_ref_idc == 0))
3815 h->deblocking_filter = 0;
3817 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3818 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3819 /* Cheat slightly for speed:
3820 * Do not bother to deblock across slices. */
3821 h->deblocking_filter = 2;
3823 h0->max_contexts = 1;
3824 if (!h0->single_decode_warning) {
3825 av_log(h->avctx, AV_LOG_INFO,
3826 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3827 h0->single_decode_warning = 1;
3830 av_log(h->avctx, AV_LOG_ERROR,
3831 "Deblocking switched inside frame.\n");
3836 h->qp_thresh = 15 + 52 -
3837 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3839 h->pps.chroma_qp_index_offset[0],
3840 h->pps.chroma_qp_index_offset[1]) +
3841 6 * (h->sps.bit_depth_luma - 8);
3843 h0->last_slice_type = slice_type;
3844 h->slice_num = ++h0->current_slice;
3845 if (h->slice_num >= MAX_SLICES) {
3846 av_log(h->avctx, AV_LOG_ERROR,
3847 "Too many slices, increase MAX_SLICES and recompile\n");
3850 for (j = 0; j < 2; j++) {
3852 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
3853 for (i = 0; i < 16; i++) {
3855 if (j < h->list_count && i < h->ref_count[j] &&
3856 h->ref_list[j][i].f.buf[0]) {
3858 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
3859 for (k = 0; k < h->short_ref_count; k++)
3860 if (h->short_ref[k]->f.buf[0]->buffer == buf) {
3864 for (k = 0; k < h->long_ref_count; k++)
3865 if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
3866 id_list[i] = h->short_ref_count + k;
3874 for (i = 0; i < 16; i++)
3875 ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
3877 ref2frm[18 + 1] = -1;
3878 for (i = 16; i < 48; i++)
3879 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
3880 (h->ref_list[j][i].reference & 3);
3883 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
3884 av_log(h->avctx, AV_LOG_DEBUG,
3885 "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",
3887 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
3889 av_get_picture_type_char(h->slice_type),
3890 h->slice_type_fixed ? " fix" : "",
3891 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
3892 pps_id, h->frame_num,
3893 h->cur_pic_ptr->field_poc[0],
3894 h->cur_pic_ptr->field_poc[1],
3895 h->ref_count[0], h->ref_count[1],
3897 h->deblocking_filter,
3898 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
3900 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
3901 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
3907 int ff_h264_get_slice_type(const H264Context *h)
3909 switch (h->slice_type) {
3910 case AV_PICTURE_TYPE_P:
3912 case AV_PICTURE_TYPE_B:
3914 case AV_PICTURE_TYPE_I:
3916 case AV_PICTURE_TYPE_SP:
3918 case AV_PICTURE_TYPE_SI:
3921 return AVERROR_INVALIDDATA;
3925 static av_always_inline void fill_filter_caches_inter(H264Context *h,
3926 int mb_type, int top_xy,
3927 int left_xy[LEFT_MBS],
3929 int left_type[LEFT_MBS],
3930 int mb_xy, int list)
3932 int b_stride = h->b_stride;
3933 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
3934 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
3935 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
3936 if (USES_LIST(top_type, list)) {
3937 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
3938 const int b8_xy = 4 * top_xy + 2;
3939 int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
3940 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
3941 ref_cache[0 - 1 * 8] =
3942 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
3943 ref_cache[2 - 1 * 8] =
3944 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
3946 AV_ZERO128(mv_dst - 1 * 8);
3947 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3950 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
3951 if (USES_LIST(left_type[LTOP], list)) {
3952 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
3953 const int b8_xy = 4 * left_xy[LTOP] + 1;
3954 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
3955 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
3956 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
3957 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
3958 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
3960 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
3961 ref_cache[-1 + 16] =
3962 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
3964 AV_ZERO32(mv_dst - 1 + 0);
3965 AV_ZERO32(mv_dst - 1 + 8);
3966 AV_ZERO32(mv_dst - 1 + 16);
3967 AV_ZERO32(mv_dst - 1 + 24);
3970 ref_cache[-1 + 16] =
3971 ref_cache[-1 + 24] = LIST_NOT_USED;
3976 if (!USES_LIST(mb_type, list)) {
3977 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
3978 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3979 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3980 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3981 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
3986 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
3987 int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2);
3988 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
3989 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
3990 AV_WN32A(&ref_cache[0 * 8], ref01);
3991 AV_WN32A(&ref_cache[1 * 8], ref01);
3992 AV_WN32A(&ref_cache[2 * 8], ref23);
3993 AV_WN32A(&ref_cache[3 * 8], ref23);
3997 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
3998 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
3999 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4000 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4001 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4007 * @return non zero if the loop filter can be skipped
4009 static int fill_filter_caches(H264Context *h, int mb_type)
4011 const int mb_xy = h->mb_xy;
4012 int top_xy, left_xy[LEFT_MBS];
4013 int top_type, left_type[LEFT_MBS];
4017 top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4019 /* Wow, what a mess, why didn't they simplify the interlacing & intra
4020 * stuff, I can't imagine that these complex rules are worth it. */
4022 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4023 if (FRAME_MBAFF(h)) {
4024 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4025 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4027 if (left_mb_field_flag != curr_mb_field_flag)
4028 left_xy[LTOP] -= h->mb_stride;
4030 if (curr_mb_field_flag)
4031 top_xy += h->mb_stride &
4032 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4033 if (left_mb_field_flag != curr_mb_field_flag)
4034 left_xy[LBOT] += h->mb_stride;
4038 h->top_mb_xy = top_xy;
4039 h->left_mb_xy[LTOP] = left_xy[LTOP];
4040 h->left_mb_xy[LBOT] = left_xy[LBOT];
4042 /* For sufficiently low qp, filtering wouldn't do anything.
4043 * This is a conservative estimate: could also check beta_offset
4044 * and more accurate chroma_qp. */
4045 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4046 int qp = h->cur_pic.qscale_table[mb_xy];
4047 if (qp <= qp_thresh &&
4048 (left_xy[LTOP] < 0 ||
4049 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4051 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4052 if (!FRAME_MBAFF(h))
4054 if ((left_xy[LTOP] < 0 ||
4055 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4056 (top_xy < h->mb_stride ||
4057 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4062 top_type = h->cur_pic.mb_type[top_xy];
4063 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4064 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4065 if (h->deblocking_filter == 2) {
4066 if (h->slice_table[top_xy] != h->slice_num)
4068 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4069 left_type[LTOP] = left_type[LBOT] = 0;
4071 if (h->slice_table[top_xy] == 0xFFFF)
4073 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4074 left_type[LTOP] = left_type[LBOT] = 0;
4076 h->top_type = top_type;
4077 h->left_type[LTOP] = left_type[LTOP];
4078 h->left_type[LBOT] = left_type[LBOT];
4080 if (IS_INTRA(mb_type))
4083 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4084 top_type, left_type, mb_xy, 0);
4085 if (h->list_count == 2)
4086 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4087 top_type, left_type, mb_xy, 1);
4089 nnz = h->non_zero_count[mb_xy];
4090 nnz_cache = h->non_zero_count_cache;
4091 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4092 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4093 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4094 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4095 h->cbp = h->cbp_table[mb_xy];
4098 nnz = h->non_zero_count[top_xy];
4099 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4102 if (left_type[LTOP]) {
4103 nnz = h->non_zero_count[left_xy[LTOP]];
4104 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4105 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4106 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4107 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4110 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4111 * from what the loop filter needs */
4112 if (!CABAC(h) && h->pps.transform_8x8_mode) {
4113 if (IS_8x8DCT(top_type)) {
4114 nnz_cache[4 + 8 * 0] =
4115 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4116 nnz_cache[6 + 8 * 0] =
4117 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4119 if (IS_8x8DCT(left_type[LTOP])) {
4120 nnz_cache[3 + 8 * 1] =
4121 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4123 if (IS_8x8DCT(left_type[LBOT])) {
4124 nnz_cache[3 + 8 * 3] =
4125 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4128 if (IS_8x8DCT(mb_type)) {
4129 nnz_cache[scan8[0]] =
4130 nnz_cache[scan8[1]] =
4131 nnz_cache[scan8[2]] =
4132 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4134 nnz_cache[scan8[0 + 4]] =
4135 nnz_cache[scan8[1 + 4]] =
4136 nnz_cache[scan8[2 + 4]] =
4137 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4139 nnz_cache[scan8[0 + 8]] =
4140 nnz_cache[scan8[1 + 8]] =
4141 nnz_cache[scan8[2 + 8]] =
4142 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4144 nnz_cache[scan8[0 + 12]] =
4145 nnz_cache[scan8[1 + 12]] =
4146 nnz_cache[scan8[2 + 12]] =
4147 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4154 static void loop_filter(H264Context *h, int start_x, int end_x)
4156 uint8_t *dest_y, *dest_cb, *dest_cr;
4157 int linesize, uvlinesize, mb_x, mb_y;
4158 const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4159 const int old_slice_type = h->slice_type;
4160 const int pixel_shift = h->pixel_shift;
4161 const int block_h = 16 >> h->chroma_y_shift;
4163 if (h->deblocking_filter) {
4164 for (mb_x = start_x; mb_x < end_x; mb_x++)
4165 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4167 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4168 h->slice_num = h->slice_table[mb_xy];
4169 mb_type = h->cur_pic.mb_type[mb_xy];
4170 h->list_count = h->list_counts[mb_xy];
4174 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4178 dest_y = h->cur_pic.f.data[0] +
4179 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4180 dest_cb = h->cur_pic.f.data[1] +
4181 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4182 mb_y * h->uvlinesize * block_h;
4183 dest_cr = h->cur_pic.f.data[2] +
4184 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4185 mb_y * h->uvlinesize * block_h;
4186 // FIXME simplify above
4189 linesize = h->mb_linesize = h->linesize * 2;
4190 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4191 if (mb_y & 1) { // FIXME move out of this function?
4192 dest_y -= h->linesize * 15;
4193 dest_cb -= h->uvlinesize * (block_h - 1);
4194 dest_cr -= h->uvlinesize * (block_h - 1);
4197 linesize = h->mb_linesize = h->linesize;
4198 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4200 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4202 if (fill_filter_caches(h, mb_type))
4204 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4205 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4207 if (FRAME_MBAFF(h)) {
4208 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4209 linesize, uvlinesize);
4211 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4212 dest_cr, linesize, uvlinesize);
4216 h->slice_type = old_slice_type;
4218 h->mb_y = end_mb_y - FRAME_MBAFF(h);
4219 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4220 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4223 static void predict_field_decoding_flag(H264Context *h)
4225 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4226 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4227 h->cur_pic.mb_type[mb_xy - 1] :
4228 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4229 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4230 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4234 * Draw edges and report progress for the last MB row.
4236 static void decode_finish_row(H264Context *h)
4238 int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4239 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4240 int height = 16 << FRAME_MBAFF(h);
4241 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4243 if (h->deblocking_filter) {
4244 if ((top + height) >= pic_height)
4245 height += deblock_border;
4246 top -= deblock_border;
4249 if (top >= pic_height || (top + height) < 0)
4252 height = FFMIN(height, pic_height - top);
4254 height = top + height;
4258 ff_h264_draw_horiz_band(h, top, height);
4263 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4264 h->picture_structure == PICT_BOTTOM_FIELD);
4267 static void er_add_slice(H264Context *h, int startx, int starty,
4268 int endx, int endy, int status)
4270 #if CONFIG_ERROR_RESILIENCE
4271 ERContext *er = &h->er;
4273 er->ref_count = h->ref_count[0];
4274 ff_er_add_slice(er, startx, starty, endx, endy, status);
4278 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4280 H264Context *h = *(void **)arg;
4281 int lf_x_start = h->mb_x;
4283 h->mb_skip_run = -1;
4285 h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4286 avctx->codec_id != AV_CODEC_ID_H264 ||
4287 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4291 align_get_bits(&h->gb);
4294 ff_init_cabac_decoder(&h->cabac,
4295 h->gb.buffer + get_bits_count(&h->gb) / 8,
4296 (get_bits_left(&h->gb) + 7) / 8);
4298 ff_h264_init_cabac_states(h);
4302 int ret = ff_h264_decode_mb_cabac(h);
4304 // STOP_TIMER("decode_mb_cabac")
4307 ff_h264_hl_decode_mb(h);
4309 // FIXME optimal? or let mb_decode decode 16x32 ?
4310 if (ret >= 0 && FRAME_MBAFF(h)) {
4313 ret = ff_h264_decode_mb_cabac(h);
4316 ff_h264_hl_decode_mb(h);
4319 eos = get_cabac_terminate(&h->cabac);
4321 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4322 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4323 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4324 h->mb_y, ER_MB_END);
4325 if (h->mb_x >= lf_x_start)
4326 loop_filter(h, lf_x_start, h->mb_x + 1);
4329 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4330 av_log(h->avctx, AV_LOG_ERROR,
4331 "error while decoding MB %d %d, bytestream (%td)\n",
4333 h->cabac.bytestream_end - h->cabac.bytestream);
4334 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4335 h->mb_y, ER_MB_ERROR);
4336 return AVERROR_INVALIDDATA;
4339 if (++h->mb_x >= h->mb_width) {
4340 loop_filter(h, lf_x_start, h->mb_x);
4341 h->mb_x = lf_x_start = 0;
4342 decode_finish_row(h);
4344 if (FIELD_OR_MBAFF_PICTURE(h)) {
4346 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4347 predict_field_decoding_flag(h);
4351 if (eos || h->mb_y >= h->mb_height) {
4352 tprintf(h->avctx, "slice end %d %d\n",
4353 get_bits_count(&h->gb), h->gb.size_in_bits);
4354 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4355 h->mb_y, ER_MB_END);
4356 if (h->mb_x > lf_x_start)
4357 loop_filter(h, lf_x_start, h->mb_x);
4363 int ret = ff_h264_decode_mb_cavlc(h);
4366 ff_h264_hl_decode_mb(h);
4368 // FIXME optimal? or let mb_decode decode 16x32 ?
4369 if (ret >= 0 && FRAME_MBAFF(h)) {
4371 ret = ff_h264_decode_mb_cavlc(h);
4374 ff_h264_hl_decode_mb(h);
4379 av_log(h->avctx, AV_LOG_ERROR,
4380 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4381 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4382 h->mb_y, ER_MB_ERROR);
4386 if (++h->mb_x >= h->mb_width) {
4387 loop_filter(h, lf_x_start, h->mb_x);
4388 h->mb_x = lf_x_start = 0;
4389 decode_finish_row(h);
4391 if (FIELD_OR_MBAFF_PICTURE(h)) {
4393 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4394 predict_field_decoding_flag(h);
4396 if (h->mb_y >= h->mb_height) {
4397 tprintf(h->avctx, "slice end %d %d\n",
4398 get_bits_count(&h->gb), h->gb.size_in_bits);
4400 if (get_bits_left(&h->gb) == 0) {
4401 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4402 h->mb_x - 1, h->mb_y,
4407 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4408 h->mb_x - 1, h->mb_y,
4411 return AVERROR_INVALIDDATA;
4416 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4417 tprintf(h->avctx, "slice end %d %d\n",
4418 get_bits_count(&h->gb), h->gb.size_in_bits);
4420 if (get_bits_left(&h->gb) == 0) {
4421 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4422 h->mb_x - 1, h->mb_y,
4424 if (h->mb_x > lf_x_start)
4425 loop_filter(h, lf_x_start, h->mb_x);
4429 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4430 h->mb_y, ER_MB_ERROR);
4432 return AVERROR_INVALIDDATA;
4440 * Call decode_slice() for each context.
4442 * @param h h264 master context
4443 * @param context_count number of contexts to execute
4445 static int execute_decode_slices(H264Context *h, int context_count)
4447 AVCodecContext *const avctx = h->avctx;
4451 if (h->avctx->hwaccel)
4453 if (context_count == 1) {
4454 return decode_slice(avctx, &h);
4456 for (i = 1; i < context_count; i++) {
4457 hx = h->thread_context[i];
4458 hx->er.error_count = 0;
4461 avctx->execute(avctx, decode_slice, h->thread_context,
4462 NULL, context_count, sizeof(void *));
4464 /* pull back stuff from slices to master context */
4465 hx = h->thread_context[context_count - 1];
4468 h->droppable = hx->droppable;
4469 h->picture_structure = hx->picture_structure;
4470 for (i = 1; i < context_count; i++)
4471 h->er.error_count += h->thread_context[i]->er.error_count;
4477 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4478 int parse_extradata)
4480 AVCodecContext *const avctx = h->avctx;
4481 H264Context *hx; ///< thread context
4485 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4486 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4490 h->max_contexts = h->slice_context_count;
4491 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4492 h->current_slice = 0;
4493 if (!h->first_field)
4494 h->cur_pic_ptr = NULL;
4495 ff_h264_reset_sei(h);
4498 for (; pass <= 1; pass++) {
4501 next_avc = h->is_avc ? 0 : buf_size;
4511 if (buf_index >= next_avc) {
4512 if (buf_index >= buf_size - h->nal_length_size)
4515 for (i = 0; i < h->nal_length_size; i++)
4516 nalsize = (nalsize << 8) | buf[buf_index++];
4517 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4518 av_log(h->avctx, AV_LOG_ERROR,
4519 "AVC: nal size %d\n", nalsize);
4522 next_avc = buf_index + nalsize;
4524 // start code prefix search
4525 for (; buf_index + 3 < next_avc; buf_index++)
4526 // This should always succeed in the first iteration.
4527 if (buf[buf_index] == 0 &&
4528 buf[buf_index + 1] == 0 &&
4529 buf[buf_index + 2] == 1)
4532 if (buf_index + 3 >= buf_size) {
4533 buf_index = buf_size;
4538 if (buf_index >= next_avc)
4542 hx = h->thread_context[context_count];
4544 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4545 &consumed, next_avc - buf_index);
4546 if (ptr == NULL || dst_length < 0) {
4550 i = buf_index + consumed;
4551 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4552 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4553 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4554 h->workaround_bugs |= FF_BUG_TRUNCATED;
4556 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4557 while (ptr[dst_length - 1] == 0 && dst_length > 0)
4559 bit_length = !dst_length ? 0
4561 decode_rbsp_trailing(h, ptr + dst_length - 1));
4563 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4564 av_log(h->avctx, AV_LOG_DEBUG,
4565 "NAL %d at %d/%d length %d\n",
4566 hx->nal_unit_type, buf_index, buf_size, dst_length);
4568 if (h->is_avc && (nalsize != consumed) && nalsize)
4569 av_log(h->avctx, AV_LOG_DEBUG,
4570 "AVC: Consumed only %d bytes instead of %d\n",
4573 buf_index += consumed;
4577 /* packets can sometimes contain multiple PPS/SPS,
4578 * e.g. two PAFF field pictures in one packet, or a demuxer
4579 * which splits NALs strangely if so, when frame threading we
4580 * can't start the next thread until we've read all of them */
4581 switch (hx->nal_unit_type) {
4584 nals_needed = nal_index;
4589 init_get_bits(&hx->gb, ptr, bit_length);
4590 if (!get_ue_golomb(&hx->gb))
4591 nals_needed = nal_index;
4596 if (avctx->skip_frame >= AVDISCARD_NONREF &&
4597 h->nal_ref_idc == 0 &&
4598 h->nal_unit_type != NAL_SEI)
4602 /* Ignore every NAL unit type except PPS and SPS during extradata
4603 * parsing. Decoding slices is not possible in codec init
4605 if (parse_extradata && HAVE_THREADS &&
4606 (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
4607 (hx->nal_unit_type != NAL_PPS &&
4608 hx->nal_unit_type != NAL_SPS)) {
4609 if (hx->nal_unit_type < NAL_AUD ||
4610 hx->nal_unit_type > NAL_AUXILIARY_SLICE)
4611 av_log(avctx, AV_LOG_INFO,
4612 "Ignoring NAL unit %d during extradata parsing\n",
4614 hx->nal_unit_type = NAL_FF_IGNORE;
4617 switch (hx->nal_unit_type) {
4619 if (h->nal_unit_type != NAL_IDR_SLICE) {
4620 av_log(h->avctx, AV_LOG_ERROR,
4621 "Invalid mix of idr and non-idr slices\n");
4625 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4627 init_get_bits(&hx->gb, ptr, bit_length);
4629 hx->inter_gb_ptr = &hx->gb;
4630 hx->data_partitioning = 0;
4632 if ((err = decode_slice_header(hx, h)))
4635 if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
4636 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4637 ((1 << h->sps.log2_max_frame_num) - 1);
4640 h->cur_pic_ptr->f.key_frame |=
4641 (hx->nal_unit_type == NAL_IDR_SLICE) ||
4642 (h->sei_recovery_frame_cnt >= 0);
4644 if (hx->nal_unit_type == NAL_IDR_SLICE ||
4645 h->recovery_frame == h->frame_num) {
4646 h->recovery_frame = -1;
4647 h->cur_pic_ptr->recovered = 1;
4649 // If we have an IDR, all frames after it in decoded order are
4651 if (hx->nal_unit_type == NAL_IDR_SLICE)
4652 h->frame_recovered |= FRAME_RECOVERED_IDR;
4653 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
4655 if (h->current_slice == 1) {
4656 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4657 decode_postinit(h, nal_index >= nals_needed);
4659 if (h->avctx->hwaccel &&
4660 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4664 if (hx->redundant_pic_count == 0 &&
4665 (avctx->skip_frame < AVDISCARD_NONREF ||
4667 (avctx->skip_frame < AVDISCARD_BIDIR ||
4668 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4669 (avctx->skip_frame < AVDISCARD_NONKEY ||
4670 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4671 avctx->skip_frame < AVDISCARD_ALL) {
4672 if (avctx->hwaccel) {
4673 ret = avctx->hwaccel->decode_slice(avctx,
4674 &buf[buf_index - consumed],
4683 init_get_bits(&hx->gb, ptr, bit_length);
4685 hx->inter_gb_ptr = NULL;
4687 if ((err = decode_slice_header(hx, h)) < 0)
4690 hx->data_partitioning = 1;
4693 init_get_bits(&hx->intra_gb, ptr, bit_length);
4694 hx->intra_gb_ptr = &hx->intra_gb;
4697 init_get_bits(&hx->inter_gb, ptr, bit_length);
4698 hx->inter_gb_ptr = &hx->inter_gb;
4700 if (hx->redundant_pic_count == 0 &&
4702 hx->data_partitioning &&
4703 h->cur_pic_ptr && h->context_initialized &&
4704 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4705 (avctx->skip_frame < AVDISCARD_BIDIR ||
4706 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4707 (avctx->skip_frame < AVDISCARD_NONKEY ||
4708 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4709 avctx->skip_frame < AVDISCARD_ALL)
4713 init_get_bits(&h->gb, ptr, bit_length);
4714 ff_h264_decode_sei(h);
4717 init_get_bits(&h->gb, ptr, bit_length);
4718 ret = ff_h264_decode_seq_parameter_set(h);
4719 if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
4720 av_log(h->avctx, AV_LOG_DEBUG,
4721 "SPS decoding failure, trying again with the complete NAL\n");
4722 init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
4724 ff_h264_decode_seq_parameter_set(h);
4727 ret = h264_set_parameter_from_sps(h);
4733 init_get_bits(&h->gb, ptr, bit_length);
4734 ff_h264_decode_picture_parameter_set(h, bit_length);
4737 case NAL_END_SEQUENCE:
4738 case NAL_END_STREAM:
4739 case NAL_FILLER_DATA:
4741 case NAL_AUXILIARY_SLICE:
4746 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4747 hx->nal_unit_type, bit_length);
4750 if (context_count == h->max_contexts) {
4751 execute_decode_slices(h, context_count);
4756 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
4757 else if (err == 1) {
4758 /* Slice could not be decoded in parallel mode, copy down
4759 * NAL unit stuff to context 0 and restart. Note that
4760 * rbsp_buffer is not transferred, but since we no longer
4761 * run in parallel mode this should not be an issue. */
4762 h->nal_unit_type = hx->nal_unit_type;
4763 h->nal_ref_idc = hx->nal_ref_idc;
4770 execute_decode_slices(h, context_count);
4774 if (h->cur_pic_ptr && !h->droppable) {
4775 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
4776 h->picture_structure == PICT_BOTTOM_FIELD);
4779 return (ret < 0) ? ret : buf_index;
4783 * Return the number of bytes consumed for building the current frame.
4785 static int get_consumed_bytes(int pos, int buf_size)
4788 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
4789 if (pos + 10 > buf_size)
4790 pos = buf_size; // oops ;)
4795 static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
4798 int ret = av_frame_ref(dst, src);
4805 for (i = 0; i < 3; i++) {
4806 int hshift = (i > 0) ? h->chroma_x_shift : 0;
4807 int vshift = (i > 0) ? h->chroma_y_shift : 0;
4808 int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
4809 (h->sps.crop_top >> vshift) * dst->linesize[i];
4810 dst->data[i] += off;
4815 static int decode_frame(AVCodecContext *avctx, void *data,
4816 int *got_frame, AVPacket *avpkt)
4818 const uint8_t *buf = avpkt->data;
4819 int buf_size = avpkt->size;
4820 H264Context *h = avctx->priv_data;
4821 AVFrame *pict = data;
4825 h->flags = avctx->flags;
4827 /* end of stream, output what is still in the buffers */
4829 if (buf_size == 0) {
4833 h->cur_pic_ptr = NULL;
4835 // FIXME factorize this with the output code below
4836 out = h->delayed_pic[0];
4839 h->delayed_pic[i] &&
4840 !h->delayed_pic[i]->f.key_frame &&
4841 !h->delayed_pic[i]->mmco_reset;
4843 if (h->delayed_pic[i]->poc < out->poc) {
4844 out = h->delayed_pic[i];
4848 for (i = out_idx; h->delayed_pic[i]; i++)
4849 h->delayed_pic[i] = h->delayed_pic[i + 1];
4852 ret = output_frame(h, pict, &out->f);
4861 buf_index = decode_nal_units(h, buf, buf_size, 0);
4863 return AVERROR_INVALIDDATA;
4865 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
4870 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
4871 if (avctx->skip_frame >= AVDISCARD_NONREF)
4873 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
4874 return AVERROR_INVALIDDATA;
4877 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
4878 (h->mb_y >= h->mb_height && h->mb_height)) {
4879 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
4880 decode_postinit(h, 1);
4885 if (h->next_output_pic && ((avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT) ||
4886 h->next_output_pic->recovered)) {
4887 if (!h->next_output_pic->recovered)
4888 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
4890 ret = output_frame(h, pict, &h->next_output_pic->f);
4897 assert(pict->data[0] || !*got_frame);
4899 return get_consumed_bytes(buf_index, buf_size);
4902 av_cold void ff_h264_free_context(H264Context *h)
4906 free_tables(h, 1); // FIXME cleanup init stuff perhaps
4908 for (i = 0; i < MAX_SPS_COUNT; i++)
4909 av_freep(h->sps_buffers + i);
4911 for (i = 0; i < MAX_PPS_COUNT; i++)
4912 av_freep(h->pps_buffers + i);
4915 static av_cold int h264_decode_end(AVCodecContext *avctx)
4917 H264Context *h = avctx->priv_data;
4919 ff_h264_free_context(h);
4921 unref_picture(h, &h->cur_pic);
4926 static const AVProfile profiles[] = {
4927 { FF_PROFILE_H264_BASELINE, "Baseline" },
4928 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
4929 { FF_PROFILE_H264_MAIN, "Main" },
4930 { FF_PROFILE_H264_EXTENDED, "Extended" },
4931 { FF_PROFILE_H264_HIGH, "High" },
4932 { FF_PROFILE_H264_HIGH_10, "High 10" },
4933 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
4934 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
4935 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
4936 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
4937 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
4938 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
4939 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
4940 { FF_PROFILE_UNKNOWN },
4943 AVCodec ff_h264_decoder = {
4945 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
4946 .type = AVMEDIA_TYPE_VIDEO,
4947 .id = AV_CODEC_ID_H264,
4948 .priv_data_size = sizeof(H264Context),
4949 .init = ff_h264_decode_init,
4950 .close = h264_decode_end,
4951 .decode = decode_frame,
4952 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
4953 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
4954 CODEC_CAP_FRAME_THREADS,
4956 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
4957 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
4958 .profiles = NULL_IF_CONFIG_SMALL(profiles),