2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/avassert.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/opt.h"
35 #include "cabac_functions.h"
37 #include "error_resilience.h"
39 #include "mpegvideo.h"
42 #include "h264chroma.h"
43 #include "h264_mvpred.h"
46 #include "rectangle.h"
49 #include "vdpau_internal.h"
53 static void flush_change(H264Context *h);
55 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
57 static const uint8_t rem6[QP_MAX_NUM + 1] = {
58 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
59 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
60 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
61 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
65 static const uint8_t div6[QP_MAX_NUM + 1] = {
66 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
67 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
68 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
69 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
73 static const uint8_t field_scan[16+1] = {
74 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
75 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
76 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
77 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
80 static const uint8_t field_scan8x8[64+1] = {
81 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
82 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
83 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
84 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
85 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
86 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
87 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
88 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
89 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
90 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
91 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
92 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
93 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
94 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
95 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
96 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
99 static const uint8_t field_scan8x8_cavlc[64+1] = {
100 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
101 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
102 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
103 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
104 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
105 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
106 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
107 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
108 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
109 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
110 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
111 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
112 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
113 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
114 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
115 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
118 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
119 static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
120 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
121 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
122 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
123 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
124 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
125 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
126 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
127 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
128 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
129 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
130 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
131 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
132 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
133 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
134 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
135 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
138 static const uint8_t dequant4_coeff_init[6][3] = {
147 static const uint8_t dequant8_coeff_init_scan[16] = {
148 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
151 static const uint8_t dequant8_coeff_init[6][6] = {
152 { 20, 18, 32, 19, 25, 24 },
153 { 22, 19, 35, 21, 28, 26 },
154 { 26, 23, 42, 24, 33, 31 },
155 { 28, 25, 45, 26, 35, 33 },
156 { 32, 28, 51, 30, 40, 38 },
157 { 36, 32, 58, 34, 46, 43 },
160 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
161 #if CONFIG_H264_DXVA2_HWACCEL
162 AV_PIX_FMT_DXVA2_VLD,
164 #if CONFIG_H264_VAAPI_HWACCEL
165 AV_PIX_FMT_VAAPI_VLD,
167 #if CONFIG_H264_VDA_HWACCEL
170 #if CONFIG_H264_VDPAU_HWACCEL
177 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
178 #if CONFIG_H264_DXVA2_HWACCEL
179 AV_PIX_FMT_DXVA2_VLD,
181 #if CONFIG_H264_VAAPI_HWACCEL
182 AV_PIX_FMT_VAAPI_VLD,
184 #if CONFIG_H264_VDA_HWACCEL
187 #if CONFIG_H264_VDPAU_HWACCEL
194 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
196 H264Context *h = avctx->priv_data;
197 return h ? h->sps.num_reorder_frames : 0;
200 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
202 int mb_x, int mb_y, int mb_intra, int mb_skipped)
204 H264Context *h = opaque;
208 h->mb_xy = mb_x + mb_y * h->mb_stride;
209 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
210 av_assert1(ref >= 0);
211 /* FIXME: It is possible albeit uncommon that slice references
212 * differ between slices. We take the easy approach and ignore
213 * it for now. If this turns out to have any relevance in
214 * practice then correct remapping should be added. */
215 if (ref >= h->ref_count[0])
217 if (!h->ref_list[0][ref].f.data[0]) {
218 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
221 if ((h->ref_list[0][ref].reference&3) != 3) {
222 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
225 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
227 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
228 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
229 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
231 h->mb_field_decoding_flag = 0;
232 ff_h264_hl_decode_mb(h);
235 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
237 AVCodecContext *avctx = h->avctx;
238 Picture *cur = &h->cur_pic;
239 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
240 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
241 int vshift = desc->log2_chroma_h;
242 const int field_pic = h->picture_structure != PICT_FRAME;
248 height = FFMIN(height, avctx->height - y);
250 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
253 if (avctx->draw_horiz_band) {
255 int offset[AV_NUM_DATA_POINTERS];
258 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
259 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
266 offset[0] = y * src->linesize[0];
268 offset[2] = (y >> vshift) * src->linesize[1];
269 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
274 avctx->draw_horiz_band(avctx, src, offset,
275 y, h->picture_structure, height);
279 static void unref_picture(H264Context *h, Picture *pic)
281 int off = offsetof(Picture, tf) + sizeof(pic->tf);
287 ff_thread_release_buffer(h->avctx, &pic->tf);
288 av_buffer_unref(&pic->hwaccel_priv_buf);
290 av_buffer_unref(&pic->qscale_table_buf);
291 av_buffer_unref(&pic->mb_type_buf);
292 for (i = 0; i < 2; i++) {
293 av_buffer_unref(&pic->motion_val_buf[i]);
294 av_buffer_unref(&pic->ref_index_buf[i]);
297 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
300 static void release_unused_pictures(H264Context *h, int remove_current)
304 /* release non reference frames */
305 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
306 if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
307 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
308 unref_picture(h, &h->DPB[i]);
313 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
317 av_assert0(!dst->f.buf[0]);
318 av_assert0(src->f.buf[0]);
322 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
326 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
327 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
328 if (!dst->qscale_table_buf || !dst->mb_type_buf)
330 dst->qscale_table = src->qscale_table;
331 dst->mb_type = src->mb_type;
333 for (i = 0; i < 2; i++) {
334 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
335 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
336 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
338 dst->motion_val[i] = src->motion_val[i];
339 dst->ref_index[i] = src->ref_index[i];
342 if (src->hwaccel_picture_private) {
343 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
344 if (!dst->hwaccel_priv_buf)
346 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
349 for (i = 0; i < 2; i++)
350 dst->field_poc[i] = src->field_poc[i];
352 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
353 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
356 dst->frame_num = src->frame_num;
357 dst->mmco_reset = src->mmco_reset;
358 dst->pic_id = src->pic_id;
359 dst->long_ref = src->long_ref;
360 dst->mbaff = src->mbaff;
361 dst->field_picture = src->field_picture;
362 dst->needs_realloc = src->needs_realloc;
363 dst->reference = src->reference;
364 dst->crop = src->crop;
365 dst->crop_left = src->crop_left;
366 dst->crop_top = src->crop_top;
367 dst->recovered = src->recovered;
371 unref_picture(h, dst);
375 static int alloc_scratch_buffers(H264Context *h, int linesize)
377 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
379 if (h->bipred_scratchpad)
382 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
383 // edge emu needs blocksize + filter length - 1
384 // (= 21x21 for h264)
385 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
386 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
388 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
389 av_freep(&h->bipred_scratchpad);
390 av_freep(&h->edge_emu_buffer);
391 av_freep(&h->me.scratchpad);
392 return AVERROR(ENOMEM);
395 h->me.temp = h->me.scratchpad;
400 static int init_table_pools(H264Context *h)
402 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
403 const int mb_array_size = h->mb_stride * h->mb_height;
404 const int b4_stride = h->mb_width * 4 + 1;
405 const int b4_array_size = b4_stride * h->mb_height * 4;
407 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
409 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
410 sizeof(uint32_t), av_buffer_allocz);
411 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
412 sizeof(int16_t), av_buffer_allocz);
413 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
415 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
416 !h->ref_index_pool) {
417 av_buffer_pool_uninit(&h->qscale_table_pool);
418 av_buffer_pool_uninit(&h->mb_type_pool);
419 av_buffer_pool_uninit(&h->motion_val_pool);
420 av_buffer_pool_uninit(&h->ref_index_pool);
421 return AVERROR(ENOMEM);
427 static int alloc_picture(H264Context *h, Picture *pic)
431 av_assert0(!pic->f.data[0]);
434 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
435 AV_GET_BUFFER_FLAG_REF : 0);
439 h->linesize = pic->f.linesize[0];
440 h->uvlinesize = pic->f.linesize[1];
441 pic->crop = h->sps.crop;
442 pic->crop_top = h->sps.crop_top;
443 pic->crop_left= h->sps.crop_left;
445 if (h->avctx->hwaccel) {
446 const AVHWAccel *hwaccel = h->avctx->hwaccel;
447 av_assert0(!pic->hwaccel_picture_private);
448 if (hwaccel->priv_data_size) {
449 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
450 if (!pic->hwaccel_priv_buf)
451 return AVERROR(ENOMEM);
452 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
456 if (!h->qscale_table_pool) {
457 ret = init_table_pools(h);
462 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
463 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
464 if (!pic->qscale_table_buf || !pic->mb_type_buf)
467 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
468 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
470 for (i = 0; i < 2; i++) {
471 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
472 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
473 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
476 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
477 pic->ref_index[i] = pic->ref_index_buf[i]->data;
482 unref_picture(h, pic);
483 return (ret < 0) ? ret : AVERROR(ENOMEM);
486 static inline int pic_is_unused(H264Context *h, Picture *pic)
490 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
495 static int find_unused_picture(H264Context *h)
499 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
500 if (pic_is_unused(h, &h->DPB[i]))
503 if (i == MAX_PICTURE_COUNT)
504 return AVERROR_INVALIDDATA;
506 if (h->DPB[i].needs_realloc) {
507 h->DPB[i].needs_realloc = 0;
508 unref_picture(h, &h->DPB[i]);
515 * Check if the top & left blocks are available if needed and
516 * change the dc mode so it only uses the available blocks.
518 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
520 static const int8_t top[12] = {
521 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
523 static const int8_t left[12] = {
524 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
528 if (!(h->top_samples_available & 0x8000)) {
529 for (i = 0; i < 4; i++) {
530 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
532 av_log(h->avctx, AV_LOG_ERROR,
533 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
534 status, h->mb_x, h->mb_y);
535 return AVERROR_INVALIDDATA;
537 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
542 if ((h->left_samples_available & 0x8888) != 0x8888) {
543 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
544 for (i = 0; i < 4; i++)
545 if (!(h->left_samples_available & mask[i])) {
546 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
548 av_log(h->avctx, AV_LOG_ERROR,
549 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
550 status, h->mb_x, h->mb_y);
551 return AVERROR_INVALIDDATA;
553 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
559 } // FIXME cleanup like ff_h264_check_intra_pred_mode
562 * Check if the top & left blocks are available if needed and
563 * change the dc mode so it only uses the available blocks.
565 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
567 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
568 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
571 av_log(h->avctx, AV_LOG_ERROR,
572 "out of range intra chroma pred mode at %d %d\n",
574 return AVERROR_INVALIDDATA;
577 if (!(h->top_samples_available & 0x8000)) {
580 av_log(h->avctx, AV_LOG_ERROR,
581 "top block unavailable for requested intra mode at %d %d\n",
583 return AVERROR_INVALIDDATA;
587 if ((h->left_samples_available & 0x8080) != 0x8080) {
589 if (is_chroma && (h->left_samples_available & 0x8080)) {
590 // mad cow disease mode, aka MBAFF + constrained_intra_pred
591 mode = ALZHEIMER_DC_L0T_PRED8x8 +
592 (!(h->left_samples_available & 0x8000)) +
593 2 * (mode == DC_128_PRED8x8);
596 av_log(h->avctx, AV_LOG_ERROR,
597 "left block unavailable for requested intra mode at %d %d\n",
599 return AVERROR_INVALIDDATA;
606 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
607 int *dst_length, int *consumed, int length)
613 // src[0]&0x80; // forbidden bit
614 h->nal_ref_idc = src[0] >> 5;
615 h->nal_unit_type = src[0] & 0x1F;
620 #define STARTCODE_TEST \
621 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
622 if (src[i + 2] != 3) { \
623 /* startcode, so we must be past the end */ \
629 #if HAVE_FAST_UNALIGNED
630 #define FIND_FIRST_ZERO \
631 if (i > 0 && !src[i]) \
637 for (i = 0; i + 1 < length; i += 9) {
638 if (!((~AV_RN64A(src + i) &
639 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
640 0x8000800080008080ULL))
647 for (i = 0; i + 1 < length; i += 5) {
648 if (!((~AV_RN32A(src + i) &
649 (AV_RN32A(src + i) - 0x01000101U)) &
658 for (i = 0; i + 1 < length; i += 2) {
661 if (i > 0 && src[i - 1] == 0)
667 // use second escape buffer for inter data
668 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
670 si = h->rbsp_buffer_size[bufidx];
671 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
672 dst = h->rbsp_buffer[bufidx];
677 if(i>=length-1){ //no escaped 0
679 *consumed= length+1; //+1 for the header
680 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
683 memcpy(dst, src, length);
690 while (si + 2 < length) {
691 // remove escapes (very rare 1:2^22)
692 if (src[si + 2] > 3) {
693 dst[di++] = src[si++];
694 dst[di++] = src[si++];
695 } else if (src[si] == 0 && src[si + 1] == 0) {
696 if (src[si + 2] == 3) { // escape
701 } else // next start code
705 dst[di++] = src[si++];
708 dst[di++] = src[si++];
711 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
714 *consumed = si + 1; // +1 for the header
715 /* FIXME store exact number of bits in the getbitcontext
716 * (it is needed for decoding) */
721 * Identify the exact end of the bitstream
722 * @return the length of the trailing, or 0 if damaged
724 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
729 tprintf(h->avctx, "rbsp trailing %X\n", v);
731 for (r = 1; r < 9; r++) {
739 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
740 int height, int y_offset, int list)
742 int raw_my = h->mv_cache[list][scan8[n]][1];
743 int filter_height_down = (raw_my & 3) ? 3 : 0;
744 int full_my = (raw_my >> 2) + y_offset;
745 int bottom = full_my + filter_height_down + height;
747 av_assert2(height >= 0);
749 return FFMAX(0, bottom);
752 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
753 int height, int y_offset, int list0,
754 int list1, int *nrefs)
758 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
761 int ref_n = h->ref_cache[0][scan8[n]];
762 Picture *ref = &h->ref_list[0][ref_n];
764 // Error resilience puts the current picture in the ref list.
765 // Don't try to wait on these as it will cause a deadlock.
766 // Fields can wait on each other, though.
767 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
768 (ref->reference & 3) != h->picture_structure) {
769 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
770 if (refs[0][ref_n] < 0)
772 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
777 int ref_n = h->ref_cache[1][scan8[n]];
778 Picture *ref = &h->ref_list[1][ref_n];
780 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
781 (ref->reference & 3) != h->picture_structure) {
782 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
783 if (refs[1][ref_n] < 0)
785 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
791 * Wait until all reference frames are available for MC operations.
793 * @param h the H264 context
795 static void await_references(H264Context *h)
797 const int mb_xy = h->mb_xy;
798 const int mb_type = h->cur_pic.mb_type[mb_xy];
800 int nrefs[2] = { 0 };
803 memset(refs, -1, sizeof(refs));
805 if (IS_16X16(mb_type)) {
806 get_lowest_part_y(h, refs, 0, 16, 0,
807 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
808 } else if (IS_16X8(mb_type)) {
809 get_lowest_part_y(h, refs, 0, 8, 0,
810 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
811 get_lowest_part_y(h, refs, 8, 8, 8,
812 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
813 } else if (IS_8X16(mb_type)) {
814 get_lowest_part_y(h, refs, 0, 16, 0,
815 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
816 get_lowest_part_y(h, refs, 4, 16, 0,
817 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
821 av_assert2(IS_8X8(mb_type));
823 for (i = 0; i < 4; i++) {
824 const int sub_mb_type = h->sub_mb_type[i];
826 int y_offset = (i & 2) << 2;
828 if (IS_SUB_8X8(sub_mb_type)) {
829 get_lowest_part_y(h, refs, n, 8, y_offset,
830 IS_DIR(sub_mb_type, 0, 0),
831 IS_DIR(sub_mb_type, 0, 1),
833 } else if (IS_SUB_8X4(sub_mb_type)) {
834 get_lowest_part_y(h, refs, n, 4, y_offset,
835 IS_DIR(sub_mb_type, 0, 0),
836 IS_DIR(sub_mb_type, 0, 1),
838 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
839 IS_DIR(sub_mb_type, 0, 0),
840 IS_DIR(sub_mb_type, 0, 1),
842 } else if (IS_SUB_4X8(sub_mb_type)) {
843 get_lowest_part_y(h, refs, n, 8, y_offset,
844 IS_DIR(sub_mb_type, 0, 0),
845 IS_DIR(sub_mb_type, 0, 1),
847 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
848 IS_DIR(sub_mb_type, 0, 0),
849 IS_DIR(sub_mb_type, 0, 1),
853 av_assert2(IS_SUB_4X4(sub_mb_type));
854 for (j = 0; j < 4; j++) {
855 int sub_y_offset = y_offset + 2 * (j & 2);
856 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
857 IS_DIR(sub_mb_type, 0, 0),
858 IS_DIR(sub_mb_type, 0, 1),
865 for (list = h->list_count - 1; list >= 0; list--)
866 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
867 int row = refs[list][ref];
869 Picture *ref_pic = &h->ref_list[list][ref];
870 int ref_field = ref_pic->reference - 1;
871 int ref_field_picture = ref_pic->field_picture;
872 int pic_height = 16 * h->mb_height >> ref_field_picture;
877 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
878 ff_thread_await_progress(&ref_pic->tf,
879 FFMIN((row >> 1) - !(row & 1),
882 ff_thread_await_progress(&ref_pic->tf,
883 FFMIN((row >> 1), pic_height - 1),
885 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
886 ff_thread_await_progress(&ref_pic->tf,
887 FFMIN(row * 2 + ref_field,
890 } else if (FIELD_PICTURE(h)) {
891 ff_thread_await_progress(&ref_pic->tf,
892 FFMIN(row, pic_height - 1),
895 ff_thread_await_progress(&ref_pic->tf,
896 FFMIN(row, pic_height - 1),
903 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
904 int n, int square, int height,
906 uint8_t *dest_y, uint8_t *dest_cb,
908 int src_x_offset, int src_y_offset,
909 qpel_mc_func *qpix_op,
910 h264_chroma_mc_func chroma_op,
911 int pixel_shift, int chroma_idc)
913 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
914 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
915 const int luma_xy = (mx & 3) + ((my & 3) << 2);
916 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
917 uint8_t *src_y = pic->f.data[0] + offset;
918 uint8_t *src_cb, *src_cr;
920 int extra_height = 0;
922 const int full_mx = mx >> 2;
923 const int full_my = my >> 2;
924 const int pic_width = 16 * h->mb_width;
925 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
933 if (full_mx < 0 - extra_width ||
934 full_my < 0 - extra_height ||
935 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
936 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
937 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
938 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
939 h->mb_linesize, h->mb_linesize,
940 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
941 full_my - 2, pic_width, pic_height);
942 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
946 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
948 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
950 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
953 if (chroma_idc == 3 /* yuv444 */) {
954 src_cb = pic->f.data[1] + offset;
956 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
957 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
958 h->mb_linesize, h->mb_linesize,
959 16 + 5, 16 + 5 /*FIXME*/,
960 full_mx - 2, full_my - 2,
961 pic_width, pic_height);
962 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
964 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
966 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
968 src_cr = pic->f.data[2] + offset;
970 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
971 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
972 h->mb_linesize, h->mb_linesize,
973 16 + 5, 16 + 5 /*FIXME*/,
974 full_mx - 2, full_my - 2,
975 pic_width, pic_height);
976 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
978 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
980 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
984 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
985 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
986 // chroma offset when predicting from a field of opposite parity
987 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
988 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
991 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
992 (my >> ysh) * h->mb_uvlinesize;
993 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
994 (my >> ysh) * h->mb_uvlinesize;
997 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
998 h->mb_uvlinesize, h->mb_uvlinesize,
999 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1000 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1001 src_cb = h->edge_emu_buffer;
1003 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
1004 height >> (chroma_idc == 1 /* yuv420 */),
1005 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1008 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
1009 h->mb_uvlinesize, h->mb_uvlinesize,
1010 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1011 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1012 src_cr = h->edge_emu_buffer;
1014 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
1015 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1018 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
1019 int height, int delta,
1020 uint8_t *dest_y, uint8_t *dest_cb,
1022 int x_offset, int y_offset,
1023 qpel_mc_func *qpix_put,
1024 h264_chroma_mc_func chroma_put,
1025 qpel_mc_func *qpix_avg,
1026 h264_chroma_mc_func chroma_avg,
1027 int list0, int list1,
1028 int pixel_shift, int chroma_idc)
1030 qpel_mc_func *qpix_op = qpix_put;
1031 h264_chroma_mc_func chroma_op = chroma_put;
1033 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1034 if (chroma_idc == 3 /* yuv444 */) {
1035 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1036 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1037 } else if (chroma_idc == 2 /* yuv422 */) {
1038 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1039 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1040 } else { /* yuv420 */
1041 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1042 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1044 x_offset += 8 * h->mb_x;
1045 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1048 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1049 mc_dir_part(h, ref, n, square, height, delta, 0,
1050 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1051 qpix_op, chroma_op, pixel_shift, chroma_idc);
1054 chroma_op = chroma_avg;
1058 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1059 mc_dir_part(h, ref, n, square, height, delta, 1,
1060 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1061 qpix_op, chroma_op, pixel_shift, chroma_idc);
1065 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1066 int height, int delta,
1067 uint8_t *dest_y, uint8_t *dest_cb,
1069 int x_offset, int y_offset,
1070 qpel_mc_func *qpix_put,
1071 h264_chroma_mc_func chroma_put,
1072 h264_weight_func luma_weight_op,
1073 h264_weight_func chroma_weight_op,
1074 h264_biweight_func luma_weight_avg,
1075 h264_biweight_func chroma_weight_avg,
1076 int list0, int list1,
1077 int pixel_shift, int chroma_idc)
1081 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1082 if (chroma_idc == 3 /* yuv444 */) {
1083 chroma_height = height;
1084 chroma_weight_avg = luma_weight_avg;
1085 chroma_weight_op = luma_weight_op;
1086 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1087 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1088 } else if (chroma_idc == 2 /* yuv422 */) {
1089 chroma_height = height;
1090 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1091 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1092 } else { /* yuv420 */
1093 chroma_height = height >> 1;
1094 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1095 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1097 x_offset += 8 * h->mb_x;
1098 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1100 if (list0 && list1) {
1101 /* don't optimize for luma-only case, since B-frames usually
1102 * use implicit weights => chroma too. */
1103 uint8_t *tmp_cb = h->bipred_scratchpad;
1104 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1105 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1106 int refn0 = h->ref_cache[0][scan8[n]];
1107 int refn1 = h->ref_cache[1][scan8[n]];
1109 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1110 dest_y, dest_cb, dest_cr,
1111 x_offset, y_offset, qpix_put, chroma_put,
1112 pixel_shift, chroma_idc);
1113 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1114 tmp_y, tmp_cb, tmp_cr,
1115 x_offset, y_offset, qpix_put, chroma_put,
1116 pixel_shift, chroma_idc);
1118 if (h->use_weight == 2) {
1119 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1120 int weight1 = 64 - weight0;
1121 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1122 height, 5, weight0, weight1, 0);
1123 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1124 chroma_height, 5, weight0, weight1, 0);
1125 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1126 chroma_height, 5, weight0, weight1, 0);
1128 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1129 h->luma_log2_weight_denom,
1130 h->luma_weight[refn0][0][0],
1131 h->luma_weight[refn1][1][0],
1132 h->luma_weight[refn0][0][1] +
1133 h->luma_weight[refn1][1][1]);
1134 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1135 h->chroma_log2_weight_denom,
1136 h->chroma_weight[refn0][0][0][0],
1137 h->chroma_weight[refn1][1][0][0],
1138 h->chroma_weight[refn0][0][0][1] +
1139 h->chroma_weight[refn1][1][0][1]);
1140 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1141 h->chroma_log2_weight_denom,
1142 h->chroma_weight[refn0][0][1][0],
1143 h->chroma_weight[refn1][1][1][0],
1144 h->chroma_weight[refn0][0][1][1] +
1145 h->chroma_weight[refn1][1][1][1]);
1148 int list = list1 ? 1 : 0;
1149 int refn = h->ref_cache[list][scan8[n]];
1150 Picture *ref = &h->ref_list[list][refn];
1151 mc_dir_part(h, ref, n, square, height, delta, list,
1152 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1153 qpix_put, chroma_put, pixel_shift, chroma_idc);
1155 luma_weight_op(dest_y, h->mb_linesize, height,
1156 h->luma_log2_weight_denom,
1157 h->luma_weight[refn][list][0],
1158 h->luma_weight[refn][list][1]);
1159 if (h->use_weight_chroma) {
1160 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1161 h->chroma_log2_weight_denom,
1162 h->chroma_weight[refn][list][0][0],
1163 h->chroma_weight[refn][list][0][1]);
1164 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1165 h->chroma_log2_weight_denom,
1166 h->chroma_weight[refn][list][1][0],
1167 h->chroma_weight[refn][list][1][1]);
1172 static av_always_inline void prefetch_motion(H264Context *h, int list,
1173 int pixel_shift, int chroma_idc)
1175 /* fetch pixels for estimated mv 4 macroblocks ahead
1176 * optimized for 64byte cache lines */
1177 const int refn = h->ref_cache[list][scan8[0]];
1179 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1180 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1181 uint8_t **src = h->ref_list[list][refn].f.data;
1182 int off = (mx << pixel_shift) +
1183 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1184 (64 << pixel_shift);
1185 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1186 if (chroma_idc == 3 /* yuv444 */) {
1187 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1188 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1190 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
1191 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1196 static void free_tables(H264Context *h, int free_rbsp)
1201 av_freep(&h->intra4x4_pred_mode);
1202 av_freep(&h->chroma_pred_mode_table);
1203 av_freep(&h->cbp_table);
1204 av_freep(&h->mvd_table[0]);
1205 av_freep(&h->mvd_table[1]);
1206 av_freep(&h->direct_table);
1207 av_freep(&h->non_zero_count);
1208 av_freep(&h->slice_table_base);
1209 h->slice_table = NULL;
1210 av_freep(&h->list_counts);
1212 av_freep(&h->mb2b_xy);
1213 av_freep(&h->mb2br_xy);
1215 for (i = 0; i < 3; i++)
1216 av_freep(&h->visualization_buffer[i]);
1218 av_buffer_pool_uninit(&h->qscale_table_pool);
1219 av_buffer_pool_uninit(&h->mb_type_pool);
1220 av_buffer_pool_uninit(&h->motion_val_pool);
1221 av_buffer_pool_uninit(&h->ref_index_pool);
1223 if (free_rbsp && h->DPB) {
1224 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1225 unref_picture(h, &h->DPB[i]);
1227 } else if (h->DPB) {
1228 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1229 h->DPB[i].needs_realloc = 1;
1232 h->cur_pic_ptr = NULL;
1234 for (i = 0; i < MAX_THREADS; i++) {
1235 hx = h->thread_context[i];
1238 av_freep(&hx->top_borders[1]);
1239 av_freep(&hx->top_borders[0]);
1240 av_freep(&hx->bipred_scratchpad);
1241 av_freep(&hx->edge_emu_buffer);
1242 av_freep(&hx->dc_val_base);
1243 av_freep(&hx->me.scratchpad);
1244 av_freep(&hx->er.mb_index2xy);
1245 av_freep(&hx->er.error_status_table);
1246 av_freep(&hx->er.er_temp_buffer);
1247 av_freep(&hx->er.mbintra_table);
1248 av_freep(&hx->er.mbskip_table);
1251 av_freep(&hx->rbsp_buffer[1]);
1252 av_freep(&hx->rbsp_buffer[0]);
1253 hx->rbsp_buffer_size[0] = 0;
1254 hx->rbsp_buffer_size[1] = 0;
1257 av_freep(&h->thread_context[i]);
1261 static void init_dequant8_coeff_table(H264Context *h)
1264 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1266 for (i = 0; i < 6; i++) {
1267 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1268 for (j = 0; j < i; j++)
1269 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1270 64 * sizeof(uint8_t))) {
1271 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1277 for (q = 0; q < max_qp + 1; q++) {
1278 int shift = div6[q];
1280 for (x = 0; x < 64; x++)
1281 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1282 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1283 h->pps.scaling_matrix8[i][x]) << shift;
1288 static void init_dequant4_coeff_table(H264Context *h)
1291 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1292 for (i = 0; i < 6; i++) {
1293 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1294 for (j = 0; j < i; j++)
1295 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1296 16 * sizeof(uint8_t))) {
1297 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1303 for (q = 0; q < max_qp + 1; q++) {
1304 int shift = div6[q] + 2;
1306 for (x = 0; x < 16; x++)
1307 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1308 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1309 h->pps.scaling_matrix4[i][x]) << shift;
1314 static void init_dequant_tables(H264Context *h)
1317 init_dequant4_coeff_table(h);
1318 if (h->pps.transform_8x8_mode)
1319 init_dequant8_coeff_table(h);
1320 if (h->sps.transform_bypass) {
1321 for (i = 0; i < 6; i++)
1322 for (x = 0; x < 16; x++)
1323 h->dequant4_coeff[i][0][x] = 1 << 6;
1324 if (h->pps.transform_8x8_mode)
1325 for (i = 0; i < 6; i++)
1326 for (x = 0; x < 64; x++)
1327 h->dequant8_coeff[i][0][x] = 1 << 6;
1331 int ff_h264_alloc_tables(H264Context *h)
1333 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1334 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1337 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1338 row_mb_num * 8 * sizeof(uint8_t), fail)
1339 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1340 big_mb_num * 48 * sizeof(uint8_t), fail)
1341 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1342 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1343 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1344 big_mb_num * sizeof(uint16_t), fail)
1345 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1346 big_mb_num * sizeof(uint8_t), fail)
1347 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1348 16 * row_mb_num * sizeof(uint8_t), fail);
1349 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1350 16 * row_mb_num * sizeof(uint8_t), fail);
1351 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1352 4 * big_mb_num * sizeof(uint8_t), fail);
1353 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1354 big_mb_num * sizeof(uint8_t), fail)
1356 memset(h->slice_table_base, -1,
1357 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1358 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1360 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1361 big_mb_num * sizeof(uint32_t), fail);
1362 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1363 big_mb_num * sizeof(uint32_t), fail);
1364 for (y = 0; y < h->mb_height; y++)
1365 for (x = 0; x < h->mb_width; x++) {
1366 const int mb_xy = x + y * h->mb_stride;
1367 const int b_xy = 4 * x + 4 * y * h->b_stride;
1369 h->mb2b_xy[mb_xy] = b_xy;
1370 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1373 if (!h->dequant4_coeff[0])
1374 init_dequant_tables(h);
1377 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1379 return AVERROR(ENOMEM);
1380 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1381 avcodec_get_frame_defaults(&h->DPB[i].f);
1382 avcodec_get_frame_defaults(&h->cur_pic.f);
1389 return AVERROR(ENOMEM);
1393 * Mimic alloc_tables(), but for every context thread.
1395 static void clone_tables(H264Context *dst, H264Context *src, int i)
1397 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1398 dst->non_zero_count = src->non_zero_count;
1399 dst->slice_table = src->slice_table;
1400 dst->cbp_table = src->cbp_table;
1401 dst->mb2b_xy = src->mb2b_xy;
1402 dst->mb2br_xy = src->mb2br_xy;
1403 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1404 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1405 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1406 dst->direct_table = src->direct_table;
1407 dst->list_counts = src->list_counts;
1408 dst->DPB = src->DPB;
1409 dst->cur_pic_ptr = src->cur_pic_ptr;
1410 dst->cur_pic = src->cur_pic;
1411 dst->bipred_scratchpad = NULL;
1412 dst->edge_emu_buffer = NULL;
1413 dst->me.scratchpad = NULL;
1414 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1415 src->sps.chroma_format_idc);
1420 * Allocate buffers which are not shared amongst multiple threads.
1422 static int context_init(H264Context *h)
1424 ERContext *er = &h->er;
1425 int mb_array_size = h->mb_height * h->mb_stride;
1426 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1427 int c_size = h->mb_stride * (h->mb_height + 1);
1428 int yc_size = y_size + 2 * c_size;
1431 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1432 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1433 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1434 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1436 h->ref_cache[0][scan8[5] + 1] =
1437 h->ref_cache[0][scan8[7] + 1] =
1438 h->ref_cache[0][scan8[13] + 1] =
1439 h->ref_cache[1][scan8[5] + 1] =
1440 h->ref_cache[1][scan8[7] + 1] =
1441 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1443 if (CONFIG_ERROR_RESILIENCE) {
1445 er->avctx = h->avctx;
1447 er->decode_mb = h264_er_decode_mb;
1449 er->quarter_sample = 1;
1451 er->mb_num = h->mb_num;
1452 er->mb_width = h->mb_width;
1453 er->mb_height = h->mb_height;
1454 er->mb_stride = h->mb_stride;
1455 er->b8_stride = h->mb_width * 2 + 1;
1457 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1458 fail); // error ressilience code looks cleaner with this
1459 for (y = 0; y < h->mb_height; y++)
1460 for (x = 0; x < h->mb_width; x++)
1461 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1463 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1464 h->mb_stride + h->mb_width;
1466 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1467 mb_array_size * sizeof(uint8_t), fail);
1469 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1470 memset(er->mbintra_table, 1, mb_array_size);
1472 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1474 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1477 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1478 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1479 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1480 er->dc_val[2] = er->dc_val[1] + c_size;
1481 for (i = 0; i < yc_size; i++)
1482 h->dc_val_base[i] = 1024;
1488 return AVERROR(ENOMEM); // free_tables will clean up for us
1491 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1492 int parse_extradata);
1494 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1496 AVCodecContext *avctx = h->avctx;
1499 if (!buf || size <= 0)
1503 int i, cnt, nalsize;
1504 const unsigned char *p = buf;
1509 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1510 return AVERROR_INVALIDDATA;
1512 /* sps and pps in the avcC always have length coded with 2 bytes,
1513 * so put a fake nal_length_size = 2 while parsing them */
1514 h->nal_length_size = 2;
1515 // Decode sps from avcC
1516 cnt = *(p + 5) & 0x1f; // Number of sps
1518 for (i = 0; i < cnt; i++) {
1519 nalsize = AV_RB16(p) + 2;
1520 if(nalsize > size - (p-buf))
1521 return AVERROR_INVALIDDATA;
1522 ret = decode_nal_units(h, p, nalsize, 1);
1524 av_log(avctx, AV_LOG_ERROR,
1525 "Decoding sps %d from avcC failed\n", i);
1530 // Decode pps from avcC
1531 cnt = *(p++); // Number of pps
1532 for (i = 0; i < cnt; i++) {
1533 nalsize = AV_RB16(p) + 2;
1534 if(nalsize > size - (p-buf))
1535 return AVERROR_INVALIDDATA;
1536 ret = decode_nal_units(h, p, nalsize, 1);
1538 av_log(avctx, AV_LOG_ERROR,
1539 "Decoding pps %d from avcC failed\n", i);
1544 // Now store right nal length size, that will be used to parse all other nals
1545 h->nal_length_size = (buf[4] & 0x03) + 1;
1548 ret = decode_nal_units(h, buf, size, 1);
1555 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1557 H264Context *h = avctx->priv_data;
1563 h->bit_depth_luma = 8;
1564 h->chroma_format_idc = 1;
1566 h->avctx->bits_per_raw_sample = 8;
1567 h->cur_chroma_format_idc = 1;
1569 ff_h264dsp_init(&h->h264dsp, 8, 1);
1570 av_assert0(h->sps.bit_depth_chroma == 0);
1571 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1572 ff_h264qpel_init(&h->h264qpel, 8);
1573 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1575 h->dequant_coeff_pps = -1;
1576 h->current_sps_id = -1;
1578 /* needed so that IDCT permutation is known early */
1579 if (CONFIG_ERROR_RESILIENCE)
1580 ff_dsputil_init(&h->dsp, h->avctx);
1581 ff_videodsp_init(&h->vdsp, 8);
1583 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1584 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1586 h->picture_structure = PICT_FRAME;
1587 h->slice_context_count = 1;
1588 h->workaround_bugs = avctx->workaround_bugs;
1589 h->flags = avctx->flags;
1592 // s->decode_mb = ff_h263_decode_mb;
1593 if (!avctx->has_b_frames)
1596 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1598 ff_h264_decode_init_vlc();
1600 ff_init_cabac_states();
1603 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1605 h->thread_context[0] = h;
1606 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1607 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1608 h->last_pocs[i] = INT_MIN;
1609 h->prev_poc_msb = 1 << 16;
1610 h->prev_frame_num = -1;
1612 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
1613 ff_h264_reset_sei(h);
1614 if (avctx->codec_id == AV_CODEC_ID_H264) {
1615 if (avctx->ticks_per_frame == 1) {
1616 if(h->avctx->time_base.den < INT_MAX/2) {
1617 h->avctx->time_base.den *= 2;
1619 h->avctx->time_base.num /= 2;
1621 avctx->ticks_per_frame = 2;
1624 if (avctx->extradata_size > 0 && avctx->extradata) {
1625 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
1627 ff_h264_free_context(h);
1632 if (h->sps.bitstream_restriction_flag &&
1633 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1634 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1638 avctx->internal->allocate_progress = 1;
1645 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1646 #undef REBASE_PICTURE
1647 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1648 ((pic && pic >= old_ctx->DPB && \
1649 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1650 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1652 static void copy_picture_range(Picture **to, Picture **from, int count,
1653 H264Context *new_base,
1654 H264Context *old_base)
1658 for (i = 0; i < count; i++) {
1659 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1660 IN_RANGE(from[i], old_base->DPB,
1661 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1663 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1667 static int copy_parameter_set(void **to, void **from, int count, int size)
1671 for (i = 0; i < count; i++) {
1672 if (to[i] && !from[i]) {
1674 } else if (from[i] && !to[i]) {
1675 to[i] = av_malloc(size);
1677 return AVERROR(ENOMEM);
1681 memcpy(to[i], from[i], size);
1687 static int decode_init_thread_copy(AVCodecContext *avctx)
1689 H264Context *h = avctx->priv_data;
1691 if (!avctx->internal->is_copy)
1693 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1694 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1696 h->rbsp_buffer[0] = NULL;
1697 h->rbsp_buffer[1] = NULL;
1698 h->rbsp_buffer_size[0] = 0;
1699 h->rbsp_buffer_size[1] = 0;
1700 h->context_initialized = 0;
1705 #define copy_fields(to, from, start_field, end_field) \
1706 memcpy(&to->start_field, &from->start_field, \
1707 (char *)&to->end_field - (char *)&to->start_field)
1709 static int h264_slice_header_init(H264Context *, int);
1711 static int h264_set_parameter_from_sps(H264Context *h);
1713 static int decode_update_thread_context(AVCodecContext *dst,
1714 const AVCodecContext *src)
1716 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1717 int inited = h->context_initialized, err = 0;
1718 int context_reinitialized = 0;
1725 (h->width != h1->width ||
1726 h->height != h1->height ||
1727 h->mb_width != h1->mb_width ||
1728 h->mb_height != h1->mb_height ||
1729 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1730 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1731 h->sps.colorspace != h1->sps.colorspace)) {
1733 /* set bits_per_raw_sample to the previous value. the check for changed
1734 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1735 * the current value */
1736 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1738 av_freep(&h->bipred_scratchpad);
1740 h->width = h1->width;
1741 h->height = h1->height;
1742 h->mb_height = h1->mb_height;
1743 h->mb_width = h1->mb_width;
1744 h->mb_num = h1->mb_num;
1745 h->mb_stride = h1->mb_stride;
1746 h->b_stride = h1->b_stride;
1748 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1749 (void **)h1->sps_buffers,
1750 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1753 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1754 (void **)h1->pps_buffers,
1755 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1759 if ((err = h264_slice_header_init(h, 1)) < 0) {
1760 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1763 context_reinitialized = 1;
1766 h264_set_parameter_from_sps(h);
1767 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1768 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1771 /* update linesize on resize for h264. The h264 decoder doesn't
1772 * necessarily call ff_MPV_frame_start in the new thread */
1773 h->linesize = h1->linesize;
1774 h->uvlinesize = h1->uvlinesize;
1776 /* copy block_offset since frame_start may not be called */
1777 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1780 for (i = 0; i < MAX_SPS_COUNT; i++)
1781 av_freep(h->sps_buffers + i);
1783 for (i = 0; i < MAX_PPS_COUNT; i++)
1784 av_freep(h->pps_buffers + i);
1786 av_freep(&h->rbsp_buffer[0]);
1787 av_freep(&h->rbsp_buffer[1]);
1788 memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1789 memcpy(&h->cabac, &h1->cabac,
1790 sizeof(H264Context) - offsetof(H264Context, cabac));
1791 av_assert0((void*)&h->cabac == &h->mb_padding + 1);
1793 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1794 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1796 memset(&h->er, 0, sizeof(h->er));
1797 memset(&h->me, 0, sizeof(h->me));
1798 memset(&h->mb, 0, sizeof(h->mb));
1799 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1800 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1804 h->qscale_table_pool = NULL;
1805 h->mb_type_pool = NULL;
1806 h->ref_index_pool = NULL;
1807 h->motion_val_pool = NULL;
1808 for (i = 0; i < 2; i++) {
1809 h->rbsp_buffer[i] = NULL;
1810 h->rbsp_buffer_size[i] = 0;
1813 if (h1->context_initialized) {
1814 h->context_initialized = 0;
1816 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1817 avcodec_get_frame_defaults(&h->cur_pic.f);
1818 h->cur_pic.tf.f = &h->cur_pic.f;
1820 ret = ff_h264_alloc_tables(h);
1822 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1825 ret = context_init(h);
1827 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1832 h->bipred_scratchpad = NULL;
1833 h->edge_emu_buffer = NULL;
1835 h->thread_context[0] = h;
1836 h->context_initialized = h1->context_initialized;
1839 h->avctx->coded_height = h1->avctx->coded_height;
1840 h->avctx->coded_width = h1->avctx->coded_width;
1841 h->avctx->width = h1->avctx->width;
1842 h->avctx->height = h1->avctx->height;
1843 h->coded_picture_number = h1->coded_picture_number;
1844 h->first_field = h1->first_field;
1845 h->picture_structure = h1->picture_structure;
1846 h->qscale = h1->qscale;
1847 h->droppable = h1->droppable;
1848 h->data_partitioning = h1->data_partitioning;
1849 h->low_delay = h1->low_delay;
1851 for (i = 0; h->DPB && i < MAX_PICTURE_COUNT; i++) {
1852 unref_picture(h, &h->DPB[i]);
1853 if (h1->DPB[i].f.buf[0] &&
1854 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1858 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1859 unref_picture(h, &h->cur_pic);
1860 if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1863 h->workaround_bugs = h1->workaround_bugs;
1864 h->low_delay = h1->low_delay;
1865 h->droppable = h1->droppable;
1867 // extradata/NAL handling
1868 h->is_avc = h1->is_avc;
1871 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1872 (void **)h1->sps_buffers,
1873 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1876 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1877 (void **)h1->pps_buffers,
1878 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1882 // Dequantization matrices
1883 // FIXME these are big - can they be only copied when PPS changes?
1884 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1886 for (i = 0; i < 6; i++)
1887 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1888 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1890 for (i = 0; i < 6; i++)
1891 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1892 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1894 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1897 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1900 copy_fields(h, h1, short_ref, cabac_init_idc);
1902 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1903 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1904 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1905 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1907 h->frame_recovered = h1->frame_recovered;
1909 if (context_reinitialized)
1910 h264_set_parameter_from_sps(h);
1912 if (!h->cur_pic_ptr)
1915 if (!h->droppable) {
1916 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1917 h->prev_poc_msb = h->poc_msb;
1918 h->prev_poc_lsb = h->poc_lsb;
1920 h->prev_frame_num_offset = h->frame_num_offset;
1921 h->prev_frame_num = h->frame_num;
1922 h->outputed_poc = h->next_outputed_poc;
1924 h->recovery_frame = h1->recovery_frame;
1929 static int h264_frame_start(H264Context *h)
1933 const int pixel_shift = h->pixel_shift;
1935 1<<(h->sps.bit_depth_luma-1),
1936 1<<(h->sps.bit_depth_chroma-1),
1937 1<<(h->sps.bit_depth_chroma-1),
1941 if (!ff_thread_can_start_frame(h->avctx)) {
1942 av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1946 release_unused_pictures(h, 1);
1947 h->cur_pic_ptr = NULL;
1949 i = find_unused_picture(h);
1951 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1956 pic->reference = h->droppable ? 0 : h->picture_structure;
1957 pic->f.coded_picture_number = h->coded_picture_number++;
1958 pic->field_picture = h->picture_structure != PICT_FRAME;
1961 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1963 * See decode_nal_units().
1965 pic->f.key_frame = 0;
1966 pic->mmco_reset = 0;
1969 if ((ret = alloc_picture(h, pic)) < 0)
1971 if(!h->frame_recovered && !h->avctx->hwaccel &&
1972 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1973 avpriv_color_frame(&pic->f, c);
1975 h->cur_pic_ptr = pic;
1976 unref_picture(h, &h->cur_pic);
1977 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1980 if (CONFIG_ERROR_RESILIENCE) {
1981 ff_er_frame_start(&h->er);
1983 h->er.next_pic = NULL;
1986 assert(h->linesize && h->uvlinesize);
1988 for (i = 0; i < 16; i++) {
1989 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1990 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1992 for (i = 0; i < 16; i++) {
1993 h->block_offset[16 + i] =
1994 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1995 h->block_offset[48 + 16 + i] =
1996 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1999 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
2000 // h->cur_pic.reference /* || h->contains_intra */ || 1;
2002 /* We mark the current picture as non-reference after allocating it, so
2003 * that if we break out due to an error it can be released automatically
2004 * in the next ff_MPV_frame_start().
2006 h->cur_pic_ptr->reference = 0;
2008 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
2010 h->next_output_pic = NULL;
2012 assert(h->cur_pic_ptr->long_ref == 0);
2018 * Run setup operations that must be run after slice header decoding.
2019 * This includes finding the next displayed frame.
2021 * @param h h264 master context
2022 * @param setup_finished enough NALs have been read that we can call
2023 * ff_thread_finish_setup()
2025 static void decode_postinit(H264Context *h, int setup_finished)
2027 Picture *out = h->cur_pic_ptr;
2028 Picture *cur = h->cur_pic_ptr;
2029 int i, pics, out_of_order, out_idx;
2031 h->cur_pic_ptr->f.pict_type = h->pict_type;
2033 if (h->next_output_pic)
2036 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
2037 /* FIXME: if we have two PAFF fields in one packet, we can't start
2038 * the next thread here. If we have one field per packet, we can.
2039 * The check in decode_nal_units() is not good enough to find this
2040 * yet, so we assume the worst for now. */
2041 // if (setup_finished)
2042 // ff_thread_finish_setup(h->avctx);
2046 cur->f.interlaced_frame = 0;
2047 cur->f.repeat_pict = 0;
2049 /* Signal interlacing information externally. */
2050 /* Prioritize picture timing SEI information over used
2051 * decoding process if it exists. */
2053 if (h->sps.pic_struct_present_flag) {
2054 switch (h->sei_pic_struct) {
2055 case SEI_PIC_STRUCT_FRAME:
2057 case SEI_PIC_STRUCT_TOP_FIELD:
2058 case SEI_PIC_STRUCT_BOTTOM_FIELD:
2059 cur->f.interlaced_frame = 1;
2061 case SEI_PIC_STRUCT_TOP_BOTTOM:
2062 case SEI_PIC_STRUCT_BOTTOM_TOP:
2063 if (FIELD_OR_MBAFF_PICTURE(h))
2064 cur->f.interlaced_frame = 1;
2066 // try to flag soft telecine progressive
2067 cur->f.interlaced_frame = h->prev_interlaced_frame;
2069 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
2070 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
2071 /* Signal the possibility of telecined film externally
2072 * (pic_struct 5,6). From these hints, let the applications
2073 * decide if they apply deinterlacing. */
2074 cur->f.repeat_pict = 1;
2076 case SEI_PIC_STRUCT_FRAME_DOUBLING:
2077 cur->f.repeat_pict = 2;
2079 case SEI_PIC_STRUCT_FRAME_TRIPLING:
2080 cur->f.repeat_pict = 4;
2084 if ((h->sei_ct_type & 3) &&
2085 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2086 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2088 /* Derive interlacing flag from used decoding process. */
2089 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2091 h->prev_interlaced_frame = cur->f.interlaced_frame;
2093 if (cur->field_poc[0] != cur->field_poc[1]) {
2094 /* Derive top_field_first from field pocs. */
2095 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2097 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2098 /* Use picture timing SEI information. Even if it is a
2099 * information of a past frame, better than nothing. */
2100 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2101 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2102 cur->f.top_field_first = 1;
2104 cur->f.top_field_first = 0;
2106 /* Most likely progressive */
2107 cur->f.top_field_first = 0;
2111 cur->mmco_reset = h->mmco_reset;
2113 // FIXME do something with unavailable reference frames
2115 /* Sort B-frames into display order */
2117 if (h->sps.bitstream_restriction_flag &&
2118 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2119 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2123 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2124 !h->sps.bitstream_restriction_flag) {
2125 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2129 for (i = 0; 1; i++) {
2130 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2132 h->last_pocs[i-1] = cur->poc;
2135 h->last_pocs[i-1]= h->last_pocs[i];
2138 out_of_order = MAX_DELAYED_PIC_COUNT - i;
2139 if( cur->f.pict_type == AV_PICTURE_TYPE_B
2140 || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
2141 out_of_order = FFMAX(out_of_order, 1);
2142 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2143 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2144 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2145 h->last_pocs[i] = INT_MIN;
2146 h->last_pocs[0] = cur->poc;
2147 cur->mmco_reset = 1;
2148 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2149 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2150 h->avctx->has_b_frames = out_of_order;
2155 while (h->delayed_pic[pics])
2158 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
2160 h->delayed_pic[pics++] = cur;
2161 if (cur->reference == 0)
2162 cur->reference = DELAYED_PIC_REF;
2164 out = h->delayed_pic[0];
2166 for (i = 1; h->delayed_pic[i] &&
2167 !h->delayed_pic[i]->f.key_frame &&
2168 !h->delayed_pic[i]->mmco_reset;
2170 if (h->delayed_pic[i]->poc < out->poc) {
2171 out = h->delayed_pic[i];
2174 if (h->avctx->has_b_frames == 0 &&
2175 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2176 h->next_outputed_poc = INT_MIN;
2177 out_of_order = out->poc < h->next_outputed_poc;
2179 if (out_of_order || pics > h->avctx->has_b_frames) {
2180 out->reference &= ~DELAYED_PIC_REF;
2181 // for frame threading, the owner must be the second field's thread or
2182 // else the first thread can release the picture and reuse it unsafely
2183 for (i = out_idx; h->delayed_pic[i]; i++)
2184 h->delayed_pic[i] = h->delayed_pic[i + 1];
2186 if (!out_of_order && pics > h->avctx->has_b_frames) {
2187 h->next_output_pic = out;
2188 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2189 h->next_outputed_poc = INT_MIN;
2191 h->next_outputed_poc = out->poc;
2193 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2196 if (h->next_output_pic) {
2197 if (h->next_output_pic->recovered) {
2198 // We have reached an recovery point and all frames after it in
2199 // display order are "recovered".
2200 h->frame_recovered |= FRAME_RECOVERED_SEI;
2202 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2205 if (setup_finished && !h->avctx->hwaccel)
2206 ff_thread_finish_setup(h->avctx);
2209 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2210 uint8_t *src_cb, uint8_t *src_cr,
2211 int linesize, int uvlinesize,
2214 uint8_t *top_border;
2216 const int pixel_shift = h->pixel_shift;
2217 int chroma444 = CHROMA444(h);
2218 int chroma422 = CHROMA422(h);
2221 src_cb -= uvlinesize;
2222 src_cr -= uvlinesize;
2224 if (!simple && FRAME_MBAFF(h)) {
2227 top_border = h->top_borders[0][h->mb_x];
2228 AV_COPY128(top_border, src_y + 15 * linesize);
2230 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2231 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2234 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2235 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2236 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2237 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2239 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2240 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2242 } else if (chroma422) {
2244 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2245 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2247 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2248 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2252 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2253 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2255 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2256 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2261 } else if (MB_MBAFF(h)) {
2267 top_border = h->top_borders[top_idx][h->mb_x];
2268 /* There are two lines saved, the line above the top macroblock
2269 * of a pair, and the line above the bottom macroblock. */
2270 AV_COPY128(top_border, src_y + 16 * linesize);
2272 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2274 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2277 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2278 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2279 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2280 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2282 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2283 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2285 } else if (chroma422) {
2287 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2288 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2290 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2291 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2295 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2296 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2298 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2299 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2305 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2306 uint8_t *src_cb, uint8_t *src_cr,
2307 int linesize, int uvlinesize,
2308 int xchg, int chroma444,
2309 int simple, int pixel_shift)
2311 int deblock_topleft;
2314 uint8_t *top_border_m1;
2315 uint8_t *top_border;
2317 if (!simple && FRAME_MBAFF(h)) {
2322 top_idx = MB_MBAFF(h) ? 0 : 1;
2326 if (h->deblocking_filter == 2) {
2327 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2328 deblock_top = h->top_type;
2330 deblock_topleft = (h->mb_x > 0);
2331 deblock_top = (h->mb_y > !!MB_FIELD(h));
2334 src_y -= linesize + 1 + pixel_shift;
2335 src_cb -= uvlinesize + 1 + pixel_shift;
2336 src_cr -= uvlinesize + 1 + pixel_shift;
2338 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2339 top_border = h->top_borders[top_idx][h->mb_x];
2341 #define XCHG(a, b, xchg) \
2342 if (pixel_shift) { \
2344 AV_SWAP64(b + 0, a + 0); \
2345 AV_SWAP64(b + 8, a + 8); \
2355 if (deblock_topleft) {
2356 XCHG(top_border_m1 + (8 << pixel_shift),
2357 src_y - (7 << pixel_shift), 1);
2359 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2360 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2361 if (h->mb_x + 1 < h->mb_width) {
2362 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2363 src_y + (17 << pixel_shift), 1);
2365 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2367 if (deblock_topleft) {
2368 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2369 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2371 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2372 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2373 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2374 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2375 if (h->mb_x + 1 < h->mb_width) {
2376 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2377 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2380 if (deblock_topleft) {
2381 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2382 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2384 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2385 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2391 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2394 if (high_bit_depth) {
2395 return AV_RN32A(((int32_t *)mb) + index);
2397 return AV_RN16A(mb + index);
2400 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2401 int index, int value)
2403 if (high_bit_depth) {
2404 AV_WN32A(((int32_t *)mb) + index, value);
2406 AV_WN16A(mb + index, value);
2409 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2410 int mb_type, int is_h264,
2412 int transform_bypass,
2416 uint8_t *dest_y, int p)
2418 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2419 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2421 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2422 block_offset += 16 * p;
2423 if (IS_INTRA4x4(mb_type)) {
2424 if (IS_8x8DCT(mb_type)) {
2425 if (transform_bypass) {
2427 idct_add = h->h264dsp.h264_add_pixels8_clear;
2429 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2430 idct_add = h->h264dsp.h264_idct8_add;
2432 for (i = 0; i < 16; i += 4) {
2433 uint8_t *const ptr = dest_y + block_offset[i];
2434 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2435 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2436 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2438 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2439 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2440 (h->topright_samples_available << i) & 0x4000, linesize);
2442 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2443 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2445 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2450 if (transform_bypass) {
2452 idct_add = h->h264dsp.h264_add_pixels4_clear;
2454 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2455 idct_add = h->h264dsp.h264_idct_add;
2457 for (i = 0; i < 16; i++) {
2458 uint8_t *const ptr = dest_y + block_offset[i];
2459 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2461 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2462 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2467 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2468 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2469 av_assert2(h->mb_y || linesize <= block_offset[i]);
2470 if (!topright_avail) {
2472 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2473 topright = (uint8_t *)&tr_high;
2475 tr = ptr[3 - linesize] * 0x01010101u;
2476 topright = (uint8_t *)&tr;
2479 topright = ptr + (4 << pixel_shift) - linesize;
2483 h->hpc.pred4x4[dir](ptr, topright, linesize);
2484 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2487 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2488 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2490 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2491 } else if (CONFIG_SVQ3_DECODER)
2492 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2498 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2500 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2501 if (!transform_bypass)
2502 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2504 h->dequant4_coeff[p][qscale][0]);
2506 static const uint8_t dc_mapping[16] = {
2507 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2508 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2509 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2510 10 * 16, 11 * 16, 14 * 16, 15 * 16
2512 for (i = 0; i < 16; i++)
2513 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2514 pixel_shift, dc_mapping[i],
2515 dctcoef_get(h->mb_luma_dc[p],
2519 } else if (CONFIG_SVQ3_DECODER)
2520 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2521 h->mb_luma_dc[p], qscale);
2525 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2526 int is_h264, int simple,
2527 int transform_bypass,
2531 uint8_t *dest_y, int p)
2533 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2535 block_offset += 16 * p;
2536 if (!IS_INTRA4x4(mb_type)) {
2538 if (IS_INTRA16x16(mb_type)) {
2539 if (transform_bypass) {
2540 if (h->sps.profile_idc == 244 &&
2541 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2542 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2543 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2544 h->mb + (p * 256 << pixel_shift),
2547 for (i = 0; i < 16; i++)
2548 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2549 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2550 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2551 h->mb + (i * 16 + p * 256 << pixel_shift),
2555 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2556 h->mb + (p * 256 << pixel_shift),
2558 h->non_zero_count_cache + p * 5 * 8);
2560 } else if (h->cbp & 15) {
2561 if (transform_bypass) {
2562 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2563 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2564 : h->h264dsp.h264_add_pixels4_clear;
2565 for (i = 0; i < 16; i += di)
2566 if (h->non_zero_count_cache[scan8[i + p * 16]])
2567 idct_add(dest_y + block_offset[i],
2568 h->mb + (i * 16 + p * 256 << pixel_shift),
2571 if (IS_8x8DCT(mb_type))
2572 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2573 h->mb + (p * 256 << pixel_shift),
2575 h->non_zero_count_cache + p * 5 * 8);
2577 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2578 h->mb + (p * 256 << pixel_shift),
2580 h->non_zero_count_cache + p * 5 * 8);
2583 } else if (CONFIG_SVQ3_DECODER) {
2584 for (i = 0; i < 16; i++)
2585 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2586 // FIXME benchmark weird rule, & below
2587 uint8_t *const ptr = dest_y + block_offset[i];
2588 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2589 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2597 #include "h264_mb_template.c"
2601 #include "h264_mb_template.c"
2605 #include "h264_mb_template.c"
2607 void ff_h264_hl_decode_mb(H264Context *h)
2609 const int mb_xy = h->mb_xy;
2610 const int mb_type = h->cur_pic.mb_type[mb_xy];
2611 int is_complex = CONFIG_SMALL || h->is_complex ||
2612 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2615 if (is_complex || h->pixel_shift)
2616 hl_decode_mb_444_complex(h);
2618 hl_decode_mb_444_simple_8(h);
2619 } else if (is_complex) {
2620 hl_decode_mb_complex(h);
2621 } else if (h->pixel_shift) {
2622 hl_decode_mb_simple_16(h);
2624 hl_decode_mb_simple_8(h);
2627 int ff_pred_weight_table(H264Context *h)
2630 int luma_def, chroma_def;
2633 h->use_weight_chroma = 0;
2634 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2635 if (h->sps.chroma_format_idc)
2636 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2637 luma_def = 1 << h->luma_log2_weight_denom;
2638 chroma_def = 1 << h->chroma_log2_weight_denom;
2640 for (list = 0; list < 2; list++) {
2641 h->luma_weight_flag[list] = 0;
2642 h->chroma_weight_flag[list] = 0;
2643 for (i = 0; i < h->ref_count[list]; i++) {
2644 int luma_weight_flag, chroma_weight_flag;
2646 luma_weight_flag = get_bits1(&h->gb);
2647 if (luma_weight_flag) {
2648 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2649 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2650 if (h->luma_weight[i][list][0] != luma_def ||
2651 h->luma_weight[i][list][1] != 0) {
2653 h->luma_weight_flag[list] = 1;
2656 h->luma_weight[i][list][0] = luma_def;
2657 h->luma_weight[i][list][1] = 0;
2660 if (h->sps.chroma_format_idc) {
2661 chroma_weight_flag = get_bits1(&h->gb);
2662 if (chroma_weight_flag) {
2664 for (j = 0; j < 2; j++) {
2665 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2666 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2667 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2668 h->chroma_weight[i][list][j][1] != 0) {
2669 h->use_weight_chroma = 1;
2670 h->chroma_weight_flag[list] = 1;
2675 for (j = 0; j < 2; j++) {
2676 h->chroma_weight[i][list][j][0] = chroma_def;
2677 h->chroma_weight[i][list][j][1] = 0;
2682 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2685 h->use_weight = h->use_weight || h->use_weight_chroma;
2690 * Initialize implicit_weight table.
2691 * @param field 0/1 initialize the weight for interlaced MBAFF
2692 * -1 initializes the rest
2694 static void implicit_weight_table(H264Context *h, int field)
2696 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2698 for (i = 0; i < 2; i++) {
2699 h->luma_weight_flag[i] = 0;
2700 h->chroma_weight_flag[i] = 0;
2704 if (h->picture_structure == PICT_FRAME) {
2705 cur_poc = h->cur_pic_ptr->poc;
2707 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2709 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2710 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2712 h->use_weight_chroma = 0;
2716 ref_count0 = h->ref_count[0];
2717 ref_count1 = h->ref_count[1];
2719 cur_poc = h->cur_pic_ptr->field_poc[field];
2721 ref_count0 = 16 + 2 * h->ref_count[0];
2722 ref_count1 = 16 + 2 * h->ref_count[1];
2726 h->use_weight_chroma = 2;
2727 h->luma_log2_weight_denom = 5;
2728 h->chroma_log2_weight_denom = 5;
2730 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2731 int poc0 = h->ref_list[0][ref0].poc;
2732 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2734 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2735 int poc1 = h->ref_list[1][ref1].poc;
2736 int td = av_clip(poc1 - poc0, -128, 127);
2738 int tb = av_clip(cur_poc - poc0, -128, 127);
2739 int tx = (16384 + (FFABS(td) >> 1)) / td;
2740 int dist_scale_factor = (tb * tx + 32) >> 8;
2741 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2742 w = 64 - dist_scale_factor;
2746 h->implicit_weight[ref0][ref1][0] =
2747 h->implicit_weight[ref0][ref1][1] = w;
2749 h->implicit_weight[ref0][ref1][field] = w;
2756 * instantaneous decoder refresh.
2758 static void idr(H264Context *h)
2761 ff_h264_remove_all_refs(h);
2762 h->prev_frame_num = 0;
2763 h->prev_frame_num_offset = 0;
2764 h->prev_poc_msb = 1<<16;
2765 h->prev_poc_lsb = 0;
2766 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2767 h->last_pocs[i] = INT_MIN;
2770 /* forget old pics after a seek */
2771 static void flush_change(H264Context *h)
2775 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2776 h->prev_interlaced_frame = 1;
2779 h->prev_frame_num = -1;
2780 if (h->cur_pic_ptr) {
2781 h->cur_pic_ptr->reference = 0;
2782 for (j=i=0; h->delayed_pic[i]; i++)
2783 if (h->delayed_pic[i] != h->cur_pic_ptr)
2784 h->delayed_pic[j++] = h->delayed_pic[i];
2785 h->delayed_pic[j] = NULL;
2788 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2789 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2790 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2791 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2792 ff_h264_reset_sei(h);
2793 h->recovery_frame = -1;
2794 h->frame_recovered = 0;
2796 h->current_slice = 0;
2800 /* forget old pics after a seek */
2801 static void flush_dpb(AVCodecContext *avctx)
2803 H264Context *h = avctx->priv_data;
2806 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2807 if (h->delayed_pic[i])
2808 h->delayed_pic[i]->reference = 0;
2809 h->delayed_pic[i] = NULL;
2815 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2816 unref_picture(h, &h->DPB[i]);
2817 h->cur_pic_ptr = NULL;
2818 unref_picture(h, &h->cur_pic);
2820 h->mb_x = h->mb_y = 0;
2822 h->parse_context.state = -1;
2823 h->parse_context.frame_start_found = 0;
2824 h->parse_context.overread = 0;
2825 h->parse_context.overread_index = 0;
2826 h->parse_context.index = 0;
2827 h->parse_context.last_index = 0;
2830 h->context_initialized = 0;
2833 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2835 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2838 h->frame_num_offset = h->prev_frame_num_offset;
2839 if (h->frame_num < h->prev_frame_num)
2840 h->frame_num_offset += max_frame_num;
2842 if (h->sps.poc_type == 0) {
2843 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2845 if (h->poc_lsb < h->prev_poc_lsb &&
2846 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2847 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2848 else if (h->poc_lsb > h->prev_poc_lsb &&
2849 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2850 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2852 h->poc_msb = h->prev_poc_msb;
2854 field_poc[1] = h->poc_msb + h->poc_lsb;
2855 if (h->picture_structure == PICT_FRAME)
2856 field_poc[1] += h->delta_poc_bottom;
2857 } else if (h->sps.poc_type == 1) {
2858 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2861 if (h->sps.poc_cycle_length != 0)
2862 abs_frame_num = h->frame_num_offset + h->frame_num;
2866 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2869 expected_delta_per_poc_cycle = 0;
2870 for (i = 0; i < h->sps.poc_cycle_length; i++)
2871 // FIXME integrate during sps parse
2872 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2874 if (abs_frame_num > 0) {
2875 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2876 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2878 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2879 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2880 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2884 if (h->nal_ref_idc == 0)
2885 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2887 field_poc[0] = expectedpoc + h->delta_poc[0];
2888 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2890 if (h->picture_structure == PICT_FRAME)
2891 field_poc[1] += h->delta_poc[1];
2893 int poc = 2 * (h->frame_num_offset + h->frame_num);
2895 if (!h->nal_ref_idc)
2902 if (h->picture_structure != PICT_BOTTOM_FIELD)
2903 pic_field_poc[0] = field_poc[0];
2904 if (h->picture_structure != PICT_TOP_FIELD)
2905 pic_field_poc[1] = field_poc[1];
2906 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2912 * initialize scan tables
2914 static void init_scan_tables(H264Context *h)
2917 for (i = 0; i < 16; i++) {
2918 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2919 h->zigzag_scan[i] = T(zigzag_scan[i]);
2920 h->field_scan[i] = T(field_scan[i]);
2923 for (i = 0; i < 64; i++) {
2924 #define T(x) (x >> 3) | ((x & 7) << 3)
2925 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2926 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2927 h->field_scan8x8[i] = T(field_scan8x8[i]);
2928 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2931 if (h->sps.transform_bypass) { // FIXME same ugly
2932 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2933 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2934 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2935 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2936 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2937 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2939 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2940 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2941 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2942 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2943 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2944 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2948 static int field_end(H264Context *h, int in_setup)
2950 AVCodecContext *const avctx = h->avctx;
2954 if (CONFIG_H264_VDPAU_DECODER &&
2955 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2956 ff_vdpau_h264_set_reference_frames(h);
2958 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2959 if (!h->droppable) {
2960 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
2961 h->prev_poc_msb = h->poc_msb;
2962 h->prev_poc_lsb = h->poc_lsb;
2964 h->prev_frame_num_offset = h->frame_num_offset;
2965 h->prev_frame_num = h->frame_num;
2966 h->outputed_poc = h->next_outputed_poc;
2969 if (avctx->hwaccel) {
2970 if (avctx->hwaccel->end_frame(avctx) < 0)
2971 av_log(avctx, AV_LOG_ERROR,
2972 "hardware accelerator failed to decode picture\n");
2975 if (CONFIG_H264_VDPAU_DECODER &&
2976 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2977 ff_vdpau_h264_picture_complete(h);
2980 * FIXME: Error handling code does not seem to support interlaced
2981 * when slices span multiple rows
2982 * The ff_er_add_slice calls don't work right for bottom
2983 * fields; they cause massive erroneous error concealing
2984 * Error marking covers both fields (top and bottom).
2985 * This causes a mismatched s->error_count
2986 * and a bad error table. Further, the error count goes to
2987 * INT_MAX when called for bottom field, because mb_y is
2988 * past end by one (callers fault) and resync_mb_y != 0
2989 * causes problems for the first MB line, too.
2991 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
2992 h->er.cur_pic = h->cur_pic_ptr;
2993 ff_er_frame_end(&h->er);
2995 if (!in_setup && !h->droppable)
2996 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2997 h->picture_structure == PICT_BOTTOM_FIELD);
3000 h->current_slice = 0;
3006 * Replicate H264 "master" context to thread contexts.
3008 static int clone_slice(H264Context *dst, H264Context *src)
3010 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
3011 dst->cur_pic_ptr = src->cur_pic_ptr;
3012 dst->cur_pic = src->cur_pic;
3013 dst->linesize = src->linesize;
3014 dst->uvlinesize = src->uvlinesize;
3015 dst->first_field = src->first_field;
3017 dst->prev_poc_msb = src->prev_poc_msb;
3018 dst->prev_poc_lsb = src->prev_poc_lsb;
3019 dst->prev_frame_num_offset = src->prev_frame_num_offset;
3020 dst->prev_frame_num = src->prev_frame_num;
3021 dst->short_ref_count = src->short_ref_count;
3023 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
3024 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
3025 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3027 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
3028 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
3034 * Compute profile from profile_idc and constraint_set?_flags.
3038 * @return profile as defined by FF_PROFILE_H264_*
3040 int ff_h264_get_profile(SPS *sps)
3042 int profile = sps->profile_idc;
3044 switch (sps->profile_idc) {
3045 case FF_PROFILE_H264_BASELINE:
3046 // constraint_set1_flag set to 1
3047 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3049 case FF_PROFILE_H264_HIGH_10:
3050 case FF_PROFILE_H264_HIGH_422:
3051 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3052 // constraint_set3_flag set to 1
3053 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3060 static int h264_set_parameter_from_sps(H264Context *h)
3062 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3063 (h->sps.bitstream_restriction_flag &&
3064 !h->sps.num_reorder_frames)) {
3065 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3066 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3067 "Reenabling low delay requires a codec flush.\n");
3072 if (h->avctx->has_b_frames < 2)
3073 h->avctx->has_b_frames = !h->low_delay;
3075 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
3076 avpriv_request_sample(h->avctx,
3077 "Different chroma and luma bit depth");
3078 return AVERROR_PATCHWELCOME;
3081 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3082 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
3083 if (h->avctx->codec &&
3084 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
3085 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
3086 av_log(h->avctx, AV_LOG_ERROR,
3087 "VDPAU decoding does not support video colorspace.\n");
3088 return AVERROR_INVALIDDATA;
3090 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
3091 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
3092 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3093 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
3094 h->pixel_shift = h->sps.bit_depth_luma > 8;
3096 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3097 h->sps.chroma_format_idc);
3098 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3099 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3100 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3101 h->sps.chroma_format_idc);
3103 if (CONFIG_ERROR_RESILIENCE)
3104 ff_dsputil_init(&h->dsp, h->avctx);
3105 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3107 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3108 h->sps.bit_depth_luma);
3109 return AVERROR_INVALIDDATA;
3115 static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3117 switch (h->sps.bit_depth_luma) {
3120 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3121 return AV_PIX_FMT_GBRP9;
3123 return AV_PIX_FMT_YUV444P9;
3124 } else if (CHROMA422(h))
3125 return AV_PIX_FMT_YUV422P9;
3127 return AV_PIX_FMT_YUV420P9;
3131 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3132 return AV_PIX_FMT_GBRP10;
3134 return AV_PIX_FMT_YUV444P10;
3135 } else if (CHROMA422(h))
3136 return AV_PIX_FMT_YUV422P10;
3138 return AV_PIX_FMT_YUV420P10;
3142 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3143 return AV_PIX_FMT_GBRP12;
3145 return AV_PIX_FMT_YUV444P12;
3146 } else if (CHROMA422(h))
3147 return AV_PIX_FMT_YUV422P12;
3149 return AV_PIX_FMT_YUV420P12;
3153 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3154 return AV_PIX_FMT_GBRP14;
3156 return AV_PIX_FMT_YUV444P14;
3157 } else if (CHROMA422(h))
3158 return AV_PIX_FMT_YUV422P14;
3160 return AV_PIX_FMT_YUV420P14;
3164 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3165 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
3166 return AV_PIX_FMT_GBR24P;
3167 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
3168 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
3170 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3171 : AV_PIX_FMT_YUV444P;
3172 } else if (CHROMA422(h)) {
3173 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3174 : AV_PIX_FMT_YUV422P;
3177 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
3178 h->avctx->codec->pix_fmts :
3179 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3180 h264_hwaccel_pixfmt_list_jpeg_420 :
3181 h264_hwaccel_pixfmt_list_420;
3183 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
3184 if (fmt[i] == h->avctx->pix_fmt && !force_callback)
3186 return ff_thread_get_format(h->avctx, fmt);
3190 av_log(h->avctx, AV_LOG_ERROR,
3191 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3192 return AVERROR_INVALIDDATA;
3196 /* export coded and cropped frame dimensions to AVCodecContext */
3197 static int init_dimensions(H264Context *h)
3199 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3200 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3201 av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
3202 av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
3204 /* handle container cropping */
3206 FFALIGN(h->avctx->width, 16) == h->width &&
3207 FFALIGN(h->avctx->height, 16) == h->height) {
3208 width = h->avctx->width;
3209 height = h->avctx->height;
3212 if (width <= 0 || height <= 0) {
3213 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3215 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3216 return AVERROR_INVALIDDATA;
3218 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3219 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3226 h->avctx->coded_width = h->width;
3227 h->avctx->coded_height = h->height;
3228 h->avctx->width = width;
3229 h->avctx->height = height;
3234 static int h264_slice_header_init(H264Context *h, int reinit)
3236 int nb_slices = (HAVE_THREADS &&
3237 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3238 h->avctx->thread_count : 1;
3241 h->avctx->sample_aspect_ratio = h->sps.sar;
3242 av_assert0(h->avctx->sample_aspect_ratio.den);
3243 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3244 &h->chroma_x_shift, &h->chroma_y_shift);
3246 if (h->sps.timing_info_present_flag) {
3247 int64_t den = h->sps.time_scale;
3248 if (h->x264_build < 44U)
3250 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3251 h->sps.num_units_in_tick, den, 1 << 30);
3254 h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3259 h->prev_interlaced_frame = 1;
3261 init_scan_tables(h);
3262 ret = ff_h264_alloc_tables(h);
3264 av_log(h->avctx, AV_LOG_ERROR,
3265 "Could not allocate memory for h264\n");
3269 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3272 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3274 max_slices = MAX_THREADS;
3275 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3276 " reducing to %d\n", nb_slices, max_slices);
3277 nb_slices = max_slices;
3279 h->slice_context_count = nb_slices;
3281 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3282 ret = context_init(h);
3284 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3288 for (i = 1; i < h->slice_context_count; i++) {
3290 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3292 return AVERROR(ENOMEM);
3293 c->avctx = h->avctx;
3294 if (CONFIG_ERROR_RESILIENCE) {
3298 c->h264dsp = h->h264dsp;
3299 c->h264qpel = h->h264qpel;
3300 c->h264chroma = h->h264chroma;
3303 c->pixel_shift = h->pixel_shift;
3304 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3305 c->width = h->width;
3306 c->height = h->height;
3307 c->linesize = h->linesize;
3308 c->uvlinesize = h->uvlinesize;
3309 c->chroma_x_shift = h->chroma_x_shift;
3310 c->chroma_y_shift = h->chroma_y_shift;
3311 c->qscale = h->qscale;
3312 c->droppable = h->droppable;
3313 c->data_partitioning = h->data_partitioning;
3314 c->low_delay = h->low_delay;
3315 c->mb_width = h->mb_width;
3316 c->mb_height = h->mb_height;
3317 c->mb_stride = h->mb_stride;
3318 c->mb_num = h->mb_num;
3319 c->flags = h->flags;
3320 c->workaround_bugs = h->workaround_bugs;
3321 c->pict_type = h->pict_type;
3323 init_scan_tables(c);
3324 clone_tables(c, h, i);
3325 c->context_initialized = 1;
3328 for (i = 0; i < h->slice_context_count; i++)
3329 if ((ret = context_init(h->thread_context[i])) < 0) {
3330 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3335 h->context_initialized = 1;
3340 int ff_set_ref_count(H264Context *h)
3342 int num_ref_idx_active_override_flag;
3344 // set defaults, might be overridden a few lines later
3345 h->ref_count[0] = h->pps.ref_count[0];
3346 h->ref_count[1] = h->pps.ref_count[1];
3348 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3350 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3352 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3353 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3354 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3356 if (num_ref_idx_active_override_flag) {
3357 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3358 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3359 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3361 // full range is spec-ok in this case, even for frames
3362 h->ref_count[1] = 1;
3365 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3366 av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
3367 h->ref_count[0] = h->ref_count[1] = 0;
3368 return AVERROR_INVALIDDATA;
3371 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3377 h->ref_count[0] = h->ref_count[1] = 0;
3384 * Decode a slice header.
3385 * This will also call ff_MPV_common_init() and frame_start() as needed.
3387 * @param h h264context
3388 * @param h0 h264 master context (differs from 'h' when doing sliced based
3389 * parallel decoding)
3391 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3393 static int decode_slice_header(H264Context *h, H264Context *h0)
3395 unsigned int first_mb_in_slice;
3396 unsigned int pps_id;
3398 unsigned int slice_type, tmp, i, j;
3399 int last_pic_structure, last_pic_droppable;
3401 int needs_reinit = 0;
3402 int field_pic_flag, bottom_field_flag;
3404 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3405 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3407 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3409 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3410 if (h0->current_slice && FIELD_PICTURE(h)) {
3414 h0->current_slice = 0;
3415 if (!h0->first_field) {
3416 if (h->cur_pic_ptr && !h->droppable) {
3417 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3418 h->picture_structure == PICT_BOTTOM_FIELD);
3420 h->cur_pic_ptr = NULL;
3424 slice_type = get_ue_golomb_31(&h->gb);
3425 if (slice_type > 9) {
3426 av_log(h->avctx, AV_LOG_ERROR,
3427 "slice type too large (%d) at %d %d\n",
3428 slice_type, h->mb_x, h->mb_y);
3429 return AVERROR_INVALIDDATA;
3431 if (slice_type > 4) {
3433 h->slice_type_fixed = 1;
3435 h->slice_type_fixed = 0;
3437 slice_type = golomb_to_pict_type[slice_type];
3438 h->slice_type = slice_type;
3439 h->slice_type_nos = slice_type & 3;
3441 // to make a few old functions happy, it's wrong though
3442 h->pict_type = h->slice_type;
3444 pps_id = get_ue_golomb(&h->gb);
3445 if (pps_id >= MAX_PPS_COUNT) {
3446 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3447 return AVERROR_INVALIDDATA;
3449 if (!h0->pps_buffers[pps_id]) {
3450 av_log(h->avctx, AV_LOG_ERROR,
3451 "non-existing PPS %u referenced\n",
3453 return AVERROR_INVALIDDATA;
3455 h->pps = *h0->pps_buffers[pps_id];
3457 if (!h0->sps_buffers[h->pps.sps_id]) {
3458 av_log(h->avctx, AV_LOG_ERROR,
3459 "non-existing SPS %u referenced\n",
3461 return AVERROR_INVALIDDATA;
3464 if (h->pps.sps_id != h->current_sps_id ||
3465 h0->sps_buffers[h->pps.sps_id]->new) {
3466 h0->sps_buffers[h->pps.sps_id]->new = 0;
3468 h->current_sps_id = h->pps.sps_id;
3469 h->sps = *h0->sps_buffers[h->pps.sps_id];
3471 if (h->mb_width != h->sps.mb_width ||
3472 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3473 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3474 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3478 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3479 h->chroma_format_idc != h->sps.chroma_format_idc) {
3480 h->bit_depth_luma = h->sps.bit_depth_luma;
3481 h->chroma_format_idc = h->sps.chroma_format_idc;
3484 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3488 h->avctx->profile = ff_h264_get_profile(&h->sps);
3489 h->avctx->level = h->sps.level_idc;
3490 h->avctx->refs = h->sps.ref_frame_count;
3492 must_reinit = (h->context_initialized &&
3493 ( 16*h->sps.mb_width != h->avctx->coded_width
3494 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3495 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3496 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3497 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
3498 || h->mb_width != h->sps.mb_width
3499 || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
3501 if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3504 h->mb_width = h->sps.mb_width;
3505 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3506 h->mb_num = h->mb_width * h->mb_height;
3507 h->mb_stride = h->mb_width + 1;
3509 h->b_stride = h->mb_width * 4;
3511 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3513 h->width = 16 * h->mb_width;
3514 h->height = 16 * h->mb_height;
3516 ret = init_dimensions(h);
3520 if (h->sps.video_signal_type_present_flag) {
3521 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3523 if (h->sps.colour_description_present_flag) {
3524 if (h->avctx->colorspace != h->sps.colorspace)
3526 h->avctx->color_primaries = h->sps.color_primaries;
3527 h->avctx->color_trc = h->sps.color_trc;
3528 h->avctx->colorspace = h->sps.colorspace;
3532 if (h->context_initialized &&
3533 (h->width != h->avctx->coded_width ||
3534 h->height != h->avctx->coded_height ||
3538 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3539 "slice %d\n", h0->current_slice + 1);
3540 return AVERROR_INVALIDDATA;
3545 if ((ret = get_pixel_format(h, 1)) < 0)
3547 h->avctx->pix_fmt = ret;
3549 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3550 "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
3552 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3553 av_log(h->avctx, AV_LOG_ERROR,
3554 "h264_slice_header_init() failed\n");
3558 if (!h->context_initialized) {
3560 av_log(h->avctx, AV_LOG_ERROR,
3561 "Cannot (re-)initialize context during parallel decoding.\n");
3562 return AVERROR_PATCHWELCOME;
3565 if ((ret = get_pixel_format(h, 1)) < 0)
3567 h->avctx->pix_fmt = ret;
3569 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3570 av_log(h->avctx, AV_LOG_ERROR,
3571 "h264_slice_header_init() failed\n");
3576 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3577 h->dequant_coeff_pps = pps_id;
3578 init_dequant_tables(h);
3581 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3584 h->mb_aff_frame = 0;
3585 last_pic_structure = h0->picture_structure;
3586 last_pic_droppable = h0->droppable;
3587 h->droppable = h->nal_ref_idc == 0;
3588 if (h->sps.frame_mbs_only_flag) {
3589 h->picture_structure = PICT_FRAME;
3591 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3592 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3595 field_pic_flag = get_bits1(&h->gb);
3596 if (field_pic_flag) {
3597 bottom_field_flag = get_bits1(&h->gb);
3598 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3600 h->picture_structure = PICT_FRAME;
3601 h->mb_aff_frame = h->sps.mb_aff;
3604 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3606 if (h0->current_slice != 0) {
3607 if (last_pic_structure != h->picture_structure ||
3608 last_pic_droppable != h->droppable) {
3609 av_log(h->avctx, AV_LOG_ERROR,
3610 "Changing field mode (%d -> %d) between slices is not allowed\n",
3611 last_pic_structure, h->picture_structure);
3612 h->picture_structure = last_pic_structure;
3613 h->droppable = last_pic_droppable;
3614 return AVERROR_INVALIDDATA;
3615 } else if (!h0->cur_pic_ptr) {
3616 av_log(h->avctx, AV_LOG_ERROR,
3617 "unset cur_pic_ptr on %d. slice\n",
3618 h0->current_slice + 1);
3619 return AVERROR_INVALIDDATA;
3622 /* Shorten frame num gaps so we don't have to allocate reference
3623 * frames just to throw them away */
3624 if (h->frame_num != h->prev_frame_num) {
3625 int unwrap_prev_frame_num = h->prev_frame_num;
3626 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3628 if (unwrap_prev_frame_num > h->frame_num)
3629 unwrap_prev_frame_num -= max_frame_num;
3631 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3632 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3633 if (unwrap_prev_frame_num < 0)
3634 unwrap_prev_frame_num += max_frame_num;
3636 h->prev_frame_num = unwrap_prev_frame_num;
3640 /* See if we have a decoded first field looking for a pair...
3641 * Here, we're using that to see if we should mark previously
3642 * decode frames as "finished".
3643 * We have to do that before the "dummy" in-between frame allocation,
3644 * since that can modify h->cur_pic_ptr. */
3645 if (h0->first_field) {
3646 assert(h0->cur_pic_ptr);
3647 assert(h0->cur_pic_ptr->f.buf[0]);
3648 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3650 /* Mark old field/frame as completed */
3651 if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
3652 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3653 last_pic_structure == PICT_BOTTOM_FIELD);
3656 /* figure out if we have a complementary field pair */
3657 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3658 /* Previous field is unmatched. Don't display it, but let it
3659 * remain for reference if marked as such. */
3660 if (last_pic_structure != PICT_FRAME) {
3661 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3662 last_pic_structure == PICT_TOP_FIELD);
3665 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3666 /* This and previous field were reference, but had
3667 * different frame_nums. Consider this field first in
3668 * pair. Throw away previous field except for reference
3670 if (last_pic_structure != PICT_FRAME) {
3671 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3672 last_pic_structure == PICT_TOP_FIELD);
3675 /* Second field in complementary pair */
3676 if (!((last_pic_structure == PICT_TOP_FIELD &&
3677 h->picture_structure == PICT_BOTTOM_FIELD) ||
3678 (last_pic_structure == PICT_BOTTOM_FIELD &&
3679 h->picture_structure == PICT_TOP_FIELD))) {
3680 av_log(h->avctx, AV_LOG_ERROR,
3681 "Invalid field mode combination %d/%d\n",
3682 last_pic_structure, h->picture_structure);
3683 h->picture_structure = last_pic_structure;
3684 h->droppable = last_pic_droppable;
3685 return AVERROR_INVALIDDATA;
3686 } else if (last_pic_droppable != h->droppable) {
3687 avpriv_request_sample(h->avctx,
3688 "Found reference and non-reference fields in the same frame, which");
3689 h->picture_structure = last_pic_structure;
3690 h->droppable = last_pic_droppable;
3691 return AVERROR_PATCHWELCOME;
3697 while (h->frame_num != h->prev_frame_num && !h0->first_field &&
3698 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3699 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3700 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3701 h->frame_num, h->prev_frame_num);
3702 if (!h->sps.gaps_in_frame_num_allowed_flag)
3703 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3704 h->last_pocs[i] = INT_MIN;
3705 ret = h264_frame_start(h);
3708 h->prev_frame_num++;
3709 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3710 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3711 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3712 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3713 ret = ff_generate_sliding_window_mmcos(h, 1);
3714 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3716 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3717 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3719 /* Error concealment: If a ref is missing, copy the previous ref
3721 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3722 * many assumptions about there being no actual duplicates.
3723 * FIXME: This does not copy padding for out-of-frame motion
3724 * vectors. Given we are concealing a lost frame, this probably
3725 * is not noticeable by comparison, but it should be fixed. */
3726 if (h->short_ref_count) {
3728 av_image_copy(h->short_ref[0]->f.data,
3729 h->short_ref[0]->f.linesize,
3730 (const uint8_t **)prev->f.data,
3735 h->short_ref[0]->poc = prev->poc + 2;
3737 h->short_ref[0]->frame_num = h->prev_frame_num;
3741 /* See if we have a decoded first field looking for a pair...
3742 * We're using that to see whether to continue decoding in that
3743 * frame, or to allocate a new one. */
3744 if (h0->first_field) {
3745 assert(h0->cur_pic_ptr);
3746 assert(h0->cur_pic_ptr->f.buf[0]);
3747 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3749 /* figure out if we have a complementary field pair */
3750 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3751 /* Previous field is unmatched. Don't display it, but let it
3752 * remain for reference if marked as such. */
3753 h0->cur_pic_ptr = NULL;
3754 h0->first_field = FIELD_PICTURE(h);
3756 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3757 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3758 h0->picture_structure==PICT_BOTTOM_FIELD);
3759 /* This and the previous field had different frame_nums.
3760 * Consider this field first in pair. Throw away previous
3761 * one except for reference purposes. */
3762 h0->first_field = 1;
3763 h0->cur_pic_ptr = NULL;
3765 /* Second field in complementary pair */
3766 h0->first_field = 0;
3770 /* Frame or first field in a potentially complementary pair */
3771 h0->first_field = FIELD_PICTURE(h);
3774 if (!FIELD_PICTURE(h) || h0->first_field) {
3775 if (h264_frame_start(h) < 0) {
3776 h0->first_field = 0;
3777 return AVERROR_INVALIDDATA;
3780 release_unused_pictures(h, 0);
3782 /* Some macroblocks can be accessed before they're available in case
3783 * of lost slices, MBAFF or threading. */
3784 if (FIELD_PICTURE(h)) {
3785 for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
3786 memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
3788 memset(h->slice_table, -1,
3789 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
3791 h0->last_slice_type = -1;
3793 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3796 /* can't be in alloc_tables because linesize isn't known there.
3797 * FIXME: redo bipred weight to not require extra buffer? */
3798 for (i = 0; i < h->slice_context_count; i++)
3799 if (h->thread_context[i]) {
3800 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
3805 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3807 av_assert1(h->mb_num == h->mb_width * h->mb_height);
3808 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3809 first_mb_in_slice >= h->mb_num) {
3810 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3811 return AVERROR_INVALIDDATA;
3813 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3814 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3815 FIELD_OR_MBAFF_PICTURE(h);
3816 if (h->picture_structure == PICT_BOTTOM_FIELD)
3817 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3818 av_assert1(h->mb_y < h->mb_height);
3820 if (h->picture_structure == PICT_FRAME) {
3821 h->curr_pic_num = h->frame_num;
3822 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3824 h->curr_pic_num = 2 * h->frame_num + 1;
3825 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3828 if (h->nal_unit_type == NAL_IDR_SLICE)
3829 get_ue_golomb(&h->gb); /* idr_pic_id */
3831 if (h->sps.poc_type == 0) {
3832 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3834 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3835 h->delta_poc_bottom = get_se_golomb(&h->gb);
3838 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3839 h->delta_poc[0] = get_se_golomb(&h->gb);
3841 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3842 h->delta_poc[1] = get_se_golomb(&h->gb);
3845 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3847 if (h->pps.redundant_pic_cnt_present)
3848 h->redundant_pic_count = get_ue_golomb(&h->gb);
3850 ret = ff_set_ref_count(h);
3854 if (slice_type != AV_PICTURE_TYPE_I &&
3855 (h0->current_slice == 0 ||
3856 slice_type != h0->last_slice_type ||
3857 memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3859 ff_h264_fill_default_ref_list(h);
3862 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3863 ret = ff_h264_decode_ref_pic_list_reordering(h);
3865 h->ref_count[1] = h->ref_count[0] = 0;
3870 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3871 (h->pps.weighted_bipred_idc == 1 &&
3872 h->slice_type_nos == AV_PICTURE_TYPE_B))
3873 ff_pred_weight_table(h);
3874 else if (h->pps.weighted_bipred_idc == 2 &&
3875 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3876 implicit_weight_table(h, -1);
3879 for (i = 0; i < 2; i++) {
3880 h->luma_weight_flag[i] = 0;
3881 h->chroma_weight_flag[i] = 0;
3885 // If frame-mt is enabled, only update mmco tables for the first slice
3886 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3887 // or h->mmco, which will cause ref list mix-ups and decoding errors
3888 // further down the line. This may break decoding if the first slice is
3889 // corrupt, thus we only do this if frame-mt is enabled.
3890 if (h->nal_ref_idc) {
3891 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3892 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3893 h0->current_slice == 0);
3894 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3895 return AVERROR_INVALIDDATA;
3898 if (FRAME_MBAFF(h)) {
3899 ff_h264_fill_mbaff_ref_list(h);
3901 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3902 implicit_weight_table(h, 0);
3903 implicit_weight_table(h, 1);
3907 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3908 ff_h264_direct_dist_scale_factor(h);
3909 ff_h264_direct_ref_list_init(h);
3911 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3912 tmp = get_ue_golomb_31(&h->gb);
3914 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3915 return AVERROR_INVALIDDATA;
3917 h->cabac_init_idc = tmp;
3920 h->last_qscale_diff = 0;
3921 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3922 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3923 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3924 return AVERROR_INVALIDDATA;
3927 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3928 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3929 // FIXME qscale / qp ... stuff
3930 if (h->slice_type == AV_PICTURE_TYPE_SP)
3931 get_bits1(&h->gb); /* sp_for_switch_flag */
3932 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3933 h->slice_type == AV_PICTURE_TYPE_SI)
3934 get_se_golomb(&h->gb); /* slice_qs_delta */
3936 h->deblocking_filter = 1;
3937 h->slice_alpha_c0_offset = 52;
3938 h->slice_beta_offset = 52;
3939 if (h->pps.deblocking_filter_parameters_present) {
3940 tmp = get_ue_golomb_31(&h->gb);
3942 av_log(h->avctx, AV_LOG_ERROR,
3943 "deblocking_filter_idc %u out of range\n", tmp);
3944 return AVERROR_INVALIDDATA;
3946 h->deblocking_filter = tmp;
3947 if (h->deblocking_filter < 2)
3948 h->deblocking_filter ^= 1; // 1<->0
3950 if (h->deblocking_filter) {
3951 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3952 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3953 if (h->slice_alpha_c0_offset > 104U ||
3954 h->slice_beta_offset > 104U) {
3955 av_log(h->avctx, AV_LOG_ERROR,
3956 "deblocking filter parameters %d %d out of range\n",
3957 h->slice_alpha_c0_offset, h->slice_beta_offset);
3958 return AVERROR_INVALIDDATA;
3963 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
3964 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
3965 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
3966 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
3967 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
3968 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
3969 h->nal_ref_idc == 0))
3970 h->deblocking_filter = 0;
3972 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
3973 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
3974 /* Cheat slightly for speed:
3975 * Do not bother to deblock across slices. */
3976 h->deblocking_filter = 2;
3978 h0->max_contexts = 1;
3979 if (!h0->single_decode_warning) {
3980 av_log(h->avctx, AV_LOG_INFO,
3981 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
3982 h0->single_decode_warning = 1;
3985 av_log(h->avctx, AV_LOG_ERROR,
3986 "Deblocking switched inside frame.\n");
3991 h->qp_thresh = 15 + 52 -
3992 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
3994 h->pps.chroma_qp_index_offset[0],
3995 h->pps.chroma_qp_index_offset[1]) +
3996 6 * (h->sps.bit_depth_luma - 8);
3998 h0->last_slice_type = slice_type;
3999 memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
4000 h->slice_num = ++h0->current_slice;
4003 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
4004 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
4005 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
4006 && h->slice_num >= MAX_SLICES) {
4007 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
4008 av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
4011 for (j = 0; j < 2; j++) {
4013 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
4014 for (i = 0; i < 16; i++) {
4016 if (j < h->list_count && i < h->ref_count[j] &&
4017 h->ref_list[j][i].f.buf[0]) {
4019 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
4020 for (k = 0; k < h->short_ref_count; k++)
4021 if (h->short_ref[k]->f.buf[0]->buffer == buf) {
4025 for (k = 0; k < h->long_ref_count; k++)
4026 if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
4027 id_list[i] = h->short_ref_count + k;
4035 for (i = 0; i < 16; i++)
4036 ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
4038 ref2frm[18 + 1] = -1;
4039 for (i = 16; i < 48; i++)
4040 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
4041 (h->ref_list[j][i].reference & 3);
4044 if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
4045 if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
4046 h->er.ref_count = h->ref_count[0];
4048 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
4049 av_log(h->avctx, AV_LOG_DEBUG,
4050 "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",
4052 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
4054 av_get_picture_type_char(h->slice_type),
4055 h->slice_type_fixed ? " fix" : "",
4056 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
4057 pps_id, h->frame_num,
4058 h->cur_pic_ptr->field_poc[0],
4059 h->cur_pic_ptr->field_poc[1],
4060 h->ref_count[0], h->ref_count[1],
4062 h->deblocking_filter,
4063 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
4065 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
4066 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
4072 int ff_h264_get_slice_type(const H264Context *h)
4074 switch (h->slice_type) {
4075 case AV_PICTURE_TYPE_P:
4077 case AV_PICTURE_TYPE_B:
4079 case AV_PICTURE_TYPE_I:
4081 case AV_PICTURE_TYPE_SP:
4083 case AV_PICTURE_TYPE_SI:
4086 return AVERROR_INVALIDDATA;
4090 static av_always_inline void fill_filter_caches_inter(H264Context *h,
4091 int mb_type, int top_xy,
4092 int left_xy[LEFT_MBS],
4094 int left_type[LEFT_MBS],
4095 int mb_xy, int list)
4097 int b_stride = h->b_stride;
4098 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4099 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4100 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4101 if (USES_LIST(top_type, list)) {
4102 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
4103 const int b8_xy = 4 * top_xy + 2;
4104 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4105 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4106 ref_cache[0 - 1 * 8] =
4107 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4108 ref_cache[2 - 1 * 8] =
4109 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4111 AV_ZERO128(mv_dst - 1 * 8);
4112 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4115 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4116 if (USES_LIST(left_type[LTOP], list)) {
4117 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
4118 const int b8_xy = 4 * left_xy[LTOP] + 1;
4119 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4120 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4121 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4122 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4123 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4125 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4126 ref_cache[-1 + 16] =
4127 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4129 AV_ZERO32(mv_dst - 1 + 0);
4130 AV_ZERO32(mv_dst - 1 + 8);
4131 AV_ZERO32(mv_dst - 1 + 16);
4132 AV_ZERO32(mv_dst - 1 + 24);
4135 ref_cache[-1 + 16] =
4136 ref_cache[-1 + 24] = LIST_NOT_USED;
4141 if (!USES_LIST(mb_type, list)) {
4142 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4143 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4144 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4145 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4146 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4151 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4152 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4153 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4154 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4155 AV_WN32A(&ref_cache[0 * 8], ref01);
4156 AV_WN32A(&ref_cache[1 * 8], ref01);
4157 AV_WN32A(&ref_cache[2 * 8], ref23);
4158 AV_WN32A(&ref_cache[3 * 8], ref23);
4162 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4163 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4164 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4165 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4166 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4172 * @return non zero if the loop filter can be skipped
4174 static int fill_filter_caches(H264Context *h, int mb_type)
4176 const int mb_xy = h->mb_xy;
4177 int top_xy, left_xy[LEFT_MBS];
4178 int top_type, left_type[LEFT_MBS];
4182 top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4184 /* Wow, what a mess, why didn't they simplify the interlacing & intra
4185 * stuff, I can't imagine that these complex rules are worth it. */
4187 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4188 if (FRAME_MBAFF(h)) {
4189 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4190 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4192 if (left_mb_field_flag != curr_mb_field_flag)
4193 left_xy[LTOP] -= h->mb_stride;
4195 if (curr_mb_field_flag)
4196 top_xy += h->mb_stride &
4197 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4198 if (left_mb_field_flag != curr_mb_field_flag)
4199 left_xy[LBOT] += h->mb_stride;
4203 h->top_mb_xy = top_xy;
4204 h->left_mb_xy[LTOP] = left_xy[LTOP];
4205 h->left_mb_xy[LBOT] = left_xy[LBOT];
4207 /* For sufficiently low qp, filtering wouldn't do anything.
4208 * This is a conservative estimate: could also check beta_offset
4209 * and more accurate chroma_qp. */
4210 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4211 int qp = h->cur_pic.qscale_table[mb_xy];
4212 if (qp <= qp_thresh &&
4213 (left_xy[LTOP] < 0 ||
4214 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4216 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4217 if (!FRAME_MBAFF(h))
4219 if ((left_xy[LTOP] < 0 ||
4220 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4221 (top_xy < h->mb_stride ||
4222 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4227 top_type = h->cur_pic.mb_type[top_xy];
4228 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4229 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4230 if (h->deblocking_filter == 2) {
4231 if (h->slice_table[top_xy] != h->slice_num)
4233 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4234 left_type[LTOP] = left_type[LBOT] = 0;
4236 if (h->slice_table[top_xy] == 0xFFFF)
4238 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4239 left_type[LTOP] = left_type[LBOT] = 0;
4241 h->top_type = top_type;
4242 h->left_type[LTOP] = left_type[LTOP];
4243 h->left_type[LBOT] = left_type[LBOT];
4245 if (IS_INTRA(mb_type))
4248 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4249 top_type, left_type, mb_xy, 0);
4250 if (h->list_count == 2)
4251 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4252 top_type, left_type, mb_xy, 1);
4254 nnz = h->non_zero_count[mb_xy];
4255 nnz_cache = h->non_zero_count_cache;
4256 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4257 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4258 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4259 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4260 h->cbp = h->cbp_table[mb_xy];
4263 nnz = h->non_zero_count[top_xy];
4264 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4267 if (left_type[LTOP]) {
4268 nnz = h->non_zero_count[left_xy[LTOP]];
4269 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4270 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4271 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4272 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4275 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4276 * from what the loop filter needs */
4277 if (!CABAC(h) && h->pps.transform_8x8_mode) {
4278 if (IS_8x8DCT(top_type)) {
4279 nnz_cache[4 + 8 * 0] =
4280 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4281 nnz_cache[6 + 8 * 0] =
4282 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4284 if (IS_8x8DCT(left_type[LTOP])) {
4285 nnz_cache[3 + 8 * 1] =
4286 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4288 if (IS_8x8DCT(left_type[LBOT])) {
4289 nnz_cache[3 + 8 * 3] =
4290 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4293 if (IS_8x8DCT(mb_type)) {
4294 nnz_cache[scan8[0]] =
4295 nnz_cache[scan8[1]] =
4296 nnz_cache[scan8[2]] =
4297 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4299 nnz_cache[scan8[0 + 4]] =
4300 nnz_cache[scan8[1 + 4]] =
4301 nnz_cache[scan8[2 + 4]] =
4302 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4304 nnz_cache[scan8[0 + 8]] =
4305 nnz_cache[scan8[1 + 8]] =
4306 nnz_cache[scan8[2 + 8]] =
4307 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4309 nnz_cache[scan8[0 + 12]] =
4310 nnz_cache[scan8[1 + 12]] =
4311 nnz_cache[scan8[2 + 12]] =
4312 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4319 static void loop_filter(H264Context *h, int start_x, int end_x)
4321 uint8_t *dest_y, *dest_cb, *dest_cr;
4322 int linesize, uvlinesize, mb_x, mb_y;
4323 const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4324 const int old_slice_type = h->slice_type;
4325 const int pixel_shift = h->pixel_shift;
4326 const int block_h = 16 >> h->chroma_y_shift;
4328 if (h->deblocking_filter) {
4329 for (mb_x = start_x; mb_x < end_x; mb_x++)
4330 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4332 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4333 h->slice_num = h->slice_table[mb_xy];
4334 mb_type = h->cur_pic.mb_type[mb_xy];
4335 h->list_count = h->list_counts[mb_xy];
4339 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4343 dest_y = h->cur_pic.f.data[0] +
4344 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4345 dest_cb = h->cur_pic.f.data[1] +
4346 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4347 mb_y * h->uvlinesize * block_h;
4348 dest_cr = h->cur_pic.f.data[2] +
4349 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4350 mb_y * h->uvlinesize * block_h;
4351 // FIXME simplify above
4354 linesize = h->mb_linesize = h->linesize * 2;
4355 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4356 if (mb_y & 1) { // FIXME move out of this function?
4357 dest_y -= h->linesize * 15;
4358 dest_cb -= h->uvlinesize * (block_h - 1);
4359 dest_cr -= h->uvlinesize * (block_h - 1);
4362 linesize = h->mb_linesize = h->linesize;
4363 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4365 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4367 if (fill_filter_caches(h, mb_type))
4369 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4370 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4372 if (FRAME_MBAFF(h)) {
4373 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4374 linesize, uvlinesize);
4376 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4377 dest_cr, linesize, uvlinesize);
4381 h->slice_type = old_slice_type;
4383 h->mb_y = end_mb_y - FRAME_MBAFF(h);
4384 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4385 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4388 static void predict_field_decoding_flag(H264Context *h)
4390 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4391 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4392 h->cur_pic.mb_type[mb_xy - 1] :
4393 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4394 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4395 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4399 * Draw edges and report progress for the last MB row.
4401 static void decode_finish_row(H264Context *h)
4403 int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4404 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4405 int height = 16 << FRAME_MBAFF(h);
4406 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4408 if (h->deblocking_filter) {
4409 if ((top + height) >= pic_height)
4410 height += deblock_border;
4411 top -= deblock_border;
4414 if (top >= pic_height || (top + height) < 0)
4417 height = FFMIN(height, pic_height - top);
4419 height = top + height;
4423 ff_h264_draw_horiz_band(h, top, height);
4425 if (h->droppable || h->er.error_occurred)
4428 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4429 h->picture_structure == PICT_BOTTOM_FIELD);
4432 static void er_add_slice(H264Context *h, int startx, int starty,
4433 int endx, int endy, int status)
4435 if (CONFIG_ERROR_RESILIENCE) {
4436 ERContext *er = &h->er;
4438 ff_er_add_slice(er, startx, starty, endx, endy, status);
4442 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4444 H264Context *h = *(void **)arg;
4445 int lf_x_start = h->mb_x;
4447 h->mb_skip_run = -1;
4449 av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4451 h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4452 avctx->codec_id != AV_CODEC_ID_H264 ||
4453 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4455 if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
4456 const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
4458 int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
4459 prev_status &= ~ VP_START;
4460 if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
4461 h->er.error_occurred = 1;
4467 align_get_bits(&h->gb);
4470 ff_init_cabac_decoder(&h->cabac,
4471 h->gb.buffer + get_bits_count(&h->gb) / 8,
4472 (get_bits_left(&h->gb) + 7) / 8);
4474 ff_h264_init_cabac_states(h);
4478 int ret = ff_h264_decode_mb_cabac(h);
4480 // STOP_TIMER("decode_mb_cabac")
4483 ff_h264_hl_decode_mb(h);
4485 // FIXME optimal? or let mb_decode decode 16x32 ?
4486 if (ret >= 0 && FRAME_MBAFF(h)) {
4489 ret = ff_h264_decode_mb_cabac(h);
4492 ff_h264_hl_decode_mb(h);
4495 eos = get_cabac_terminate(&h->cabac);
4497 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4498 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4499 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4500 h->mb_y, ER_MB_END);
4501 if (h->mb_x >= lf_x_start)
4502 loop_filter(h, lf_x_start, h->mb_x + 1);
4505 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4506 av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4507 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4508 av_log(h->avctx, AV_LOG_ERROR,
4509 "error while decoding MB %d %d, bytestream (%td)\n",
4511 h->cabac.bytestream_end - h->cabac.bytestream);
4512 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4513 h->mb_y, ER_MB_ERROR);
4514 return AVERROR_INVALIDDATA;
4517 if (++h->mb_x >= h->mb_width) {
4518 loop_filter(h, lf_x_start, h->mb_x);
4519 h->mb_x = lf_x_start = 0;
4520 decode_finish_row(h);
4522 if (FIELD_OR_MBAFF_PICTURE(h)) {
4524 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4525 predict_field_decoding_flag(h);
4529 if (eos || h->mb_y >= h->mb_height) {
4530 tprintf(h->avctx, "slice end %d %d\n",
4531 get_bits_count(&h->gb), h->gb.size_in_bits);
4532 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4533 h->mb_y, ER_MB_END);
4534 if (h->mb_x > lf_x_start)
4535 loop_filter(h, lf_x_start, h->mb_x);
4541 int ret = ff_h264_decode_mb_cavlc(h);
4544 ff_h264_hl_decode_mb(h);
4546 // FIXME optimal? or let mb_decode decode 16x32 ?
4547 if (ret >= 0 && FRAME_MBAFF(h)) {
4549 ret = ff_h264_decode_mb_cavlc(h);
4552 ff_h264_hl_decode_mb(h);
4557 av_log(h->avctx, AV_LOG_ERROR,
4558 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4559 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4560 h->mb_y, ER_MB_ERROR);
4564 if (++h->mb_x >= h->mb_width) {
4565 loop_filter(h, lf_x_start, h->mb_x);
4566 h->mb_x = lf_x_start = 0;
4567 decode_finish_row(h);
4569 if (FIELD_OR_MBAFF_PICTURE(h)) {
4571 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4572 predict_field_decoding_flag(h);
4574 if (h->mb_y >= h->mb_height) {
4575 tprintf(h->avctx, "slice end %d %d\n",
4576 get_bits_count(&h->gb), h->gb.size_in_bits);
4578 if ( get_bits_left(&h->gb) == 0
4579 || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4580 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4581 h->mb_x - 1, h->mb_y,
4586 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4590 return AVERROR_INVALIDDATA;
4595 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4596 tprintf(h->avctx, "slice end %d %d\n",
4597 get_bits_count(&h->gb), h->gb.size_in_bits);
4599 if (get_bits_left(&h->gb) == 0) {
4600 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4601 h->mb_x - 1, h->mb_y,
4603 if (h->mb_x > lf_x_start)
4604 loop_filter(h, lf_x_start, h->mb_x);
4608 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4609 h->mb_y, ER_MB_ERROR);
4611 return AVERROR_INVALIDDATA;
4619 * Call decode_slice() for each context.
4621 * @param h h264 master context
4622 * @param context_count number of contexts to execute
4624 static int execute_decode_slices(H264Context *h, int context_count)
4626 AVCodecContext *const avctx = h->avctx;
4630 if (h->avctx->hwaccel ||
4631 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4633 if (context_count == 1) {
4634 return decode_slice(avctx, &h);
4636 av_assert0(context_count > 0);
4637 for (i = 1; i < context_count; i++) {
4638 hx = h->thread_context[i];
4639 if (CONFIG_ERROR_RESILIENCE) {
4640 hx->er.error_count = 0;
4642 hx->x264_build = h->x264_build;
4645 avctx->execute(avctx, decode_slice, h->thread_context,
4646 NULL, context_count, sizeof(void *));
4648 /* pull back stuff from slices to master context */
4649 hx = h->thread_context[context_count - 1];
4652 h->droppable = hx->droppable;
4653 h->picture_structure = hx->picture_structure;
4654 if (CONFIG_ERROR_RESILIENCE) {
4655 for (i = 1; i < context_count; i++)
4656 h->er.error_count += h->thread_context[i]->er.error_count;
4663 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
4665 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4666 int parse_extradata)
4668 AVCodecContext *const avctx = h->avctx;
4669 H264Context *hx; ///< thread context
4673 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4674 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4677 int first_slice = 0;
4680 h->nal_unit_type= 0;
4682 if(!h->slice_context_count)
4683 h->slice_context_count= 1;
4684 h->max_contexts = h->slice_context_count;
4685 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4686 h->current_slice = 0;
4687 if (!h->first_field)
4688 h->cur_pic_ptr = NULL;
4689 ff_h264_reset_sei(h);
4692 if (h->nal_length_size == 4) {
4693 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4695 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4699 for (; pass <= 1; pass++) {
4702 next_avc = h->is_avc ? 0 : buf_size;
4712 if (buf_index >= next_avc) {
4713 if (buf_index >= buf_size - h->nal_length_size)
4716 for (i = 0; i < h->nal_length_size; i++)
4717 nalsize = (nalsize << 8) | buf[buf_index++];
4718 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4719 av_log(h->avctx, AV_LOG_ERROR,
4720 "AVC: nal size %d\n", nalsize);
4723 next_avc = buf_index + nalsize;
4725 // start code prefix search
4726 for (; buf_index + 3 < next_avc; buf_index++)
4727 // This should always succeed in the first iteration.
4728 if (buf[buf_index] == 0 &&
4729 buf[buf_index + 1] == 0 &&
4730 buf[buf_index + 2] == 1)
4733 if (buf_index + 3 >= buf_size) {
4734 buf_index = buf_size;
4739 if (buf_index >= next_avc)
4743 hx = h->thread_context[context_count];
4745 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4746 &consumed, next_avc - buf_index);
4747 if (ptr == NULL || dst_length < 0) {
4751 i = buf_index + consumed;
4752 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4753 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4754 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4755 h->workaround_bugs |= FF_BUG_TRUNCATED;
4757 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4758 while(dst_length > 0 && ptr[dst_length - 1] == 0)
4760 bit_length = !dst_length ? 0
4762 decode_rbsp_trailing(h, ptr + dst_length - 1));
4764 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4765 av_log(h->avctx, AV_LOG_DEBUG,
4766 "NAL %d/%d at %d/%d length %d pass %d\n",
4767 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
4769 if (h->is_avc && (nalsize != consumed) && nalsize)
4770 av_log(h->avctx, AV_LOG_DEBUG,
4771 "AVC: Consumed only %d bytes instead of %d\n",
4774 buf_index += consumed;
4778 /* packets can sometimes contain multiple PPS/SPS,
4779 * e.g. two PAFF field pictures in one packet, or a demuxer
4780 * which splits NALs strangely if so, when frame threading we
4781 * can't start the next thread until we've read all of them */
4782 switch (hx->nal_unit_type) {
4785 nals_needed = nal_index;
4790 init_get_bits(&hx->gb, ptr, bit_length);
4791 if (!get_ue_golomb(&hx->gb) || !first_slice)
4792 nals_needed = nal_index;
4794 first_slice = hx->nal_unit_type;
4800 switch (hx->nal_unit_type) {
4804 first_slice = hx->nal_unit_type;
4807 if (avctx->skip_frame >= AVDISCARD_NONREF &&
4808 h->nal_ref_idc == 0 &&
4809 h->nal_unit_type != NAL_SEI)
4813 /* Ignore per frame NAL unit type during extradata
4814 * parsing. Decoding slices is not possible in codec init
4816 if (parse_extradata) {
4817 switch (hx->nal_unit_type) {
4823 av_log(h->avctx, AV_LOG_WARNING,
4824 "Ignoring NAL %d in global header/extradata\n",
4826 // fall through to next case
4827 case NAL_AUXILIARY_SLICE:
4828 hx->nal_unit_type = NAL_FF_IGNORE;
4834 switch (hx->nal_unit_type) {
4836 if (first_slice != NAL_IDR_SLICE) {
4837 av_log(h->avctx, AV_LOG_ERROR,
4838 "Invalid mix of idr and non-idr slices\n");
4843 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4846 init_get_bits(&hx->gb, ptr, bit_length);
4848 hx->inter_gb_ptr = &hx->gb;
4849 hx->data_partitioning = 0;
4851 if ((err = decode_slice_header(hx, h)))
4854 if (h->sei_recovery_frame_cnt >= 0) {
4855 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
4856 h->valid_recovery_point = 1;
4858 if ( h->recovery_frame < 0
4859 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
4860 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4861 ((1 << h->sps.log2_max_frame_num) - 1);
4863 if (!h->valid_recovery_point)
4864 h->recovery_frame = h->frame_num;
4868 h->cur_pic_ptr->f.key_frame |=
4869 (hx->nal_unit_type == NAL_IDR_SLICE);
4871 if (hx->nal_unit_type == NAL_IDR_SLICE ||
4872 h->recovery_frame == h->frame_num) {
4873 h->recovery_frame = -1;
4874 h->cur_pic_ptr->recovered = 1;
4876 // If we have an IDR, all frames after it in decoded order are
4878 if (hx->nal_unit_type == NAL_IDR_SLICE)
4879 h->frame_recovered |= FRAME_RECOVERED_IDR;
4880 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
4881 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
4883 h->cur_pic_ptr->recovered |= h->frame_recovered;
4885 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
4888 if (h->current_slice == 1) {
4889 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4890 decode_postinit(h, nal_index >= nals_needed);
4892 if (h->avctx->hwaccel &&
4893 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4895 if (CONFIG_H264_VDPAU_DECODER &&
4896 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4897 ff_vdpau_h264_picture_start(h);
4900 if (hx->redundant_pic_count == 0 &&
4901 (avctx->skip_frame < AVDISCARD_NONREF ||
4903 (avctx->skip_frame < AVDISCARD_BIDIR ||
4904 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4905 (avctx->skip_frame < AVDISCARD_NONKEY ||
4906 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4907 avctx->skip_frame < AVDISCARD_ALL) {
4908 if (avctx->hwaccel) {
4909 ret = avctx->hwaccel->decode_slice(avctx,
4910 &buf[buf_index - consumed],
4914 } else if (CONFIG_H264_VDPAU_DECODER &&
4915 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4916 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4918 sizeof(start_code));
4919 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4920 &buf[buf_index - consumed],
4927 init_get_bits(&hx->gb, ptr, bit_length);
4929 hx->inter_gb_ptr = NULL;
4931 if ((err = decode_slice_header(hx, h)) < 0)
4934 hx->data_partitioning = 1;
4937 init_get_bits(&hx->intra_gb, ptr, bit_length);
4938 hx->intra_gb_ptr = &hx->intra_gb;
4941 init_get_bits(&hx->inter_gb, ptr, bit_length);
4942 hx->inter_gb_ptr = &hx->inter_gb;
4944 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
4947 if (hx->redundant_pic_count == 0 &&
4949 hx->data_partitioning &&
4950 h->cur_pic_ptr && h->context_initialized &&
4951 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4952 (avctx->skip_frame < AVDISCARD_BIDIR ||
4953 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4954 (avctx->skip_frame < AVDISCARD_NONKEY ||
4955 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4956 avctx->skip_frame < AVDISCARD_ALL)
4960 init_get_bits(&h->gb, ptr, bit_length);
4961 ff_h264_decode_sei(h);
4964 init_get_bits(&h->gb, ptr, bit_length);
4965 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
4966 av_log(h->avctx, AV_LOG_DEBUG,
4967 "SPS decoding failure, trying again with the complete NAL\n");
4969 av_assert0(next_avc - buf_index + consumed == nalsize);
4970 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
4972 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
4973 8*(next_avc - buf_index + consumed - 1));
4974 ff_h264_decode_seq_parameter_set(h);
4979 init_get_bits(&h->gb, ptr, bit_length);
4980 ff_h264_decode_picture_parameter_set(h, bit_length);
4983 case NAL_END_SEQUENCE:
4984 case NAL_END_STREAM:
4985 case NAL_FILLER_DATA:
4987 case NAL_AUXILIARY_SLICE:
4992 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
4993 hx->nal_unit_type, bit_length);
4996 if (context_count == h->max_contexts) {
4997 execute_decode_slices(h, context_count);
5002 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
5003 else if (err == 1) {
5004 /* Slice could not be decoded in parallel mode, copy down
5005 * NAL unit stuff to context 0 and restart. Note that
5006 * rbsp_buffer is not transferred, but since we no longer
5007 * run in parallel mode this should not be an issue. */
5008 h->nal_unit_type = hx->nal_unit_type;
5009 h->nal_ref_idc = hx->nal_ref_idc;
5016 execute_decode_slices(h, context_count);
5020 if (h->cur_pic_ptr && !h->droppable) {
5021 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
5022 h->picture_structure == PICT_BOTTOM_FIELD);
5025 return (ret < 0) ? ret : buf_index;
5029 * Return the number of bytes consumed for building the current frame.
5031 static int get_consumed_bytes(int pos, int buf_size)
5034 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
5035 if (pos + 10 > buf_size)
5036 pos = buf_size; // oops ;)
5041 static int output_frame(H264Context *h, AVFrame *dst, Picture *srcp)
5043 AVFrame *src = &srcp->f;
5045 int ret = av_frame_ref(dst, src);
5049 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
5054 for (i = 0; i < 3; i++) {
5055 int hshift = (i > 0) ? h->chroma_x_shift : 0;
5056 int vshift = (i > 0) ? h->chroma_y_shift : 0;
5057 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
5058 (srcp->crop_top >> vshift) * dst->linesize[i];
5059 dst->data[i] += off;
5064 static int decode_frame(AVCodecContext *avctx, void *data,
5065 int *got_frame, AVPacket *avpkt)
5067 const uint8_t *buf = avpkt->data;
5068 int buf_size = avpkt->size;
5069 H264Context *h = avctx->priv_data;
5070 AVFrame *pict = data;
5076 h->flags = avctx->flags;
5078 /* end of stream, output what is still in the buffers */
5079 if (buf_size == 0) {
5082 h->cur_pic_ptr = NULL;
5085 // FIXME factorize this with the output code below
5086 out = h->delayed_pic[0];
5089 h->delayed_pic[i] &&
5090 !h->delayed_pic[i]->f.key_frame &&
5091 !h->delayed_pic[i]->mmco_reset;
5093 if (h->delayed_pic[i]->poc < out->poc) {
5094 out = h->delayed_pic[i];
5098 for (i = out_idx; h->delayed_pic[i]; i++)
5099 h->delayed_pic[i] = h->delayed_pic[i + 1];
5102 out->reference &= ~DELAYED_PIC_REF;
5103 ret = output_frame(h, pict, out);
5111 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
5112 int cnt= buf[5]&0x1f;
5113 const uint8_t *p= buf+6;
5115 int nalsize= AV_RB16(p) + 2;
5116 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
5124 int nalsize= AV_RB16(p) + 2;
5125 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
5130 return ff_h264_decode_extradata(h, buf, buf_size);
5134 buf_index = decode_nal_units(h, buf, buf_size, 0);
5136 return AVERROR_INVALIDDATA;
5138 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
5139 av_assert0(buf_index <= buf_size);
5143 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
5144 if (avctx->skip_frame >= AVDISCARD_NONREF ||
5145 buf_size >= 4 && !memcmp("Q264", buf, 4))
5147 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
5148 return AVERROR_INVALIDDATA;
5151 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
5152 (h->mb_y >= h->mb_height && h->mb_height)) {
5153 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
5154 decode_postinit(h, 1);
5158 /* Wait for second field. */
5160 if (h->next_output_pic && (
5161 h->next_output_pic->recovered)) {
5162 if (!h->next_output_pic->recovered)
5163 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
5165 ret = output_frame(h, pict, h->next_output_pic);
5169 if (CONFIG_MPEGVIDEO) {
5170 ff_print_debug_info2(h->avctx, h->next_output_pic, pict, h->er.mbskip_table,
5172 h->mb_width, h->mb_height, h->mb_stride, 1);
5177 assert(pict->buf[0] || !*got_frame);
5179 return get_consumed_bytes(buf_index, buf_size);
5182 av_cold void ff_h264_free_context(H264Context *h)
5186 free_tables(h, 1); // FIXME cleanup init stuff perhaps
5188 for (i = 0; i < MAX_SPS_COUNT; i++)
5189 av_freep(h->sps_buffers + i);
5191 for (i = 0; i < MAX_PPS_COUNT; i++)
5192 av_freep(h->pps_buffers + i);
5195 static av_cold int h264_decode_end(AVCodecContext *avctx)
5197 H264Context *h = avctx->priv_data;
5199 ff_h264_remove_all_refs(h);
5200 ff_h264_free_context(h);
5202 unref_picture(h, &h->cur_pic);
5207 static const AVProfile profiles[] = {
5208 { FF_PROFILE_H264_BASELINE, "Baseline" },
5209 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
5210 { FF_PROFILE_H264_MAIN, "Main" },
5211 { FF_PROFILE_H264_EXTENDED, "Extended" },
5212 { FF_PROFILE_H264_HIGH, "High" },
5213 { FF_PROFILE_H264_HIGH_10, "High 10" },
5214 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
5215 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
5216 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
5217 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
5218 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
5219 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
5220 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
5221 { FF_PROFILE_UNKNOWN },
5224 static const AVOption h264_options[] = {
5225 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
5226 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
5230 static const AVClass h264_class = {
5231 .class_name = "H264 Decoder",
5232 .item_name = av_default_item_name,
5233 .option = h264_options,
5234 .version = LIBAVUTIL_VERSION_INT,
5237 static const AVClass h264_vdpau_class = {
5238 .class_name = "H264 VDPAU Decoder",
5239 .item_name = av_default_item_name,
5240 .option = h264_options,
5241 .version = LIBAVUTIL_VERSION_INT,
5244 AVCodec ff_h264_decoder = {
5246 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5247 .type = AVMEDIA_TYPE_VIDEO,
5248 .id = AV_CODEC_ID_H264,
5249 .priv_data_size = sizeof(H264Context),
5250 .init = ff_h264_decode_init,
5251 .close = h264_decode_end,
5252 .decode = decode_frame,
5253 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5254 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
5255 CODEC_CAP_FRAME_THREADS,
5257 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
5258 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5259 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5260 .priv_class = &h264_class,
5263 #if CONFIG_H264_VDPAU_DECODER
5264 AVCodec ff_h264_vdpau_decoder = {
5265 .name = "h264_vdpau",
5266 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
5267 .type = AVMEDIA_TYPE_VIDEO,
5268 .id = AV_CODEC_ID_H264,
5269 .priv_data_size = sizeof(H264Context),
5270 .init = ff_h264_decode_init,
5271 .close = h264_decode_end,
5272 .decode = decode_frame,
5273 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5275 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
5277 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5278 .priv_class = &h264_vdpau_class,