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"
33 #include "libavutil/stereo3d.h"
34 #include "libavutil/timer.h"
37 #include "cabac_functions.h"
39 #include "error_resilience.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
47 #include "mpegutils.h"
48 #include "rectangle.h"
51 #include "vdpau_internal.h"
55 static void flush_change(H264Context *h);
57 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
59 static const uint8_t rem6[QP_MAX_NUM + 1] = {
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,
62 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
63 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
67 static const uint8_t div6[QP_MAX_NUM + 1] = {
68 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
69 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
70 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
71 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
75 static const uint8_t field_scan[16+1] = {
76 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
77 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
78 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
79 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
82 static const uint8_t field_scan8x8[64+1] = {
83 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
84 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
85 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
86 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
87 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
88 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
89 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
90 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
91 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
92 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
93 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
94 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
95 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
96 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
97 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
98 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
101 static const uint8_t field_scan8x8_cavlc[64+1] = {
102 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
103 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
104 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
105 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
106 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
107 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
108 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
109 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
110 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
111 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
112 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
113 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
114 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
115 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
116 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
117 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
120 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
121 static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
122 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
123 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
124 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
125 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
126 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
127 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
128 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
129 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
130 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
131 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
132 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
133 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
134 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
135 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
136 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
137 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
140 static const uint8_t dequant4_coeff_init[6][3] = {
149 static const uint8_t dequant8_coeff_init_scan[16] = {
150 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
153 static const uint8_t dequant8_coeff_init[6][6] = {
154 { 20, 18, 32, 19, 25, 24 },
155 { 22, 19, 35, 21, 28, 26 },
156 { 26, 23, 42, 24, 33, 31 },
157 { 28, 25, 45, 26, 35, 33 },
158 { 32, 28, 51, 30, 40, 38 },
159 { 36, 32, 58, 34, 46, 43 },
162 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
163 #if CONFIG_H264_DXVA2_HWACCEL
164 AV_PIX_FMT_DXVA2_VLD,
166 #if CONFIG_H264_VAAPI_HWACCEL
167 AV_PIX_FMT_VAAPI_VLD,
169 #if CONFIG_H264_VDA_HWACCEL
172 #if CONFIG_H264_VDPAU_HWACCEL
179 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
180 #if CONFIG_H264_DXVA2_HWACCEL
181 AV_PIX_FMT_DXVA2_VLD,
183 #if CONFIG_H264_VAAPI_HWACCEL
184 AV_PIX_FMT_VAAPI_VLD,
186 #if CONFIG_H264_VDA_HWACCEL
189 #if CONFIG_H264_VDPAU_HWACCEL
196 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
198 H264Context *h = avctx->priv_data;
199 return h ? h->sps.num_reorder_frames : 0;
202 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
204 int mb_x, int mb_y, int mb_intra, int mb_skipped)
206 H264Context *h = opaque;
210 h->mb_xy = mb_x + mb_y * h->mb_stride;
211 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
212 av_assert1(ref >= 0);
213 /* FIXME: It is possible albeit uncommon that slice references
214 * differ between slices. We take the easy approach and ignore
215 * it for now. If this turns out to have any relevance in
216 * practice then correct remapping should be added. */
217 if (ref >= h->ref_count[0])
219 if (!h->ref_list[0][ref].f.data[0]) {
220 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
223 if ((h->ref_list[0][ref].reference&3) != 3) {
224 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
227 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
229 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
230 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
231 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
233 h->mb_field_decoding_flag = 0;
234 ff_h264_hl_decode_mb(h);
237 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
239 AVCodecContext *avctx = h->avctx;
240 AVFrame *cur = &h->cur_pic.f;
241 AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
242 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
243 int vshift = desc->log2_chroma_h;
244 const int field_pic = h->picture_structure != PICT_FRAME;
250 height = FFMIN(height, avctx->height - y);
252 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
255 if (avctx->draw_horiz_band) {
257 int offset[AV_NUM_DATA_POINTERS];
260 if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
261 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
268 offset[0] = y * src->linesize[0];
270 offset[2] = (y >> vshift) * src->linesize[1];
271 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
276 avctx->draw_horiz_band(avctx, src, offset,
277 y, h->picture_structure, height);
281 static void unref_picture(H264Context *h, H264Picture *pic)
283 int off = offsetof(H264Picture, tf) + sizeof(pic->tf);
289 ff_thread_release_buffer(h->avctx, &pic->tf);
290 av_buffer_unref(&pic->hwaccel_priv_buf);
292 av_buffer_unref(&pic->qscale_table_buf);
293 av_buffer_unref(&pic->mb_type_buf);
294 for (i = 0; i < 2; i++) {
295 av_buffer_unref(&pic->motion_val_buf[i]);
296 av_buffer_unref(&pic->ref_index_buf[i]);
299 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
302 static void release_unused_pictures(H264Context *h, int remove_current)
306 /* release non reference frames */
307 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
308 if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
309 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
310 unref_picture(h, &h->DPB[i]);
315 static int ref_picture(H264Context *h, H264Picture *dst, H264Picture *src)
319 av_assert0(!dst->f.buf[0]);
320 av_assert0(src->f.buf[0]);
324 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
328 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
329 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
330 if (!dst->qscale_table_buf || !dst->mb_type_buf)
332 dst->qscale_table = src->qscale_table;
333 dst->mb_type = src->mb_type;
335 for (i = 0; i < 2; i++) {
336 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
337 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
338 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
340 dst->motion_val[i] = src->motion_val[i];
341 dst->ref_index[i] = src->ref_index[i];
344 if (src->hwaccel_picture_private) {
345 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
346 if (!dst->hwaccel_priv_buf)
348 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
351 for (i = 0; i < 2; i++)
352 dst->field_poc[i] = src->field_poc[i];
354 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
355 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
358 dst->frame_num = src->frame_num;
359 dst->mmco_reset = src->mmco_reset;
360 dst->pic_id = src->pic_id;
361 dst->long_ref = src->long_ref;
362 dst->mbaff = src->mbaff;
363 dst->field_picture = src->field_picture;
364 dst->needs_realloc = src->needs_realloc;
365 dst->reference = src->reference;
366 dst->crop = src->crop;
367 dst->crop_left = src->crop_left;
368 dst->crop_top = src->crop_top;
369 dst->recovered = src->recovered;
370 dst->invalid_gap = src->invalid_gap;
374 unref_picture(h, dst);
378 static int alloc_scratch_buffers(H264Context *h, int linesize)
380 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
382 if (h->bipred_scratchpad)
385 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
386 // edge emu needs blocksize + filter length - 1
387 // (= 21x21 for h264)
388 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
390 if (!h->bipred_scratchpad || !h->edge_emu_buffer) {
391 av_freep(&h->bipred_scratchpad);
392 av_freep(&h->edge_emu_buffer);
393 return AVERROR(ENOMEM);
399 static int init_table_pools(H264Context *h)
401 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
402 const int mb_array_size = h->mb_stride * h->mb_height;
403 const int b4_stride = h->mb_width * 4 + 1;
404 const int b4_array_size = b4_stride * h->mb_height * 4;
406 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
408 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
409 sizeof(uint32_t), av_buffer_allocz);
410 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
411 sizeof(int16_t), av_buffer_allocz);
412 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
414 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
415 !h->ref_index_pool) {
416 av_buffer_pool_uninit(&h->qscale_table_pool);
417 av_buffer_pool_uninit(&h->mb_type_pool);
418 av_buffer_pool_uninit(&h->motion_val_pool);
419 av_buffer_pool_uninit(&h->ref_index_pool);
420 return AVERROR(ENOMEM);
426 static int alloc_picture(H264Context *h, H264Picture *pic)
430 av_assert0(!pic->f.data[0]);
433 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
434 AV_GET_BUFFER_FLAG_REF : 0);
438 h->linesize = pic->f.linesize[0];
439 h->uvlinesize = pic->f.linesize[1];
440 pic->crop = h->sps.crop;
441 pic->crop_top = h->sps.crop_top;
442 pic->crop_left= h->sps.crop_left;
444 if (h->avctx->hwaccel) {
445 const AVHWAccel *hwaccel = h->avctx->hwaccel;
446 av_assert0(!pic->hwaccel_picture_private);
447 if (hwaccel->priv_data_size) {
448 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
449 if (!pic->hwaccel_priv_buf)
450 return AVERROR(ENOMEM);
451 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
454 if (!h->avctx->hwaccel && CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY && pic->f.data[2]) {
455 int h_chroma_shift, v_chroma_shift;
456 av_pix_fmt_get_chroma_sub_sample(pic->f.format,
457 &h_chroma_shift, &v_chroma_shift);
459 for(i=0; i<FF_CEIL_RSHIFT(h->avctx->height, v_chroma_shift); i++) {
460 memset(pic->f.data[1] + pic->f.linesize[1]*i,
461 0x80, FF_CEIL_RSHIFT(h->avctx->width, h_chroma_shift));
462 memset(pic->f.data[2] + pic->f.linesize[2]*i,
463 0x80, FF_CEIL_RSHIFT(h->avctx->width, h_chroma_shift));
467 if (!h->qscale_table_pool) {
468 ret = init_table_pools(h);
473 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
474 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
475 if (!pic->qscale_table_buf || !pic->mb_type_buf)
478 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
479 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
481 for (i = 0; i < 2; i++) {
482 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
483 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
484 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
487 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
488 pic->ref_index[i] = pic->ref_index_buf[i]->data;
493 unref_picture(h, pic);
494 return (ret < 0) ? ret : AVERROR(ENOMEM);
497 static inline int pic_is_unused(H264Context *h, H264Picture *pic)
501 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
506 static int find_unused_picture(H264Context *h)
510 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
511 if (pic_is_unused(h, &h->DPB[i]))
514 if (i == H264_MAX_PICTURE_COUNT)
515 return AVERROR_INVALIDDATA;
517 if (h->DPB[i].needs_realloc) {
518 h->DPB[i].needs_realloc = 0;
519 unref_picture(h, &h->DPB[i]);
526 * Check if the top & left blocks are available if needed and
527 * change the dc mode so it only uses the available blocks.
529 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
531 static const int8_t top[12] = {
532 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
534 static const int8_t left[12] = {
535 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
539 if (!(h->top_samples_available & 0x8000)) {
540 for (i = 0; i < 4; i++) {
541 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
543 av_log(h->avctx, AV_LOG_ERROR,
544 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
545 status, h->mb_x, h->mb_y);
546 return AVERROR_INVALIDDATA;
548 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
553 if ((h->left_samples_available & 0x8888) != 0x8888) {
554 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
555 for (i = 0; i < 4; i++)
556 if (!(h->left_samples_available & mask[i])) {
557 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
559 av_log(h->avctx, AV_LOG_ERROR,
560 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
561 status, h->mb_x, h->mb_y);
562 return AVERROR_INVALIDDATA;
564 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
570 } // FIXME cleanup like ff_h264_check_intra_pred_mode
573 * Check if the top & left blocks are available if needed and
574 * change the dc mode so it only uses the available blocks.
576 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
578 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
579 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
582 av_log(h->avctx, AV_LOG_ERROR,
583 "out of range intra chroma pred mode at %d %d\n",
585 return AVERROR_INVALIDDATA;
588 if (!(h->top_samples_available & 0x8000)) {
591 av_log(h->avctx, AV_LOG_ERROR,
592 "top block unavailable for requested intra mode at %d %d\n",
594 return AVERROR_INVALIDDATA;
598 if ((h->left_samples_available & 0x8080) != 0x8080) {
600 if (is_chroma && (h->left_samples_available & 0x8080)) {
601 // mad cow disease mode, aka MBAFF + constrained_intra_pred
602 mode = ALZHEIMER_DC_L0T_PRED8x8 +
603 (!(h->left_samples_available & 0x8000)) +
604 2 * (mode == DC_128_PRED8x8);
607 av_log(h->avctx, AV_LOG_ERROR,
608 "left block unavailable for requested intra mode at %d %d\n",
610 return AVERROR_INVALIDDATA;
617 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
618 int *dst_length, int *consumed, int length)
624 // src[0]&0x80; // forbidden bit
625 h->nal_ref_idc = src[0] >> 5;
626 h->nal_unit_type = src[0] & 0x1F;
631 #define STARTCODE_TEST \
632 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
633 if (src[i + 2] != 3) { \
634 /* startcode, so we must be past the end */ \
640 #if HAVE_FAST_UNALIGNED
641 #define FIND_FIRST_ZERO \
642 if (i > 0 && !src[i]) \
648 for (i = 0; i + 1 < length; i += 9) {
649 if (!((~AV_RN64A(src + i) &
650 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
651 0x8000800080008080ULL))
658 for (i = 0; i + 1 < length; i += 5) {
659 if (!((~AV_RN32A(src + i) &
660 (AV_RN32A(src + i) - 0x01000101U)) &
669 for (i = 0; i + 1 < length; i += 2) {
672 if (i > 0 && src[i - 1] == 0)
678 // use second escape buffer for inter data
679 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
681 si = h->rbsp_buffer_size[bufidx];
682 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
683 dst = h->rbsp_buffer[bufidx];
688 if(i>=length-1){ //no escaped 0
690 *consumed= length+1; //+1 for the header
691 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
694 memcpy(dst, src, length);
701 while (si + 2 < length) {
702 // remove escapes (very rare 1:2^22)
703 if (src[si + 2] > 3) {
704 dst[di++] = src[si++];
705 dst[di++] = src[si++];
706 } else if (src[si] == 0 && src[si + 1] == 0) {
707 if (src[si + 2] == 3) { // escape
712 } else // next start code
716 dst[di++] = src[si++];
719 dst[di++] = src[si++];
722 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
725 *consumed = si + 1; // +1 for the header
726 /* FIXME store exact number of bits in the getbitcontext
727 * (it is needed for decoding) */
732 * Identify the exact end of the bitstream
733 * @return the length of the trailing, or 0 if damaged
735 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
740 tprintf(h->avctx, "rbsp trailing %X\n", v);
742 for (r = 1; r < 9; r++) {
750 static inline int get_lowest_part_list_y(H264Context *h, H264Picture *pic, int n,
751 int height, int y_offset, int list)
753 int raw_my = h->mv_cache[list][scan8[n]][1];
754 int filter_height_down = (raw_my & 3) ? 3 : 0;
755 int full_my = (raw_my >> 2) + y_offset;
756 int bottom = full_my + filter_height_down + height;
758 av_assert2(height >= 0);
760 return FFMAX(0, bottom);
763 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
764 int height, int y_offset, int list0,
765 int list1, int *nrefs)
769 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
772 int ref_n = h->ref_cache[0][scan8[n]];
773 H264Picture *ref = &h->ref_list[0][ref_n];
775 // Error resilience puts the current picture in the ref list.
776 // Don't try to wait on these as it will cause a deadlock.
777 // Fields can wait on each other, though.
778 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
779 (ref->reference & 3) != h->picture_structure) {
780 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
781 if (refs[0][ref_n] < 0)
783 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
788 int ref_n = h->ref_cache[1][scan8[n]];
789 H264Picture *ref = &h->ref_list[1][ref_n];
791 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
792 (ref->reference & 3) != h->picture_structure) {
793 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
794 if (refs[1][ref_n] < 0)
796 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
802 * Wait until all reference frames are available for MC operations.
804 * @param h the H264 context
806 static void await_references(H264Context *h)
808 const int mb_xy = h->mb_xy;
809 const int mb_type = h->cur_pic.mb_type[mb_xy];
811 int nrefs[2] = { 0 };
814 memset(refs, -1, sizeof(refs));
816 if (IS_16X16(mb_type)) {
817 get_lowest_part_y(h, refs, 0, 16, 0,
818 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
819 } else if (IS_16X8(mb_type)) {
820 get_lowest_part_y(h, refs, 0, 8, 0,
821 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
822 get_lowest_part_y(h, refs, 8, 8, 8,
823 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
824 } else if (IS_8X16(mb_type)) {
825 get_lowest_part_y(h, refs, 0, 16, 0,
826 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
827 get_lowest_part_y(h, refs, 4, 16, 0,
828 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
832 av_assert2(IS_8X8(mb_type));
834 for (i = 0; i < 4; i++) {
835 const int sub_mb_type = h->sub_mb_type[i];
837 int y_offset = (i & 2) << 2;
839 if (IS_SUB_8X8(sub_mb_type)) {
840 get_lowest_part_y(h, refs, n, 8, y_offset,
841 IS_DIR(sub_mb_type, 0, 0),
842 IS_DIR(sub_mb_type, 0, 1),
844 } else if (IS_SUB_8X4(sub_mb_type)) {
845 get_lowest_part_y(h, refs, n, 4, y_offset,
846 IS_DIR(sub_mb_type, 0, 0),
847 IS_DIR(sub_mb_type, 0, 1),
849 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
850 IS_DIR(sub_mb_type, 0, 0),
851 IS_DIR(sub_mb_type, 0, 1),
853 } else if (IS_SUB_4X8(sub_mb_type)) {
854 get_lowest_part_y(h, refs, n, 8, y_offset,
855 IS_DIR(sub_mb_type, 0, 0),
856 IS_DIR(sub_mb_type, 0, 1),
858 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
859 IS_DIR(sub_mb_type, 0, 0),
860 IS_DIR(sub_mb_type, 0, 1),
864 av_assert2(IS_SUB_4X4(sub_mb_type));
865 for (j = 0; j < 4; j++) {
866 int sub_y_offset = y_offset + 2 * (j & 2);
867 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
868 IS_DIR(sub_mb_type, 0, 0),
869 IS_DIR(sub_mb_type, 0, 1),
876 for (list = h->list_count - 1; list >= 0; list--)
877 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
878 int row = refs[list][ref];
880 H264Picture *ref_pic = &h->ref_list[list][ref];
881 int ref_field = ref_pic->reference - 1;
882 int ref_field_picture = ref_pic->field_picture;
883 int pic_height = 16 * h->mb_height >> ref_field_picture;
888 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
889 ff_thread_await_progress(&ref_pic->tf,
890 FFMIN((row >> 1) - !(row & 1),
893 ff_thread_await_progress(&ref_pic->tf,
894 FFMIN((row >> 1), pic_height - 1),
896 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
897 ff_thread_await_progress(&ref_pic->tf,
898 FFMIN(row * 2 + ref_field,
901 } else if (FIELD_PICTURE(h)) {
902 ff_thread_await_progress(&ref_pic->tf,
903 FFMIN(row, pic_height - 1),
906 ff_thread_await_progress(&ref_pic->tf,
907 FFMIN(row, pic_height - 1),
914 static av_always_inline void mc_dir_part(H264Context *h, H264Picture *pic,
915 int n, int square, int height,
917 uint8_t *dest_y, uint8_t *dest_cb,
919 int src_x_offset, int src_y_offset,
920 qpel_mc_func *qpix_op,
921 h264_chroma_mc_func chroma_op,
922 int pixel_shift, int chroma_idc)
924 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
925 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
926 const int luma_xy = (mx & 3) + ((my & 3) << 2);
927 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
928 uint8_t *src_y = pic->f.data[0] + offset;
929 uint8_t *src_cb, *src_cr;
931 int extra_height = 0;
933 const int full_mx = mx >> 2;
934 const int full_my = my >> 2;
935 const int pic_width = 16 * h->mb_width;
936 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
944 if (full_mx < 0 - extra_width ||
945 full_my < 0 - extra_height ||
946 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
947 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
948 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
949 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
950 h->mb_linesize, h->mb_linesize,
951 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
952 full_my - 2, pic_width, pic_height);
953 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
957 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
959 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
961 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
964 if (chroma_idc == 3 /* yuv444 */) {
965 src_cb = pic->f.data[1] + offset;
967 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
968 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
969 h->mb_linesize, h->mb_linesize,
970 16 + 5, 16 + 5 /*FIXME*/,
971 full_mx - 2, full_my - 2,
972 pic_width, pic_height);
973 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
975 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
977 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
979 src_cr = pic->f.data[2] + offset;
981 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
982 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
983 h->mb_linesize, h->mb_linesize,
984 16 + 5, 16 + 5 /*FIXME*/,
985 full_mx - 2, full_my - 2,
986 pic_width, pic_height);
987 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
989 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
991 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
995 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
996 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
997 // chroma offset when predicting from a field of opposite parity
998 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
999 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
1002 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
1003 (my >> ysh) * h->mb_uvlinesize;
1004 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
1005 (my >> ysh) * h->mb_uvlinesize;
1008 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
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_cb = h->edge_emu_buffer;
1014 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
1015 height >> (chroma_idc == 1 /* yuv420 */),
1016 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1019 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
1020 h->mb_uvlinesize, h->mb_uvlinesize,
1021 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1022 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1023 src_cr = h->edge_emu_buffer;
1025 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
1026 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1029 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
1030 int height, int delta,
1031 uint8_t *dest_y, uint8_t *dest_cb,
1033 int x_offset, int y_offset,
1034 qpel_mc_func *qpix_put,
1035 h264_chroma_mc_func chroma_put,
1036 qpel_mc_func *qpix_avg,
1037 h264_chroma_mc_func chroma_avg,
1038 int list0, int list1,
1039 int pixel_shift, int chroma_idc)
1041 qpel_mc_func *qpix_op = qpix_put;
1042 h264_chroma_mc_func chroma_op = chroma_put;
1044 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1045 if (chroma_idc == 3 /* yuv444 */) {
1046 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1047 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1048 } else if (chroma_idc == 2 /* yuv422 */) {
1049 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1050 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1051 } else { /* yuv420 */
1052 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1053 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1055 x_offset += 8 * h->mb_x;
1056 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1059 H264Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1060 mc_dir_part(h, ref, n, square, height, delta, 0,
1061 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1062 qpix_op, chroma_op, pixel_shift, chroma_idc);
1065 chroma_op = chroma_avg;
1069 H264Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1070 mc_dir_part(h, ref, n, square, height, delta, 1,
1071 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1072 qpix_op, chroma_op, pixel_shift, chroma_idc);
1076 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1077 int height, int delta,
1078 uint8_t *dest_y, uint8_t *dest_cb,
1080 int x_offset, int y_offset,
1081 qpel_mc_func *qpix_put,
1082 h264_chroma_mc_func chroma_put,
1083 h264_weight_func luma_weight_op,
1084 h264_weight_func chroma_weight_op,
1085 h264_biweight_func luma_weight_avg,
1086 h264_biweight_func chroma_weight_avg,
1087 int list0, int list1,
1088 int pixel_shift, int chroma_idc)
1092 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1093 if (chroma_idc == 3 /* yuv444 */) {
1094 chroma_height = height;
1095 chroma_weight_avg = luma_weight_avg;
1096 chroma_weight_op = luma_weight_op;
1097 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1098 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1099 } else if (chroma_idc == 2 /* yuv422 */) {
1100 chroma_height = height;
1101 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1102 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1103 } else { /* yuv420 */
1104 chroma_height = height >> 1;
1105 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1106 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1108 x_offset += 8 * h->mb_x;
1109 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1111 if (list0 && list1) {
1112 /* don't optimize for luma-only case, since B-frames usually
1113 * use implicit weights => chroma too. */
1114 uint8_t *tmp_cb = h->bipred_scratchpad;
1115 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1116 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1117 int refn0 = h->ref_cache[0][scan8[n]];
1118 int refn1 = h->ref_cache[1][scan8[n]];
1120 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1121 dest_y, dest_cb, dest_cr,
1122 x_offset, y_offset, qpix_put, chroma_put,
1123 pixel_shift, chroma_idc);
1124 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1125 tmp_y, tmp_cb, tmp_cr,
1126 x_offset, y_offset, qpix_put, chroma_put,
1127 pixel_shift, chroma_idc);
1129 if (h->use_weight == 2) {
1130 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1131 int weight1 = 64 - weight0;
1132 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1133 height, 5, weight0, weight1, 0);
1134 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1135 chroma_height, 5, weight0, weight1, 0);
1136 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1137 chroma_height, 5, weight0, weight1, 0);
1139 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1140 h->luma_log2_weight_denom,
1141 h->luma_weight[refn0][0][0],
1142 h->luma_weight[refn1][1][0],
1143 h->luma_weight[refn0][0][1] +
1144 h->luma_weight[refn1][1][1]);
1145 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1146 h->chroma_log2_weight_denom,
1147 h->chroma_weight[refn0][0][0][0],
1148 h->chroma_weight[refn1][1][0][0],
1149 h->chroma_weight[refn0][0][0][1] +
1150 h->chroma_weight[refn1][1][0][1]);
1151 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1152 h->chroma_log2_weight_denom,
1153 h->chroma_weight[refn0][0][1][0],
1154 h->chroma_weight[refn1][1][1][0],
1155 h->chroma_weight[refn0][0][1][1] +
1156 h->chroma_weight[refn1][1][1][1]);
1159 int list = list1 ? 1 : 0;
1160 int refn = h->ref_cache[list][scan8[n]];
1161 H264Picture *ref = &h->ref_list[list][refn];
1162 mc_dir_part(h, ref, n, square, height, delta, list,
1163 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1164 qpix_put, chroma_put, pixel_shift, chroma_idc);
1166 luma_weight_op(dest_y, h->mb_linesize, height,
1167 h->luma_log2_weight_denom,
1168 h->luma_weight[refn][list][0],
1169 h->luma_weight[refn][list][1]);
1170 if (h->use_weight_chroma) {
1171 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1172 h->chroma_log2_weight_denom,
1173 h->chroma_weight[refn][list][0][0],
1174 h->chroma_weight[refn][list][0][1]);
1175 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1176 h->chroma_log2_weight_denom,
1177 h->chroma_weight[refn][list][1][0],
1178 h->chroma_weight[refn][list][1][1]);
1183 static av_always_inline void prefetch_motion(H264Context *h, int list,
1184 int pixel_shift, int chroma_idc)
1186 /* fetch pixels for estimated mv 4 macroblocks ahead
1187 * optimized for 64byte cache lines */
1188 const int refn = h->ref_cache[list][scan8[0]];
1190 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1191 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1192 uint8_t **src = h->ref_list[list][refn].f.data;
1193 int off = (mx << pixel_shift) +
1194 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1195 (64 << pixel_shift);
1196 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1197 if (chroma_idc == 3 /* yuv444 */) {
1198 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1199 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1201 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
1202 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1207 static void free_tables(H264Context *h, int free_rbsp)
1212 av_freep(&h->intra4x4_pred_mode);
1213 av_freep(&h->chroma_pred_mode_table);
1214 av_freep(&h->cbp_table);
1215 av_freep(&h->mvd_table[0]);
1216 av_freep(&h->mvd_table[1]);
1217 av_freep(&h->direct_table);
1218 av_freep(&h->non_zero_count);
1219 av_freep(&h->slice_table_base);
1220 h->slice_table = NULL;
1221 av_freep(&h->list_counts);
1223 av_freep(&h->mb2b_xy);
1224 av_freep(&h->mb2br_xy);
1226 av_buffer_pool_uninit(&h->qscale_table_pool);
1227 av_buffer_pool_uninit(&h->mb_type_pool);
1228 av_buffer_pool_uninit(&h->motion_val_pool);
1229 av_buffer_pool_uninit(&h->ref_index_pool);
1231 if (free_rbsp && h->DPB) {
1232 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1233 unref_picture(h, &h->DPB[i]);
1235 } else if (h->DPB) {
1236 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1237 h->DPB[i].needs_realloc = 1;
1240 h->cur_pic_ptr = NULL;
1242 for (i = 0; i < H264_MAX_THREADS; i++) {
1243 hx = h->thread_context[i];
1246 av_freep(&hx->top_borders[1]);
1247 av_freep(&hx->top_borders[0]);
1248 av_freep(&hx->bipred_scratchpad);
1249 av_freep(&hx->edge_emu_buffer);
1250 av_freep(&hx->dc_val_base);
1251 av_freep(&hx->er.mb_index2xy);
1252 av_freep(&hx->er.error_status_table);
1253 av_freep(&hx->er.er_temp_buffer);
1254 av_freep(&hx->er.mbintra_table);
1255 av_freep(&hx->er.mbskip_table);
1258 av_freep(&hx->rbsp_buffer[1]);
1259 av_freep(&hx->rbsp_buffer[0]);
1260 hx->rbsp_buffer_size[0] = 0;
1261 hx->rbsp_buffer_size[1] = 0;
1264 av_freep(&h->thread_context[i]);
1268 static void init_dequant8_coeff_table(H264Context *h)
1271 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1273 for (i = 0; i < 6; i++) {
1274 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1275 for (j = 0; j < i; j++)
1276 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1277 64 * sizeof(uint8_t))) {
1278 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1284 for (q = 0; q < max_qp + 1; q++) {
1285 int shift = div6[q];
1287 for (x = 0; x < 64; x++)
1288 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1289 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1290 h->pps.scaling_matrix8[i][x]) << shift;
1295 static void init_dequant4_coeff_table(H264Context *h)
1298 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1299 for (i = 0; i < 6; i++) {
1300 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1301 for (j = 0; j < i; j++)
1302 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1303 16 * sizeof(uint8_t))) {
1304 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1310 for (q = 0; q < max_qp + 1; q++) {
1311 int shift = div6[q] + 2;
1313 for (x = 0; x < 16; x++)
1314 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1315 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1316 h->pps.scaling_matrix4[i][x]) << shift;
1321 static void init_dequant_tables(H264Context *h)
1324 init_dequant4_coeff_table(h);
1325 memset(h->dequant8_coeff, 0, sizeof(h->dequant8_coeff));
1327 if (h->pps.transform_8x8_mode)
1328 init_dequant8_coeff_table(h);
1329 if (h->sps.transform_bypass) {
1330 for (i = 0; i < 6; i++)
1331 for (x = 0; x < 16; x++)
1332 h->dequant4_coeff[i][0][x] = 1 << 6;
1333 if (h->pps.transform_8x8_mode)
1334 for (i = 0; i < 6; i++)
1335 for (x = 0; x < 64; x++)
1336 h->dequant8_coeff[i][0][x] = 1 << 6;
1340 int ff_h264_alloc_tables(H264Context *h)
1342 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1343 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1346 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1347 row_mb_num * 8 * sizeof(uint8_t), fail)
1348 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1349 big_mb_num * 48 * sizeof(uint8_t), fail)
1350 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1351 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1352 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1353 big_mb_num * sizeof(uint16_t), fail)
1354 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1355 big_mb_num * sizeof(uint8_t), fail)
1356 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1357 16 * row_mb_num * sizeof(uint8_t), fail);
1358 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1359 16 * row_mb_num * sizeof(uint8_t), fail);
1360 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1361 4 * big_mb_num * sizeof(uint8_t), fail);
1362 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1363 big_mb_num * sizeof(uint8_t), fail)
1365 memset(h->slice_table_base, -1,
1366 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1367 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1369 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1370 big_mb_num * sizeof(uint32_t), fail);
1371 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1372 big_mb_num * sizeof(uint32_t), fail);
1373 for (y = 0; y < h->mb_height; y++)
1374 for (x = 0; x < h->mb_width; x++) {
1375 const int mb_xy = x + y * h->mb_stride;
1376 const int b_xy = 4 * x + 4 * y * h->b_stride;
1378 h->mb2b_xy[mb_xy] = b_xy;
1379 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1382 if (!h->dequant4_coeff[0])
1383 init_dequant_tables(h);
1386 h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
1388 return AVERROR(ENOMEM);
1389 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
1390 av_frame_unref(&h->DPB[i].f);
1391 av_frame_unref(&h->cur_pic.f);
1398 return AVERROR(ENOMEM);
1402 * Mimic alloc_tables(), but for every context thread.
1404 static void clone_tables(H264Context *dst, H264Context *src, int i)
1406 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1407 dst->non_zero_count = src->non_zero_count;
1408 dst->slice_table = src->slice_table;
1409 dst->cbp_table = src->cbp_table;
1410 dst->mb2b_xy = src->mb2b_xy;
1411 dst->mb2br_xy = src->mb2br_xy;
1412 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1413 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1414 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1415 dst->direct_table = src->direct_table;
1416 dst->list_counts = src->list_counts;
1417 dst->DPB = src->DPB;
1418 dst->cur_pic_ptr = src->cur_pic_ptr;
1419 dst->cur_pic = src->cur_pic;
1420 dst->bipred_scratchpad = NULL;
1421 dst->edge_emu_buffer = NULL;
1422 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1423 src->sps.chroma_format_idc);
1428 * Allocate buffers which are not shared amongst multiple threads.
1430 static int context_init(H264Context *h)
1432 ERContext *er = &h->er;
1433 int mb_array_size = h->mb_height * h->mb_stride;
1434 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1435 int c_size = h->mb_stride * (h->mb_height + 1);
1436 int yc_size = y_size + 2 * c_size;
1439 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1440 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1441 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1442 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1444 h->ref_cache[0][scan8[5] + 1] =
1445 h->ref_cache[0][scan8[7] + 1] =
1446 h->ref_cache[0][scan8[13] + 1] =
1447 h->ref_cache[1][scan8[5] + 1] =
1448 h->ref_cache[1][scan8[7] + 1] =
1449 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1451 if (CONFIG_ERROR_RESILIENCE) {
1453 er->avctx = h->avctx;
1455 er->decode_mb = h264_er_decode_mb;
1457 er->quarter_sample = 1;
1459 er->mb_num = h->mb_num;
1460 er->mb_width = h->mb_width;
1461 er->mb_height = h->mb_height;
1462 er->mb_stride = h->mb_stride;
1463 er->b8_stride = h->mb_width * 2 + 1;
1465 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1466 fail); // error ressilience code looks cleaner with this
1467 for (y = 0; y < h->mb_height; y++)
1468 for (x = 0; x < h->mb_width; x++)
1469 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1471 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1472 h->mb_stride + h->mb_width;
1474 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1475 mb_array_size * sizeof(uint8_t), fail);
1477 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1478 memset(er->mbintra_table, 1, mb_array_size);
1480 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1482 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1485 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1486 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1487 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1488 er->dc_val[2] = er->dc_val[1] + c_size;
1489 for (i = 0; i < yc_size; i++)
1490 h->dc_val_base[i] = 1024;
1496 return AVERROR(ENOMEM); // free_tables will clean up for us
1499 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1500 int parse_extradata);
1502 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1504 AVCodecContext *avctx = h->avctx;
1507 if (!buf || size <= 0)
1511 int i, cnt, nalsize;
1512 const unsigned char *p = buf;
1517 av_log(avctx, AV_LOG_ERROR,
1518 "avcC %d too short\n", size);
1519 return AVERROR_INVALIDDATA;
1521 /* sps and pps in the avcC always have length coded with 2 bytes,
1522 * so put a fake nal_length_size = 2 while parsing them */
1523 h->nal_length_size = 2;
1524 // Decode sps from avcC
1525 cnt = *(p + 5) & 0x1f; // Number of sps
1527 for (i = 0; i < cnt; i++) {
1528 nalsize = AV_RB16(p) + 2;
1529 if(nalsize > size - (p-buf))
1530 return AVERROR_INVALIDDATA;
1531 ret = decode_nal_units(h, p, nalsize, 1);
1533 av_log(avctx, AV_LOG_ERROR,
1534 "Decoding sps %d from avcC failed\n", i);
1539 // Decode pps from avcC
1540 cnt = *(p++); // Number of pps
1541 for (i = 0; i < cnt; i++) {
1542 nalsize = AV_RB16(p) + 2;
1543 if(nalsize > size - (p-buf))
1544 return AVERROR_INVALIDDATA;
1545 ret = decode_nal_units(h, p, nalsize, 1);
1547 av_log(avctx, AV_LOG_ERROR,
1548 "Decoding pps %d from avcC failed\n", i);
1553 // Now store right nal length size, that will be used to parse all other nals
1554 h->nal_length_size = (buf[4] & 0x03) + 1;
1557 ret = decode_nal_units(h, buf, size, 1);
1564 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1566 H264Context *h = avctx->priv_data;
1572 h->bit_depth_luma = 8;
1573 h->chroma_format_idc = 1;
1575 h->avctx->bits_per_raw_sample = 8;
1576 h->cur_chroma_format_idc = 1;
1578 ff_h264dsp_init(&h->h264dsp, 8, 1);
1579 av_assert0(h->sps.bit_depth_chroma == 0);
1580 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1581 ff_h264qpel_init(&h->h264qpel, 8);
1582 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1584 h->dequant_coeff_pps = -1;
1585 h->current_sps_id = -1;
1587 /* needed so that IDCT permutation is known early */
1588 if (CONFIG_ERROR_RESILIENCE)
1589 ff_dsputil_init(&h->dsp, h->avctx);
1590 ff_videodsp_init(&h->vdsp, 8);
1592 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1593 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1595 h->picture_structure = PICT_FRAME;
1596 h->slice_context_count = 1;
1597 h->workaround_bugs = avctx->workaround_bugs;
1598 h->flags = avctx->flags;
1601 // s->decode_mb = ff_h263_decode_mb;
1602 if (!avctx->has_b_frames)
1605 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1607 ff_h264_decode_init_vlc();
1609 ff_init_cabac_states();
1612 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1614 h->thread_context[0] = h;
1615 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1616 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1617 h->last_pocs[i] = INT_MIN;
1618 h->prev_poc_msb = 1 << 16;
1619 h->prev_frame_num = -1;
1621 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
1622 ff_h264_reset_sei(h);
1623 if (avctx->codec_id == AV_CODEC_ID_H264) {
1624 if (avctx->ticks_per_frame == 1) {
1625 if(h->avctx->time_base.den < INT_MAX/2) {
1626 h->avctx->time_base.den *= 2;
1628 h->avctx->time_base.num /= 2;
1630 avctx->ticks_per_frame = 2;
1633 if (avctx->extradata_size > 0 && avctx->extradata) {
1634 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
1636 ff_h264_free_context(h);
1641 if (h->sps.bitstream_restriction_flag &&
1642 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1643 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1647 avctx->internal->allocate_progress = 1;
1654 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1655 #undef REBASE_PICTURE
1656 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1657 ((pic && pic >= old_ctx->DPB && \
1658 pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
1659 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1661 static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
1662 H264Context *new_base,
1663 H264Context *old_base)
1667 for (i = 0; i < count; i++) {
1668 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1669 IN_RANGE(from[i], old_base->DPB,
1670 sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
1672 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1676 static int copy_parameter_set(void **to, void **from, int count, int size)
1680 for (i = 0; i < count; i++) {
1681 if (to[i] && !from[i]) {
1683 } else if (from[i] && !to[i]) {
1684 to[i] = av_malloc(size);
1686 return AVERROR(ENOMEM);
1690 memcpy(to[i], from[i], size);
1696 static int decode_init_thread_copy(AVCodecContext *avctx)
1698 H264Context *h = avctx->priv_data;
1700 if (!avctx->internal->is_copy)
1702 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1703 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1705 h->rbsp_buffer[0] = NULL;
1706 h->rbsp_buffer[1] = NULL;
1707 h->rbsp_buffer_size[0] = 0;
1708 h->rbsp_buffer_size[1] = 0;
1709 h->context_initialized = 0;
1714 #define copy_fields(to, from, start_field, end_field) \
1715 memcpy(&to->start_field, &from->start_field, \
1716 (char *)&to->end_field - (char *)&to->start_field)
1718 static int h264_slice_header_init(H264Context *, int);
1720 static int h264_set_parameter_from_sps(H264Context *h);
1722 static int decode_update_thread_context(AVCodecContext *dst,
1723 const AVCodecContext *src)
1725 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1726 int inited = h->context_initialized, err = 0;
1727 int context_reinitialized = 0;
1734 (h->width != h1->width ||
1735 h->height != h1->height ||
1736 h->mb_width != h1->mb_width ||
1737 h->mb_height != h1->mb_height ||
1738 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1739 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1740 h->sps.colorspace != h1->sps.colorspace)) {
1742 /* set bits_per_raw_sample to the previous value. the check for changed
1743 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1744 * the current value */
1745 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1747 av_freep(&h->bipred_scratchpad);
1749 h->width = h1->width;
1750 h->height = h1->height;
1751 h->mb_height = h1->mb_height;
1752 h->mb_width = h1->mb_width;
1753 h->mb_num = h1->mb_num;
1754 h->mb_stride = h1->mb_stride;
1755 h->b_stride = h1->b_stride;
1757 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1758 (void **)h1->sps_buffers,
1759 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1762 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1763 (void **)h1->pps_buffers,
1764 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1768 if ((err = h264_slice_header_init(h, 1)) < 0) {
1769 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1772 context_reinitialized = 1;
1775 h264_set_parameter_from_sps(h);
1776 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1777 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1780 /* update linesize on resize for h264. The h264 decoder doesn't
1781 * necessarily call ff_MPV_frame_start in the new thread */
1782 h->linesize = h1->linesize;
1783 h->uvlinesize = h1->uvlinesize;
1785 /* copy block_offset since frame_start may not be called */
1786 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1789 for (i = 0; i < MAX_SPS_COUNT; i++)
1790 av_freep(h->sps_buffers + i);
1792 for (i = 0; i < MAX_PPS_COUNT; i++)
1793 av_freep(h->pps_buffers + i);
1795 av_freep(&h->rbsp_buffer[0]);
1796 av_freep(&h->rbsp_buffer[1]);
1797 memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1798 memcpy(&h->cabac, &h1->cabac,
1799 sizeof(H264Context) - offsetof(H264Context, cabac));
1800 av_assert0((void*)&h->cabac == &h->mb_padding + 1);
1802 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1803 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1805 memset(&h->er, 0, sizeof(h->er));
1806 memset(&h->mb, 0, sizeof(h->mb));
1807 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1808 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1812 h->qscale_table_pool = NULL;
1813 h->mb_type_pool = NULL;
1814 h->ref_index_pool = NULL;
1815 h->motion_val_pool = NULL;
1816 for (i = 0; i < 2; i++) {
1817 h->rbsp_buffer[i] = NULL;
1818 h->rbsp_buffer_size[i] = 0;
1821 if (h1->context_initialized) {
1822 h->context_initialized = 0;
1824 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1825 av_frame_unref(&h->cur_pic.f);
1826 h->cur_pic.tf.f = &h->cur_pic.f;
1828 ret = ff_h264_alloc_tables(h);
1830 av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n");
1833 ret = context_init(h);
1835 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1840 h->bipred_scratchpad = NULL;
1841 h->edge_emu_buffer = NULL;
1843 h->thread_context[0] = h;
1844 h->context_initialized = h1->context_initialized;
1847 h->avctx->coded_height = h1->avctx->coded_height;
1848 h->avctx->coded_width = h1->avctx->coded_width;
1849 h->avctx->width = h1->avctx->width;
1850 h->avctx->height = h1->avctx->height;
1851 h->coded_picture_number = h1->coded_picture_number;
1852 h->first_field = h1->first_field;
1853 h->picture_structure = h1->picture_structure;
1854 h->qscale = h1->qscale;
1855 h->droppable = h1->droppable;
1856 h->low_delay = h1->low_delay;
1858 for (i = 0; h->DPB && i < H264_MAX_PICTURE_COUNT; i++) {
1859 unref_picture(h, &h->DPB[i]);
1860 if (h1->DPB && h1->DPB[i].f.buf[0] &&
1861 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1865 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1866 unref_picture(h, &h->cur_pic);
1867 if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1870 h->workaround_bugs = h1->workaround_bugs;
1871 h->low_delay = h1->low_delay;
1872 h->droppable = h1->droppable;
1874 // extradata/NAL handling
1875 h->is_avc = h1->is_avc;
1878 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1879 (void **)h1->sps_buffers,
1880 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1883 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1884 (void **)h1->pps_buffers,
1885 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1889 // Dequantization matrices
1890 // FIXME these are big - can they be only copied when PPS changes?
1891 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1893 for (i = 0; i < 6; i++)
1894 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1895 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1897 for (i = 0; i < 6; i++)
1898 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1899 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1901 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1904 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1907 copy_fields(h, h1, short_ref, cabac_init_idc);
1909 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1910 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1911 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1912 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1914 h->frame_recovered = h1->frame_recovered;
1916 if (context_reinitialized)
1917 h264_set_parameter_from_sps(h);
1919 if (!h->cur_pic_ptr)
1922 if (!h->droppable) {
1923 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1924 h->prev_poc_msb = h->poc_msb;
1925 h->prev_poc_lsb = h->poc_lsb;
1927 h->prev_frame_num_offset = h->frame_num_offset;
1928 h->prev_frame_num = h->frame_num;
1929 h->outputed_poc = h->next_outputed_poc;
1931 h->recovery_frame = h1->recovery_frame;
1936 static int h264_frame_start(H264Context *h)
1940 const int pixel_shift = h->pixel_shift;
1942 1<<(h->sps.bit_depth_luma-1),
1943 1<<(h->sps.bit_depth_chroma-1),
1944 1<<(h->sps.bit_depth_chroma-1),
1948 if (!ff_thread_can_start_frame(h->avctx)) {
1949 av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1953 release_unused_pictures(h, 1);
1954 h->cur_pic_ptr = NULL;
1956 i = find_unused_picture(h);
1958 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1963 pic->reference = h->droppable ? 0 : h->picture_structure;
1964 pic->f.coded_picture_number = h->coded_picture_number++;
1965 pic->field_picture = h->picture_structure != PICT_FRAME;
1968 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1970 * See decode_nal_units().
1972 pic->f.key_frame = 0;
1973 pic->mmco_reset = 0;
1975 pic->invalid_gap = 0;
1977 if ((ret = alloc_picture(h, pic)) < 0)
1979 if(!h->frame_recovered && !h->avctx->hwaccel &&
1980 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1981 avpriv_color_frame(&pic->f, c);
1983 h->cur_pic_ptr = pic;
1984 unref_picture(h, &h->cur_pic);
1985 if (CONFIG_ERROR_RESILIENCE) {
1986 memset(&h->er.cur_pic, 0, sizeof(h->er.cur_pic));
1989 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1992 if (CONFIG_ERROR_RESILIENCE) {
1993 ff_er_frame_start(&h->er);
1994 memset(&h->er.last_pic, 0, sizeof(h->er.last_pic));
1995 memset(&h->er.next_pic, 0, sizeof(h->er.next_pic));
1998 assert(h->linesize && h->uvlinesize);
2000 for (i = 0; i < 16; i++) {
2001 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
2002 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
2004 for (i = 0; i < 16; i++) {
2005 h->block_offset[16 + i] =
2006 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
2007 h->block_offset[48 + 16 + i] =
2008 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
2011 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
2012 // h->cur_pic.reference /* || h->contains_intra */ || 1;
2014 /* We mark the current picture as non-reference after allocating it, so
2015 * that if we break out due to an error it can be released automatically
2016 * in the next ff_MPV_frame_start().
2018 h->cur_pic_ptr->reference = 0;
2020 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
2022 h->next_output_pic = NULL;
2024 assert(h->cur_pic_ptr->long_ref == 0);
2030 * Run setup operations that must be run after slice header decoding.
2031 * This includes finding the next displayed frame.
2033 * @param h h264 master context
2034 * @param setup_finished enough NALs have been read that we can call
2035 * ff_thread_finish_setup()
2037 static void decode_postinit(H264Context *h, int setup_finished)
2039 H264Picture *out = h->cur_pic_ptr;
2040 H264Picture *cur = h->cur_pic_ptr;
2041 int i, pics, out_of_order, out_idx;
2043 h->cur_pic_ptr->f.pict_type = h->pict_type;
2045 if (h->next_output_pic)
2048 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
2049 /* FIXME: if we have two PAFF fields in one packet, we can't start
2050 * the next thread here. If we have one field per packet, we can.
2051 * The check in decode_nal_units() is not good enough to find this
2052 * yet, so we assume the worst for now. */
2053 // if (setup_finished)
2054 // ff_thread_finish_setup(h->avctx);
2058 cur->f.interlaced_frame = 0;
2059 cur->f.repeat_pict = 0;
2061 /* Signal interlacing information externally. */
2062 /* Prioritize picture timing SEI information over used
2063 * decoding process if it exists. */
2065 if (h->sps.pic_struct_present_flag) {
2066 switch (h->sei_pic_struct) {
2067 case SEI_PIC_STRUCT_FRAME:
2069 case SEI_PIC_STRUCT_TOP_FIELD:
2070 case SEI_PIC_STRUCT_BOTTOM_FIELD:
2071 cur->f.interlaced_frame = 1;
2073 case SEI_PIC_STRUCT_TOP_BOTTOM:
2074 case SEI_PIC_STRUCT_BOTTOM_TOP:
2075 if (FIELD_OR_MBAFF_PICTURE(h))
2076 cur->f.interlaced_frame = 1;
2078 // try to flag soft telecine progressive
2079 cur->f.interlaced_frame = h->prev_interlaced_frame;
2081 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
2082 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
2083 /* Signal the possibility of telecined film externally
2084 * (pic_struct 5,6). From these hints, let the applications
2085 * decide if they apply deinterlacing. */
2086 cur->f.repeat_pict = 1;
2088 case SEI_PIC_STRUCT_FRAME_DOUBLING:
2089 cur->f.repeat_pict = 2;
2091 case SEI_PIC_STRUCT_FRAME_TRIPLING:
2092 cur->f.repeat_pict = 4;
2096 if ((h->sei_ct_type & 3) &&
2097 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2098 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2100 /* Derive interlacing flag from used decoding process. */
2101 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2103 h->prev_interlaced_frame = cur->f.interlaced_frame;
2105 if (cur->field_poc[0] != cur->field_poc[1]) {
2106 /* Derive top_field_first from field pocs. */
2107 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2109 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2110 /* Use picture timing SEI information. Even if it is a
2111 * information of a past frame, better than nothing. */
2112 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2113 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2114 cur->f.top_field_first = 1;
2116 cur->f.top_field_first = 0;
2118 /* Most likely progressive */
2119 cur->f.top_field_first = 0;
2123 if (h->sei_frame_packing_present &&
2124 h->frame_packing_arrangement_type >= 0 &&
2125 h->frame_packing_arrangement_type <= 6 &&
2126 h->content_interpretation_type > 0 &&
2127 h->content_interpretation_type < 3) {
2128 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
2132 switch (h->frame_packing_arrangement_type) {
2134 stereo->type = AV_STEREO3D_CHECKERBOARD;
2137 stereo->type = AV_STEREO3D_LINES;
2140 stereo->type = AV_STEREO3D_COLUMNS;
2143 if (h->quincunx_subsampling)
2144 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2146 stereo->type = AV_STEREO3D_SIDEBYSIDE;
2149 stereo->type = AV_STEREO3D_TOPBOTTOM;
2152 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
2155 stereo->type = AV_STEREO3D_2D;
2159 if (h->content_interpretation_type == 2)
2160 stereo->flags = AV_STEREO3D_FLAG_INVERT;
2163 cur->mmco_reset = h->mmco_reset;
2166 // FIXME do something with unavailable reference frames
2168 /* Sort B-frames into display order */
2170 if (h->sps.bitstream_restriction_flag &&
2171 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2172 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2176 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2177 !h->sps.bitstream_restriction_flag) {
2178 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2182 for (i = 0; 1; i++) {
2183 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2185 h->last_pocs[i-1] = cur->poc;
2188 h->last_pocs[i-1]= h->last_pocs[i];
2191 out_of_order = MAX_DELAYED_PIC_COUNT - i;
2192 if( cur->f.pict_type == AV_PICTURE_TYPE_B
2193 || (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))
2194 out_of_order = FFMAX(out_of_order, 1);
2195 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2196 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2197 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2198 h->last_pocs[i] = INT_MIN;
2199 h->last_pocs[0] = cur->poc;
2200 cur->mmco_reset = 1;
2201 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2202 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2203 h->avctx->has_b_frames = out_of_order;
2208 while (h->delayed_pic[pics])
2211 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
2213 h->delayed_pic[pics++] = cur;
2214 if (cur->reference == 0)
2215 cur->reference = DELAYED_PIC_REF;
2217 out = h->delayed_pic[0];
2219 for (i = 1; h->delayed_pic[i] &&
2220 !h->delayed_pic[i]->f.key_frame &&
2221 !h->delayed_pic[i]->mmco_reset;
2223 if (h->delayed_pic[i]->poc < out->poc) {
2224 out = h->delayed_pic[i];
2227 if (h->avctx->has_b_frames == 0 &&
2228 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2229 h->next_outputed_poc = INT_MIN;
2230 out_of_order = out->poc < h->next_outputed_poc;
2232 if (out_of_order || pics > h->avctx->has_b_frames) {
2233 out->reference &= ~DELAYED_PIC_REF;
2234 // for frame threading, the owner must be the second field's thread or
2235 // else the first thread can release the picture and reuse it unsafely
2236 for (i = out_idx; h->delayed_pic[i]; i++)
2237 h->delayed_pic[i] = h->delayed_pic[i + 1];
2239 if (!out_of_order && pics > h->avctx->has_b_frames) {
2240 h->next_output_pic = out;
2241 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2242 h->next_outputed_poc = INT_MIN;
2244 h->next_outputed_poc = out->poc;
2246 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2249 if (h->next_output_pic) {
2250 if (h->next_output_pic->recovered) {
2251 // We have reached an recovery point and all frames after it in
2252 // display order are "recovered".
2253 h->frame_recovered |= FRAME_RECOVERED_SEI;
2255 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2258 if (setup_finished && !h->avctx->hwaccel)
2259 ff_thread_finish_setup(h->avctx);
2262 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2263 uint8_t *src_cb, uint8_t *src_cr,
2264 int linesize, int uvlinesize,
2267 uint8_t *top_border;
2269 const int pixel_shift = h->pixel_shift;
2270 int chroma444 = CHROMA444(h);
2271 int chroma422 = CHROMA422(h);
2274 src_cb -= uvlinesize;
2275 src_cr -= uvlinesize;
2277 if (!simple && FRAME_MBAFF(h)) {
2280 top_border = h->top_borders[0][h->mb_x];
2281 AV_COPY128(top_border, src_y + 15 * linesize);
2283 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2284 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2287 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2288 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2289 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2290 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2292 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2293 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2295 } else if (chroma422) {
2297 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2298 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2300 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2301 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2305 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2306 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2308 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2309 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2314 } else if (MB_MBAFF(h)) {
2320 top_border = h->top_borders[top_idx][h->mb_x];
2321 /* There are two lines saved, the line above the top macroblock
2322 * of a pair, and the line above the bottom macroblock. */
2323 AV_COPY128(top_border, src_y + 16 * linesize);
2325 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2327 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2330 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2331 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2332 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2333 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2335 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2336 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2338 } else if (chroma422) {
2340 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2341 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2343 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2344 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2348 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2349 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2351 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2352 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2358 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2359 uint8_t *src_cb, uint8_t *src_cr,
2360 int linesize, int uvlinesize,
2361 int xchg, int chroma444,
2362 int simple, int pixel_shift)
2364 int deblock_topleft;
2367 uint8_t *top_border_m1;
2368 uint8_t *top_border;
2370 if (!simple && FRAME_MBAFF(h)) {
2375 top_idx = MB_MBAFF(h) ? 0 : 1;
2379 if (h->deblocking_filter == 2) {
2380 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2381 deblock_top = h->top_type;
2383 deblock_topleft = (h->mb_x > 0);
2384 deblock_top = (h->mb_y > !!MB_FIELD(h));
2387 src_y -= linesize + 1 + pixel_shift;
2388 src_cb -= uvlinesize + 1 + pixel_shift;
2389 src_cr -= uvlinesize + 1 + pixel_shift;
2391 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2392 top_border = h->top_borders[top_idx][h->mb_x];
2394 #define XCHG(a, b, xchg) \
2395 if (pixel_shift) { \
2397 AV_SWAP64(b + 0, a + 0); \
2398 AV_SWAP64(b + 8, a + 8); \
2408 if (deblock_topleft) {
2409 XCHG(top_border_m1 + (8 << pixel_shift),
2410 src_y - (7 << pixel_shift), 1);
2412 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2413 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2414 if (h->mb_x + 1 < h->mb_width) {
2415 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2416 src_y + (17 << pixel_shift), 1);
2418 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2420 if (deblock_topleft) {
2421 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2422 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2424 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2425 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2426 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2427 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2428 if (h->mb_x + 1 < h->mb_width) {
2429 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2430 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2433 if (deblock_topleft) {
2434 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2435 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2437 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2438 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2444 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2447 if (high_bit_depth) {
2448 return AV_RN32A(((int32_t *)mb) + index);
2450 return AV_RN16A(mb + index);
2453 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2454 int index, int value)
2456 if (high_bit_depth) {
2457 AV_WN32A(((int32_t *)mb) + index, value);
2459 AV_WN16A(mb + index, value);
2462 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2463 int mb_type, int is_h264,
2465 int transform_bypass,
2469 uint8_t *dest_y, int p)
2471 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2472 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2474 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2475 block_offset += 16 * p;
2476 if (IS_INTRA4x4(mb_type)) {
2477 if (IS_8x8DCT(mb_type)) {
2478 if (transform_bypass) {
2480 idct_add = h->h264dsp.h264_add_pixels8_clear;
2482 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2483 idct_add = h->h264dsp.h264_idct8_add;
2485 for (i = 0; i < 16; i += 4) {
2486 uint8_t *const ptr = dest_y + block_offset[i];
2487 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2488 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2489 if (h->x264_build != -1) {
2490 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2492 h->hpc.pred8x8l_filter_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift),
2493 (h-> topleft_samples_available << i) & 0x8000,
2494 (h->topright_samples_available << i) & 0x4000, linesize);
2496 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2497 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2498 (h->topright_samples_available << i) & 0x4000, linesize);
2500 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2501 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2503 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2508 if (transform_bypass) {
2510 idct_add = h->h264dsp.h264_add_pixels4_clear;
2512 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2513 idct_add = h->h264dsp.h264_idct_add;
2515 for (i = 0; i < 16; i++) {
2516 uint8_t *const ptr = dest_y + block_offset[i];
2517 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2519 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2520 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2525 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2526 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2527 av_assert2(h->mb_y || linesize <= block_offset[i]);
2528 if (!topright_avail) {
2530 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2531 topright = (uint8_t *)&tr_high;
2533 tr = ptr[3 - linesize] * 0x01010101u;
2534 topright = (uint8_t *)&tr;
2537 topright = ptr + (4 << pixel_shift) - linesize;
2541 h->hpc.pred4x4[dir](ptr, topright, linesize);
2542 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2545 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2546 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2548 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2549 } else if (CONFIG_SVQ3_DECODER)
2550 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2556 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2558 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2559 if (!transform_bypass)
2560 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2562 h->dequant4_coeff[p][qscale][0]);
2564 static const uint8_t dc_mapping[16] = {
2565 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2566 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2567 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2568 10 * 16, 11 * 16, 14 * 16, 15 * 16
2570 for (i = 0; i < 16; i++)
2571 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2572 pixel_shift, dc_mapping[i],
2573 dctcoef_get(h->mb_luma_dc[p],
2577 } else if (CONFIG_SVQ3_DECODER)
2578 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2579 h->mb_luma_dc[p], qscale);
2583 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2584 int is_h264, int simple,
2585 int transform_bypass,
2589 uint8_t *dest_y, int p)
2591 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2593 block_offset += 16 * p;
2594 if (!IS_INTRA4x4(mb_type)) {
2596 if (IS_INTRA16x16(mb_type)) {
2597 if (transform_bypass) {
2598 if (h->sps.profile_idc == 244 &&
2599 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2600 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2601 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2602 h->mb + (p * 256 << pixel_shift),
2605 for (i = 0; i < 16; i++)
2606 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2607 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2608 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2609 h->mb + (i * 16 + p * 256 << pixel_shift),
2613 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2614 h->mb + (p * 256 << pixel_shift),
2616 h->non_zero_count_cache + p * 5 * 8);
2618 } else if (h->cbp & 15) {
2619 if (transform_bypass) {
2620 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2621 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2622 : h->h264dsp.h264_add_pixels4_clear;
2623 for (i = 0; i < 16; i += di)
2624 if (h->non_zero_count_cache[scan8[i + p * 16]])
2625 idct_add(dest_y + block_offset[i],
2626 h->mb + (i * 16 + p * 256 << pixel_shift),
2629 if (IS_8x8DCT(mb_type))
2630 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2631 h->mb + (p * 256 << pixel_shift),
2633 h->non_zero_count_cache + p * 5 * 8);
2635 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2636 h->mb + (p * 256 << pixel_shift),
2638 h->non_zero_count_cache + p * 5 * 8);
2641 } else if (CONFIG_SVQ3_DECODER) {
2642 for (i = 0; i < 16; i++)
2643 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2644 // FIXME benchmark weird rule, & below
2645 uint8_t *const ptr = dest_y + block_offset[i];
2646 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2647 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2655 #include "h264_mb_template.c"
2659 #include "h264_mb_template.c"
2663 #include "h264_mb_template.c"
2665 void ff_h264_hl_decode_mb(H264Context *h)
2667 const int mb_xy = h->mb_xy;
2668 const int mb_type = h->cur_pic.mb_type[mb_xy];
2669 int is_complex = CONFIG_SMALL || h->is_complex ||
2670 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2673 if (is_complex || h->pixel_shift)
2674 hl_decode_mb_444_complex(h);
2676 hl_decode_mb_444_simple_8(h);
2677 } else if (is_complex) {
2678 hl_decode_mb_complex(h);
2679 } else if (h->pixel_shift) {
2680 hl_decode_mb_simple_16(h);
2682 hl_decode_mb_simple_8(h);
2685 int ff_pred_weight_table(H264Context *h)
2688 int luma_def, chroma_def;
2691 h->use_weight_chroma = 0;
2692 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2693 if (h->sps.chroma_format_idc)
2694 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2695 luma_def = 1 << h->luma_log2_weight_denom;
2696 chroma_def = 1 << h->chroma_log2_weight_denom;
2698 for (list = 0; list < 2; list++) {
2699 h->luma_weight_flag[list] = 0;
2700 h->chroma_weight_flag[list] = 0;
2701 for (i = 0; i < h->ref_count[list]; i++) {
2702 int luma_weight_flag, chroma_weight_flag;
2704 luma_weight_flag = get_bits1(&h->gb);
2705 if (luma_weight_flag) {
2706 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2707 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2708 if (h->luma_weight[i][list][0] != luma_def ||
2709 h->luma_weight[i][list][1] != 0) {
2711 h->luma_weight_flag[list] = 1;
2714 h->luma_weight[i][list][0] = luma_def;
2715 h->luma_weight[i][list][1] = 0;
2718 if (h->sps.chroma_format_idc) {
2719 chroma_weight_flag = get_bits1(&h->gb);
2720 if (chroma_weight_flag) {
2722 for (j = 0; j < 2; j++) {
2723 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2724 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2725 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2726 h->chroma_weight[i][list][j][1] != 0) {
2727 h->use_weight_chroma = 1;
2728 h->chroma_weight_flag[list] = 1;
2733 for (j = 0; j < 2; j++) {
2734 h->chroma_weight[i][list][j][0] = chroma_def;
2735 h->chroma_weight[i][list][j][1] = 0;
2740 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2743 h->use_weight = h->use_weight || h->use_weight_chroma;
2748 * Initialize implicit_weight table.
2749 * @param field 0/1 initialize the weight for interlaced MBAFF
2750 * -1 initializes the rest
2752 static void implicit_weight_table(H264Context *h, int field)
2754 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2756 for (i = 0; i < 2; i++) {
2757 h->luma_weight_flag[i] = 0;
2758 h->chroma_weight_flag[i] = 0;
2762 if (h->picture_structure == PICT_FRAME) {
2763 cur_poc = h->cur_pic_ptr->poc;
2765 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2767 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2768 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2770 h->use_weight_chroma = 0;
2774 ref_count0 = h->ref_count[0];
2775 ref_count1 = h->ref_count[1];
2777 cur_poc = h->cur_pic_ptr->field_poc[field];
2779 ref_count0 = 16 + 2 * h->ref_count[0];
2780 ref_count1 = 16 + 2 * h->ref_count[1];
2784 h->use_weight_chroma = 2;
2785 h->luma_log2_weight_denom = 5;
2786 h->chroma_log2_weight_denom = 5;
2788 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2789 int poc0 = h->ref_list[0][ref0].poc;
2790 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2792 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2793 int poc1 = h->ref_list[1][ref1].poc;
2794 int td = av_clip(poc1 - poc0, -128, 127);
2796 int tb = av_clip(cur_poc - poc0, -128, 127);
2797 int tx = (16384 + (FFABS(td) >> 1)) / td;
2798 int dist_scale_factor = (tb * tx + 32) >> 8;
2799 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2800 w = 64 - dist_scale_factor;
2804 h->implicit_weight[ref0][ref1][0] =
2805 h->implicit_weight[ref0][ref1][1] = w;
2807 h->implicit_weight[ref0][ref1][field] = w;
2814 * instantaneous decoder refresh.
2816 static void idr(H264Context *h)
2819 ff_h264_remove_all_refs(h);
2820 h->prev_frame_num = 0;
2821 h->prev_frame_num_offset = 0;
2822 h->prev_poc_msb = 1<<16;
2823 h->prev_poc_lsb = 0;
2824 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2825 h->last_pocs[i] = INT_MIN;
2828 /* forget old pics after a seek */
2829 static void flush_change(H264Context *h)
2833 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2834 h->prev_interlaced_frame = 1;
2837 h->prev_frame_num = -1;
2838 if (h->cur_pic_ptr) {
2839 h->cur_pic_ptr->reference = 0;
2840 for (j=i=0; h->delayed_pic[i]; i++)
2841 if (h->delayed_pic[i] != h->cur_pic_ptr)
2842 h->delayed_pic[j++] = h->delayed_pic[i];
2843 h->delayed_pic[j] = NULL;
2846 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2847 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2848 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2849 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2850 ff_h264_reset_sei(h);
2851 h->recovery_frame = -1;
2852 h->frame_recovered = 0;
2854 h->current_slice = 0;
2858 /* forget old pics after a seek */
2859 static void flush_dpb(AVCodecContext *avctx)
2861 H264Context *h = avctx->priv_data;
2864 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2865 if (h->delayed_pic[i])
2866 h->delayed_pic[i]->reference = 0;
2867 h->delayed_pic[i] = NULL;
2873 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
2874 unref_picture(h, &h->DPB[i]);
2875 h->cur_pic_ptr = NULL;
2876 unref_picture(h, &h->cur_pic);
2878 h->mb_x = h->mb_y = 0;
2880 h->parse_context.state = -1;
2881 h->parse_context.frame_start_found = 0;
2882 h->parse_context.overread = 0;
2883 h->parse_context.overread_index = 0;
2884 h->parse_context.index = 0;
2885 h->parse_context.last_index = 0;
2888 h->context_initialized = 0;
2891 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2893 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2896 h->frame_num_offset = h->prev_frame_num_offset;
2897 if (h->frame_num < h->prev_frame_num)
2898 h->frame_num_offset += max_frame_num;
2900 if (h->sps.poc_type == 0) {
2901 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2903 if (h->poc_lsb < h->prev_poc_lsb &&
2904 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2905 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2906 else if (h->poc_lsb > h->prev_poc_lsb &&
2907 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2908 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2910 h->poc_msb = h->prev_poc_msb;
2912 field_poc[1] = h->poc_msb + h->poc_lsb;
2913 if (h->picture_structure == PICT_FRAME)
2914 field_poc[1] += h->delta_poc_bottom;
2915 } else if (h->sps.poc_type == 1) {
2916 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2919 if (h->sps.poc_cycle_length != 0)
2920 abs_frame_num = h->frame_num_offset + h->frame_num;
2924 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2927 expected_delta_per_poc_cycle = 0;
2928 for (i = 0; i < h->sps.poc_cycle_length; i++)
2929 // FIXME integrate during sps parse
2930 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2932 if (abs_frame_num > 0) {
2933 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2934 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2936 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2937 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2938 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2942 if (h->nal_ref_idc == 0)
2943 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2945 field_poc[0] = expectedpoc + h->delta_poc[0];
2946 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2948 if (h->picture_structure == PICT_FRAME)
2949 field_poc[1] += h->delta_poc[1];
2951 int poc = 2 * (h->frame_num_offset + h->frame_num);
2953 if (!h->nal_ref_idc)
2960 if (h->picture_structure != PICT_BOTTOM_FIELD)
2961 pic_field_poc[0] = field_poc[0];
2962 if (h->picture_structure != PICT_TOP_FIELD)
2963 pic_field_poc[1] = field_poc[1];
2964 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2970 * initialize scan tables
2972 static void init_scan_tables(H264Context *h)
2975 for (i = 0; i < 16; i++) {
2976 #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
2977 h->zigzag_scan[i] = TRANSPOSE(zigzag_scan[i]);
2978 h->field_scan[i] = TRANSPOSE(field_scan[i]);
2981 for (i = 0; i < 64; i++) {
2982 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
2983 h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
2984 h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
2985 h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
2986 h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
2989 if (h->sps.transform_bypass) { // FIXME same ugly
2990 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2991 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2992 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2993 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2994 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2995 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2997 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2998 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2999 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
3000 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
3001 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
3002 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
3006 #if CONFIG_ERROR_RESILIENCE
3007 static void h264_set_erpic(ERPicture *dst, H264Picture *src)
3011 memset(dst, 0, sizeof(*dst));
3019 for (i = 0; i < 2; i++) {
3020 dst->motion_val[i] = src->motion_val[i];
3021 dst->ref_index[i] = src->ref_index[i];
3024 dst->mb_type = src->mb_type;
3025 dst->field_picture = src->field_picture;
3027 #endif /* CONFIG_ERROR_RESILIENCE */
3029 static int field_end(H264Context *h, int in_setup)
3031 AVCodecContext *const avctx = h->avctx;
3035 if (CONFIG_H264_VDPAU_DECODER &&
3036 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3037 ff_vdpau_h264_set_reference_frames(h);
3039 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
3040 if (!h->droppable) {
3041 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3042 h->prev_poc_msb = h->poc_msb;
3043 h->prev_poc_lsb = h->poc_lsb;
3045 h->prev_frame_num_offset = h->frame_num_offset;
3046 h->prev_frame_num = h->frame_num;
3047 h->outputed_poc = h->next_outputed_poc;
3050 if (avctx->hwaccel) {
3051 if (avctx->hwaccel->end_frame(avctx) < 0)
3052 av_log(avctx, AV_LOG_ERROR,
3053 "hardware accelerator failed to decode picture\n");
3056 if (CONFIG_H264_VDPAU_DECODER &&
3057 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3058 ff_vdpau_h264_picture_complete(h);
3061 * FIXME: Error handling code does not seem to support interlaced
3062 * when slices span multiple rows
3063 * The ff_er_add_slice calls don't work right for bottom
3064 * fields; they cause massive erroneous error concealing
3065 * Error marking covers both fields (top and bottom).
3066 * This causes a mismatched s->error_count
3067 * and a bad error table. Further, the error count goes to
3068 * INT_MAX when called for bottom field, because mb_y is
3069 * past end by one (callers fault) and resync_mb_y != 0
3070 * causes problems for the first MB line, too.
3072 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
3073 h264_set_erpic(&h->er.cur_pic, h->cur_pic_ptr);
3074 ff_er_frame_end(&h->er);
3076 if (!in_setup && !h->droppable)
3077 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3078 h->picture_structure == PICT_BOTTOM_FIELD);
3081 h->current_slice = 0;
3087 * Replicate H264 "master" context to thread contexts.
3089 static int clone_slice(H264Context *dst, H264Context *src)
3091 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
3092 dst->cur_pic_ptr = src->cur_pic_ptr;
3093 dst->cur_pic = src->cur_pic;
3094 dst->linesize = src->linesize;
3095 dst->uvlinesize = src->uvlinesize;
3096 dst->first_field = src->first_field;
3098 dst->prev_poc_msb = src->prev_poc_msb;
3099 dst->prev_poc_lsb = src->prev_poc_lsb;
3100 dst->prev_frame_num_offset = src->prev_frame_num_offset;
3101 dst->prev_frame_num = src->prev_frame_num;
3102 dst->short_ref_count = src->short_ref_count;
3104 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
3105 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
3106 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3108 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
3109 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
3115 * Compute profile from profile_idc and constraint_set?_flags.
3119 * @return profile as defined by FF_PROFILE_H264_*
3121 int ff_h264_get_profile(SPS *sps)
3123 int profile = sps->profile_idc;
3125 switch (sps->profile_idc) {
3126 case FF_PROFILE_H264_BASELINE:
3127 // constraint_set1_flag set to 1
3128 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3130 case FF_PROFILE_H264_HIGH_10:
3131 case FF_PROFILE_H264_HIGH_422:
3132 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3133 // constraint_set3_flag set to 1
3134 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3141 static int h264_set_parameter_from_sps(H264Context *h)
3143 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3144 (h->sps.bitstream_restriction_flag &&
3145 !h->sps.num_reorder_frames)) {
3146 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3147 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3148 "Reenabling low delay requires a codec flush.\n");
3153 if (h->avctx->has_b_frames < 2)
3154 h->avctx->has_b_frames = !h->low_delay;
3156 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3157 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
3158 if (h->avctx->codec &&
3159 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
3160 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
3161 av_log(h->avctx, AV_LOG_ERROR,
3162 "VDPAU decoding does not support video colorspace.\n");
3163 return AVERROR_INVALIDDATA;
3165 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
3166 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
3167 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3168 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
3169 h->pixel_shift = h->sps.bit_depth_luma > 8;
3171 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3172 h->sps.chroma_format_idc);
3173 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3174 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3175 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3176 h->sps.chroma_format_idc);
3178 if (CONFIG_ERROR_RESILIENCE)
3179 ff_dsputil_init(&h->dsp, h->avctx);
3180 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3182 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
3183 h->sps.bit_depth_luma);
3184 return AVERROR_INVALIDDATA;
3190 static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3192 switch (h->sps.bit_depth_luma) {
3195 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3196 return AV_PIX_FMT_GBRP9;
3198 return AV_PIX_FMT_YUV444P9;
3199 } else if (CHROMA422(h))
3200 return AV_PIX_FMT_YUV422P9;
3202 return AV_PIX_FMT_YUV420P9;
3206 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3207 return AV_PIX_FMT_GBRP10;
3209 return AV_PIX_FMT_YUV444P10;
3210 } else if (CHROMA422(h))
3211 return AV_PIX_FMT_YUV422P10;
3213 return AV_PIX_FMT_YUV420P10;
3217 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3218 return AV_PIX_FMT_GBRP12;
3220 return AV_PIX_FMT_YUV444P12;
3221 } else if (CHROMA422(h))
3222 return AV_PIX_FMT_YUV422P12;
3224 return AV_PIX_FMT_YUV420P12;
3228 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3229 return AV_PIX_FMT_GBRP14;
3231 return AV_PIX_FMT_YUV444P14;
3232 } else if (CHROMA422(h))
3233 return AV_PIX_FMT_YUV422P14;
3235 return AV_PIX_FMT_YUV420P14;
3239 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3240 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
3241 return AV_PIX_FMT_GBR24P;
3242 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
3243 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
3245 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3246 : AV_PIX_FMT_YUV444P;
3247 } else if (CHROMA422(h)) {
3248 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3249 : AV_PIX_FMT_YUV422P;
3252 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
3253 h->avctx->codec->pix_fmts :
3254 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3255 h264_hwaccel_pixfmt_list_jpeg_420 :
3256 h264_hwaccel_pixfmt_list_420;
3258 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
3259 if (fmt[i] == h->avctx->pix_fmt && !force_callback)
3261 return ff_thread_get_format(h->avctx, fmt);
3265 av_log(h->avctx, AV_LOG_ERROR,
3266 "Unsupported bit depth %d\n", h->sps.bit_depth_luma);
3267 return AVERROR_INVALIDDATA;
3271 /* export coded and cropped frame dimensions to AVCodecContext */
3272 static int init_dimensions(H264Context *h)
3274 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3275 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3276 av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
3277 av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
3279 /* handle container cropping */
3281 FFALIGN(h->avctx->width, 16) == h->width &&
3282 FFALIGN(h->avctx->height, 16) == h->height) {
3283 width = h->avctx->width;
3284 height = h->avctx->height;
3287 if (width <= 0 || height <= 0) {
3288 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3290 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3291 return AVERROR_INVALIDDATA;
3293 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3294 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3301 h->avctx->coded_width = h->width;
3302 h->avctx->coded_height = h->height;
3303 h->avctx->width = width;
3304 h->avctx->height = height;
3309 static int h264_slice_header_init(H264Context *h, int reinit)
3311 int nb_slices = (HAVE_THREADS &&
3312 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3313 h->avctx->thread_count : 1;
3316 h->avctx->sample_aspect_ratio = h->sps.sar;
3317 av_assert0(h->avctx->sample_aspect_ratio.den);
3318 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3319 &h->chroma_x_shift, &h->chroma_y_shift);
3321 if (h->sps.timing_info_present_flag) {
3322 int64_t den = h->sps.time_scale;
3323 if (h->x264_build < 44U)
3325 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3326 h->sps.num_units_in_tick, den, 1 << 30);
3329 h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3334 h->prev_interlaced_frame = 1;
3336 init_scan_tables(h);
3337 ret = ff_h264_alloc_tables(h);
3339 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
3343 if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3346 max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);
3348 max_slices = H264_MAX_THREADS;
3349 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"
3350 " reducing to %d\n", nb_slices, max_slices);
3351 nb_slices = max_slices;
3353 h->slice_context_count = nb_slices;
3355 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3356 ret = context_init(h);
3358 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3362 for (i = 1; i < h->slice_context_count; i++) {
3364 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3366 return AVERROR(ENOMEM);
3367 c->avctx = h->avctx;
3368 if (CONFIG_ERROR_RESILIENCE) {
3372 c->h264dsp = h->h264dsp;
3373 c->h264qpel = h->h264qpel;
3374 c->h264chroma = h->h264chroma;
3377 c->pixel_shift = h->pixel_shift;
3378 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3379 c->width = h->width;
3380 c->height = h->height;
3381 c->linesize = h->linesize;
3382 c->uvlinesize = h->uvlinesize;
3383 c->chroma_x_shift = h->chroma_x_shift;
3384 c->chroma_y_shift = h->chroma_y_shift;
3385 c->qscale = h->qscale;
3386 c->droppable = h->droppable;
3387 c->data_partitioning = h->data_partitioning;
3388 c->low_delay = h->low_delay;
3389 c->mb_width = h->mb_width;
3390 c->mb_height = h->mb_height;
3391 c->mb_stride = h->mb_stride;
3392 c->mb_num = h->mb_num;
3393 c->flags = h->flags;
3394 c->workaround_bugs = h->workaround_bugs;
3395 c->pict_type = h->pict_type;
3397 init_scan_tables(c);
3398 clone_tables(c, h, i);
3399 c->context_initialized = 1;
3402 for (i = 0; i < h->slice_context_count; i++)
3403 if ((ret = context_init(h->thread_context[i])) < 0) {
3404 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3409 h->context_initialized = 1;
3414 int ff_set_ref_count(H264Context *h)
3416 int ref_count[2], list_count;
3417 int num_ref_idx_active_override_flag;
3419 // set defaults, might be overridden a few lines later
3420 ref_count[0] = h->pps.ref_count[0];
3421 ref_count[1] = h->pps.ref_count[1];
3423 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3425 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3427 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3428 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3429 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3431 if (num_ref_idx_active_override_flag) {
3432 ref_count[0] = get_ue_golomb(&h->gb) + 1;
3433 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3434 ref_count[1] = get_ue_golomb(&h->gb) + 1;
3436 // full range is spec-ok in this case, even for frames
3440 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
3441 av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]);
3442 h->ref_count[0] = h->ref_count[1] = 0;
3444 return AVERROR_INVALIDDATA;
3447 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3453 ref_count[0] = ref_count[1] = 0;
3456 if (list_count != h->list_count ||
3457 ref_count[0] != h->ref_count[0] ||
3458 ref_count[1] != h->ref_count[1]) {
3459 h->ref_count[0] = ref_count[0];
3460 h->ref_count[1] = ref_count[1];
3461 h->list_count = list_count;
3468 static enum AVPixelFormat non_j_pixfmt(enum AVPixelFormat a)
3471 case AV_PIX_FMT_YUVJ420P: return AV_PIX_FMT_YUV420P;
3472 case AV_PIX_FMT_YUVJ422P: return AV_PIX_FMT_YUV422P;
3473 case AV_PIX_FMT_YUVJ444P: return AV_PIX_FMT_YUV444P;
3480 * Decode a slice header.
3481 * This will (re)intialize the decoder and call h264_frame_start() as needed.
3483 * @param h h264context
3484 * @param h0 h264 master context (differs from 'h' when doing sliced based
3485 * parallel decoding)
3487 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3489 static int decode_slice_header(H264Context *h, H264Context *h0)
3491 unsigned int first_mb_in_slice;
3492 unsigned int pps_id;
3494 unsigned int slice_type, tmp, i, j;
3495 int last_pic_structure, last_pic_droppable;
3497 int needs_reinit = 0;
3498 int field_pic_flag, bottom_field_flag;
3500 h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3501 h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3503 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3505 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3506 if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
3510 h0->current_slice = 0;
3511 if (!h0->first_field) {
3512 if (h->cur_pic_ptr && !h->droppable) {
3513 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3514 h->picture_structure == PICT_BOTTOM_FIELD);
3516 h->cur_pic_ptr = NULL;
3520 slice_type = get_ue_golomb_31(&h->gb);
3521 if (slice_type > 9) {
3522 av_log(h->avctx, AV_LOG_ERROR,
3523 "slice type %d too large at %d %d\n",
3524 slice_type, h->mb_x, h->mb_y);
3525 return AVERROR_INVALIDDATA;
3527 if (slice_type > 4) {
3529 h->slice_type_fixed = 1;
3531 h->slice_type_fixed = 0;
3533 slice_type = golomb_to_pict_type[slice_type];
3534 h->slice_type = slice_type;
3535 h->slice_type_nos = slice_type & 3;
3537 if (h->nal_unit_type == NAL_IDR_SLICE &&
3538 h->slice_type_nos != AV_PICTURE_TYPE_I) {
3539 av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
3540 return AVERROR_INVALIDDATA;
3543 // to make a few old functions happy, it's wrong though
3544 h->pict_type = h->slice_type;
3546 pps_id = get_ue_golomb(&h->gb);
3547 if (pps_id >= MAX_PPS_COUNT) {
3548 av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
3549 return AVERROR_INVALIDDATA;
3551 if (!h0->pps_buffers[pps_id]) {
3552 av_log(h->avctx, AV_LOG_ERROR,
3553 "non-existing PPS %u referenced\n",
3555 return AVERROR_INVALIDDATA;
3557 if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {
3558 av_log(h->avctx, AV_LOG_ERROR,
3559 "PPS change from %d to %d forbidden\n",
3560 h0->au_pps_id, pps_id);
3561 return AVERROR_INVALIDDATA;
3563 h->pps = *h0->pps_buffers[pps_id];
3565 if (!h0->sps_buffers[h->pps.sps_id]) {
3566 av_log(h->avctx, AV_LOG_ERROR,
3567 "non-existing SPS %u referenced\n",
3569 return AVERROR_INVALIDDATA;
3572 if (h->pps.sps_id != h->sps.sps_id ||
3573 h->pps.sps_id != h->current_sps_id ||
3574 h0->sps_buffers[h->pps.sps_id]->new) {
3576 h->sps = *h0->sps_buffers[h->pps.sps_id];
3578 if (h->mb_width != h->sps.mb_width ||
3579 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3580 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3581 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3585 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3586 h->chroma_format_idc != h->sps.chroma_format_idc) {
3587 h->bit_depth_luma = h->sps.bit_depth_luma;
3588 h->chroma_format_idc = h->sps.chroma_format_idc;
3591 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3595 h->avctx->profile = ff_h264_get_profile(&h->sps);
3596 h->avctx->level = h->sps.level_idc;
3597 h->avctx->refs = h->sps.ref_frame_count;
3599 must_reinit = (h->context_initialized &&
3600 ( 16*h->sps.mb_width != h->avctx->coded_width
3601 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3602 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3603 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3604 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
3605 || h->mb_width != h->sps.mb_width
3606 || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
3608 if (non_j_pixfmt(h0->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h0, 0)))
3611 h->mb_width = h->sps.mb_width;
3612 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3613 h->mb_num = h->mb_width * h->mb_height;
3614 h->mb_stride = h->mb_width + 1;
3616 h->b_stride = h->mb_width * 4;
3618 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3620 h->width = 16 * h->mb_width;
3621 h->height = 16 * h->mb_height;
3623 ret = init_dimensions(h);
3627 if (h->sps.video_signal_type_present_flag) {
3628 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3630 if (h->sps.colour_description_present_flag) {
3631 if (h->avctx->colorspace != h->sps.colorspace)
3633 h->avctx->color_primaries = h->sps.color_primaries;
3634 h->avctx->color_trc = h->sps.color_trc;
3635 h->avctx->colorspace = h->sps.colorspace;
3639 if (h->context_initialized &&
3640 (h->width != h->avctx->coded_width ||
3641 h->height != h->avctx->coded_height ||
3645 av_log(h->avctx, AV_LOG_ERROR,
3646 "changing width %d -> %d / height %d -> %d on "
3648 h->width, h->avctx->coded_width,
3649 h->height, h->avctx->coded_height,
3650 h0->current_slice + 1);
3651 return AVERROR_INVALIDDATA;
3656 if ((ret = get_pixel_format(h, 1)) < 0)
3658 h->avctx->pix_fmt = ret;
3660 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3661 "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
3663 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3664 av_log(h->avctx, AV_LOG_ERROR,
3665 "h264_slice_header_init() failed\n");
3669 if (!h->context_initialized) {
3671 av_log(h->avctx, AV_LOG_ERROR,
3672 "Cannot (re-)initialize context during parallel decoding.\n");
3673 return AVERROR_PATCHWELCOME;
3676 if ((ret = get_pixel_format(h, 1)) < 0)
3678 h->avctx->pix_fmt = ret;
3680 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3681 av_log(h->avctx, AV_LOG_ERROR,
3682 "h264_slice_header_init() failed\n");
3687 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3688 h->dequant_coeff_pps = pps_id;
3689 init_dequant_tables(h);
3692 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3695 h->mb_aff_frame = 0;
3696 last_pic_structure = h0->picture_structure;
3697 last_pic_droppable = h0->droppable;
3698 h->droppable = h->nal_ref_idc == 0;
3699 if (h->sps.frame_mbs_only_flag) {
3700 h->picture_structure = PICT_FRAME;
3702 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3703 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3706 field_pic_flag = get_bits1(&h->gb);
3707 if (field_pic_flag) {
3708 bottom_field_flag = get_bits1(&h->gb);
3709 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3711 h->picture_structure = PICT_FRAME;
3712 h->mb_aff_frame = h->sps.mb_aff;
3715 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3717 if (h0->current_slice != 0) {
3718 if (last_pic_structure != h->picture_structure ||
3719 last_pic_droppable != h->droppable) {
3720 av_log(h->avctx, AV_LOG_ERROR,
3721 "Changing field mode (%d -> %d) between slices is not allowed\n",
3722 last_pic_structure, h->picture_structure);
3723 h->picture_structure = last_pic_structure;
3724 h->droppable = last_pic_droppable;
3725 return AVERROR_INVALIDDATA;
3726 } else if (!h0->cur_pic_ptr) {
3727 av_log(h->avctx, AV_LOG_ERROR,
3728 "unset cur_pic_ptr on slice %d\n",
3729 h0->current_slice + 1);
3730 return AVERROR_INVALIDDATA;
3733 /* Shorten frame num gaps so we don't have to allocate reference
3734 * frames just to throw them away */
3735 if (h->frame_num != h->prev_frame_num) {
3736 int unwrap_prev_frame_num = h->prev_frame_num;
3737 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3739 if (unwrap_prev_frame_num > h->frame_num)
3740 unwrap_prev_frame_num -= max_frame_num;
3742 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3743 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3744 if (unwrap_prev_frame_num < 0)
3745 unwrap_prev_frame_num += max_frame_num;
3747 h->prev_frame_num = unwrap_prev_frame_num;
3751 /* See if we have a decoded first field looking for a pair...
3752 * Here, we're using that to see if we should mark previously
3753 * decode frames as "finished".
3754 * We have to do that before the "dummy" in-between frame allocation,
3755 * since that can modify h->cur_pic_ptr. */
3756 if (h0->first_field) {
3757 assert(h0->cur_pic_ptr);
3758 assert(h0->cur_pic_ptr->f.buf[0]);
3759 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3761 /* Mark old field/frame as completed */
3762 if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
3763 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3764 last_pic_structure == PICT_BOTTOM_FIELD);
3767 /* figure out if we have a complementary field pair */
3768 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3769 /* Previous field is unmatched. Don't display it, but let it
3770 * remain for reference if marked as such. */
3771 if (last_pic_structure != PICT_FRAME) {
3772 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3773 last_pic_structure == PICT_TOP_FIELD);
3776 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3777 /* This and previous field were reference, but had
3778 * different frame_nums. Consider this field first in
3779 * pair. Throw away previous field except for reference
3781 if (last_pic_structure != PICT_FRAME) {
3782 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3783 last_pic_structure == PICT_TOP_FIELD);
3786 /* Second field in complementary pair */
3787 if (!((last_pic_structure == PICT_TOP_FIELD &&
3788 h->picture_structure == PICT_BOTTOM_FIELD) ||
3789 (last_pic_structure == PICT_BOTTOM_FIELD &&
3790 h->picture_structure == PICT_TOP_FIELD))) {
3791 av_log(h->avctx, AV_LOG_ERROR,
3792 "Invalid field mode combination %d/%d\n",
3793 last_pic_structure, h->picture_structure);
3794 h->picture_structure = last_pic_structure;
3795 h->droppable = last_pic_droppable;
3796 return AVERROR_INVALIDDATA;
3797 } else if (last_pic_droppable != h->droppable) {
3798 avpriv_request_sample(h->avctx,
3799 "Found reference and non-reference fields in the same frame, which");
3800 h->picture_structure = last_pic_structure;
3801 h->droppable = last_pic_droppable;
3802 return AVERROR_PATCHWELCOME;
3808 while (h->frame_num != h->prev_frame_num && !h0->first_field &&
3809 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3810 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3811 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3812 h->frame_num, h->prev_frame_num);
3813 if (!h->sps.gaps_in_frame_num_allowed_flag)
3814 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3815 h->last_pocs[i] = INT_MIN;
3816 ret = h264_frame_start(h);
3818 h0->first_field = 0;
3822 h->prev_frame_num++;
3823 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3824 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3825 h->cur_pic_ptr->invalid_gap = !h->sps.gaps_in_frame_num_allowed_flag;
3826 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3827 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3828 ret = ff_generate_sliding_window_mmcos(h, 1);
3829 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3831 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3832 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3834 /* Error concealment: If a ref is missing, copy the previous ref
3836 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3837 * many assumptions about there being no actual duplicates.
3838 * FIXME: This does not copy padding for out-of-frame motion
3839 * vectors. Given we are concealing a lost frame, this probably
3840 * is not noticeable by comparison, but it should be fixed. */
3841 if (h->short_ref_count) {
3843 av_image_copy(h->short_ref[0]->f.data,
3844 h->short_ref[0]->f.linesize,
3845 (const uint8_t **)prev->f.data,
3850 h->short_ref[0]->poc = prev->poc + 2;
3852 h->short_ref[0]->frame_num = h->prev_frame_num;
3856 /* See if we have a decoded first field looking for a pair...
3857 * We're using that to see whether to continue decoding in that
3858 * frame, or to allocate a new one. */
3859 if (h0->first_field) {
3860 assert(h0->cur_pic_ptr);
3861 assert(h0->cur_pic_ptr->f.buf[0]);
3862 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3864 /* figure out if we have a complementary field pair */
3865 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3866 /* Previous field is unmatched. Don't display it, but let it
3867 * remain for reference if marked as such. */
3868 h0->cur_pic_ptr = NULL;
3869 h0->first_field = FIELD_PICTURE(h);
3871 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3872 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3873 h0->picture_structure==PICT_BOTTOM_FIELD);
3874 /* This and the previous field had different frame_nums.
3875 * Consider this field first in pair. Throw away previous
3876 * one except for reference purposes. */
3877 h0->first_field = 1;
3878 h0->cur_pic_ptr = NULL;
3880 /* Second field in complementary pair */
3881 h0->first_field = 0;
3885 /* Frame or first field in a potentially complementary pair */
3886 h0->first_field = FIELD_PICTURE(h);
3889 if (!FIELD_PICTURE(h) || h0->first_field) {
3890 if (h264_frame_start(h) < 0) {
3891 h0->first_field = 0;
3892 return AVERROR_INVALIDDATA;
3895 release_unused_pictures(h, 0);
3897 /* Some macroblocks can be accessed before they're available in case
3898 * of lost slices, MBAFF or threading. */
3899 if (FIELD_PICTURE(h)) {
3900 for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
3901 memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
3903 memset(h->slice_table, -1,
3904 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
3906 h0->last_slice_type = -1;
3908 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3911 /* can't be in alloc_tables because linesize isn't known there.
3912 * FIXME: redo bipred weight to not require extra buffer? */
3913 for (i = 0; i < h->slice_context_count; i++)
3914 if (h->thread_context[i]) {
3915 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
3920 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3922 av_assert1(h->mb_num == h->mb_width * h->mb_height);
3923 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3924 first_mb_in_slice >= h->mb_num) {
3925 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3926 return AVERROR_INVALIDDATA;
3928 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3929 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3930 FIELD_OR_MBAFF_PICTURE(h);
3931 if (h->picture_structure == PICT_BOTTOM_FIELD)
3932 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3933 av_assert1(h->mb_y < h->mb_height);
3935 if (h->picture_structure == PICT_FRAME) {
3936 h->curr_pic_num = h->frame_num;
3937 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3939 h->curr_pic_num = 2 * h->frame_num + 1;
3940 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3943 if (h->nal_unit_type == NAL_IDR_SLICE)
3944 get_ue_golomb(&h->gb); /* idr_pic_id */
3946 if (h->sps.poc_type == 0) {
3947 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3949 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3950 h->delta_poc_bottom = get_se_golomb(&h->gb);
3953 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3954 h->delta_poc[0] = get_se_golomb(&h->gb);
3956 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3957 h->delta_poc[1] = get_se_golomb(&h->gb);
3960 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3962 if (h->pps.redundant_pic_cnt_present)
3963 h->redundant_pic_count = get_ue_golomb(&h->gb);
3965 ret = ff_set_ref_count(h);
3969 if (slice_type != AV_PICTURE_TYPE_I &&
3970 (h0->current_slice == 0 ||
3971 slice_type != h0->last_slice_type ||
3972 memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3974 ff_h264_fill_default_ref_list(h);
3977 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3978 ret = ff_h264_decode_ref_pic_list_reordering(h);
3980 h->ref_count[1] = h->ref_count[0] = 0;
3985 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3986 (h->pps.weighted_bipred_idc == 1 &&
3987 h->slice_type_nos == AV_PICTURE_TYPE_B))
3988 ff_pred_weight_table(h);
3989 else if (h->pps.weighted_bipred_idc == 2 &&
3990 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3991 implicit_weight_table(h, -1);
3994 for (i = 0; i < 2; i++) {
3995 h->luma_weight_flag[i] = 0;
3996 h->chroma_weight_flag[i] = 0;
4000 // If frame-mt is enabled, only update mmco tables for the first slice
4001 // in a field. Subsequent slices can temporarily clobber h->mmco_index
4002 // or h->mmco, which will cause ref list mix-ups and decoding errors
4003 // further down the line. This may break decoding if the first slice is
4004 // corrupt, thus we only do this if frame-mt is enabled.
4005 if (h->nal_ref_idc) {
4006 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
4007 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
4008 h0->current_slice == 0);
4009 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
4010 return AVERROR_INVALIDDATA;
4013 if (FRAME_MBAFF(h)) {
4014 ff_h264_fill_mbaff_ref_list(h);
4016 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
4017 implicit_weight_table(h, 0);
4018 implicit_weight_table(h, 1);
4022 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
4023 ff_h264_direct_dist_scale_factor(h);
4024 ff_h264_direct_ref_list_init(h);
4026 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
4027 tmp = get_ue_golomb_31(&h->gb);
4029 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
4030 return AVERROR_INVALIDDATA;
4032 h->cabac_init_idc = tmp;
4035 h->last_qscale_diff = 0;
4036 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
4037 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
4038 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
4039 return AVERROR_INVALIDDATA;
4042 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4043 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4044 // FIXME qscale / qp ... stuff
4045 if (h->slice_type == AV_PICTURE_TYPE_SP)
4046 get_bits1(&h->gb); /* sp_for_switch_flag */
4047 if (h->slice_type == AV_PICTURE_TYPE_SP ||
4048 h->slice_type == AV_PICTURE_TYPE_SI)
4049 get_se_golomb(&h->gb); /* slice_qs_delta */
4051 h->deblocking_filter = 1;
4052 h->slice_alpha_c0_offset = 0;
4053 h->slice_beta_offset = 0;
4054 if (h->pps.deblocking_filter_parameters_present) {
4055 tmp = get_ue_golomb_31(&h->gb);
4057 av_log(h->avctx, AV_LOG_ERROR,
4058 "deblocking_filter_idc %u out of range\n", tmp);
4059 return AVERROR_INVALIDDATA;
4061 h->deblocking_filter = tmp;
4062 if (h->deblocking_filter < 2)
4063 h->deblocking_filter ^= 1; // 1<->0
4065 if (h->deblocking_filter) {
4066 h->slice_alpha_c0_offset = get_se_golomb(&h->gb) * 2;
4067 h->slice_beta_offset = get_se_golomb(&h->gb) * 2;
4068 if (h->slice_alpha_c0_offset > 12 ||
4069 h->slice_alpha_c0_offset < -12 ||
4070 h->slice_beta_offset > 12 ||
4071 h->slice_beta_offset < -12) {
4072 av_log(h->avctx, AV_LOG_ERROR,
4073 "deblocking filter parameters %d %d out of range\n",
4074 h->slice_alpha_c0_offset, h->slice_beta_offset);
4075 return AVERROR_INVALIDDATA;
4080 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
4081 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
4082 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
4083 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
4084 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
4085 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
4086 h->nal_ref_idc == 0))
4087 h->deblocking_filter = 0;
4089 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
4090 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
4091 /* Cheat slightly for speed:
4092 * Do not bother to deblock across slices. */
4093 h->deblocking_filter = 2;
4095 h0->max_contexts = 1;
4096 if (!h0->single_decode_warning) {
4097 av_log(h->avctx, AV_LOG_INFO,
4098 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
4099 h0->single_decode_warning = 1;
4102 av_log(h->avctx, AV_LOG_ERROR,
4103 "Deblocking switched inside frame.\n");
4109 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
4111 h->pps.chroma_qp_index_offset[0],
4112 h->pps.chroma_qp_index_offset[1]) +
4113 6 * (h->sps.bit_depth_luma - 8);
4115 h0->last_slice_type = slice_type;
4116 memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
4117 h->slice_num = ++h0->current_slice;
4120 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
4121 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
4122 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
4123 && h->slice_num >= MAX_SLICES) {
4124 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
4125 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);
4128 for (j = 0; j < 2; j++) {
4130 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
4131 for (i = 0; i < 16; i++) {
4133 if (j < h->list_count && i < h->ref_count[j] &&
4134 h->ref_list[j][i].f.buf[0]) {
4136 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
4137 for (k = 0; k < h->short_ref_count; k++)
4138 if (h->short_ref[k]->f.buf[0]->buffer == buf) {
4142 for (k = 0; k < h->long_ref_count; k++)
4143 if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
4144 id_list[i] = h->short_ref_count + k;
4152 for (i = 0; i < 16; i++)
4153 ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
4155 ref2frm[18 + 1] = -1;
4156 for (i = 16; i < 48; i++)
4157 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
4158 (h->ref_list[j][i].reference & 3);
4161 if (h->ref_count[0]) h264_set_erpic(&h->er.last_pic, &h->ref_list[0][0]);
4162 if (h->ref_count[1]) h264_set_erpic(&h->er.next_pic, &h->ref_list[1][0]);
4164 h->er.ref_count = h->ref_count[0];
4165 h0->au_pps_id = pps_id;
4167 h0->sps_buffers[h->pps.sps_id]->new = 0;
4168 h->current_sps_id = h->pps.sps_id;
4170 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
4171 av_log(h->avctx, AV_LOG_DEBUG,
4172 "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",
4174 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
4176 av_get_picture_type_char(h->slice_type),
4177 h->slice_type_fixed ? " fix" : "",
4178 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
4179 pps_id, h->frame_num,
4180 h->cur_pic_ptr->field_poc[0],
4181 h->cur_pic_ptr->field_poc[1],
4182 h->ref_count[0], h->ref_count[1],
4184 h->deblocking_filter,
4185 h->slice_alpha_c0_offset, h->slice_beta_offset,
4187 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
4188 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
4194 int ff_h264_get_slice_type(const H264Context *h)
4196 switch (h->slice_type) {
4197 case AV_PICTURE_TYPE_P:
4199 case AV_PICTURE_TYPE_B:
4201 case AV_PICTURE_TYPE_I:
4203 case AV_PICTURE_TYPE_SP:
4205 case AV_PICTURE_TYPE_SI:
4208 return AVERROR_INVALIDDATA;
4212 static av_always_inline void fill_filter_caches_inter(H264Context *h,
4213 int mb_type, int top_xy,
4214 int left_xy[LEFT_MBS],
4216 int left_type[LEFT_MBS],
4217 int mb_xy, int list)
4219 int b_stride = h->b_stride;
4220 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4221 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4222 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4223 if (USES_LIST(top_type, list)) {
4224 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
4225 const int b8_xy = 4 * top_xy + 2;
4226 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4227 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4228 ref_cache[0 - 1 * 8] =
4229 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4230 ref_cache[2 - 1 * 8] =
4231 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4233 AV_ZERO128(mv_dst - 1 * 8);
4234 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4237 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4238 if (USES_LIST(left_type[LTOP], list)) {
4239 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
4240 const int b8_xy = 4 * left_xy[LTOP] + 1;
4241 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4242 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4243 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4244 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4245 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4247 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4248 ref_cache[-1 + 16] =
4249 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4251 AV_ZERO32(mv_dst - 1 + 0);
4252 AV_ZERO32(mv_dst - 1 + 8);
4253 AV_ZERO32(mv_dst - 1 + 16);
4254 AV_ZERO32(mv_dst - 1 + 24);
4257 ref_cache[-1 + 16] =
4258 ref_cache[-1 + 24] = LIST_NOT_USED;
4263 if (!USES_LIST(mb_type, list)) {
4264 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4265 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4266 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4267 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4268 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4273 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4274 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4275 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4276 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4277 AV_WN32A(&ref_cache[0 * 8], ref01);
4278 AV_WN32A(&ref_cache[1 * 8], ref01);
4279 AV_WN32A(&ref_cache[2 * 8], ref23);
4280 AV_WN32A(&ref_cache[3 * 8], ref23);
4284 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4285 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4286 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4287 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4288 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4294 * @return non zero if the loop filter can be skipped
4296 static int fill_filter_caches(H264Context *h, int mb_type)
4298 const int mb_xy = h->mb_xy;
4299 int top_xy, left_xy[LEFT_MBS];
4300 int top_type, left_type[LEFT_MBS];
4304 top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4306 /* Wow, what a mess, why didn't they simplify the interlacing & intra
4307 * stuff, I can't imagine that these complex rules are worth it. */
4309 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4310 if (FRAME_MBAFF(h)) {
4311 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4312 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4314 if (left_mb_field_flag != curr_mb_field_flag)
4315 left_xy[LTOP] -= h->mb_stride;
4317 if (curr_mb_field_flag)
4318 top_xy += h->mb_stride &
4319 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4320 if (left_mb_field_flag != curr_mb_field_flag)
4321 left_xy[LBOT] += h->mb_stride;
4325 h->top_mb_xy = top_xy;
4326 h->left_mb_xy[LTOP] = left_xy[LTOP];
4327 h->left_mb_xy[LBOT] = left_xy[LBOT];
4329 /* For sufficiently low qp, filtering wouldn't do anything.
4330 * This is a conservative estimate: could also check beta_offset
4331 * and more accurate chroma_qp. */
4332 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4333 int qp = h->cur_pic.qscale_table[mb_xy];
4334 if (qp <= qp_thresh &&
4335 (left_xy[LTOP] < 0 ||
4336 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4338 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4339 if (!FRAME_MBAFF(h))
4341 if ((left_xy[LTOP] < 0 ||
4342 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4343 (top_xy < h->mb_stride ||
4344 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4349 top_type = h->cur_pic.mb_type[top_xy];
4350 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4351 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4352 if (h->deblocking_filter == 2) {
4353 if (h->slice_table[top_xy] != h->slice_num)
4355 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4356 left_type[LTOP] = left_type[LBOT] = 0;
4358 if (h->slice_table[top_xy] == 0xFFFF)
4360 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4361 left_type[LTOP] = left_type[LBOT] = 0;
4363 h->top_type = top_type;
4364 h->left_type[LTOP] = left_type[LTOP];
4365 h->left_type[LBOT] = left_type[LBOT];
4367 if (IS_INTRA(mb_type))
4370 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4371 top_type, left_type, mb_xy, 0);
4372 if (h->list_count == 2)
4373 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4374 top_type, left_type, mb_xy, 1);
4376 nnz = h->non_zero_count[mb_xy];
4377 nnz_cache = h->non_zero_count_cache;
4378 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4379 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4380 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4381 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4382 h->cbp = h->cbp_table[mb_xy];
4385 nnz = h->non_zero_count[top_xy];
4386 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4389 if (left_type[LTOP]) {
4390 nnz = h->non_zero_count[left_xy[LTOP]];
4391 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4392 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4393 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4394 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4397 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4398 * from what the loop filter needs */
4399 if (!CABAC(h) && h->pps.transform_8x8_mode) {
4400 if (IS_8x8DCT(top_type)) {
4401 nnz_cache[4 + 8 * 0] =
4402 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4403 nnz_cache[6 + 8 * 0] =
4404 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4406 if (IS_8x8DCT(left_type[LTOP])) {
4407 nnz_cache[3 + 8 * 1] =
4408 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4410 if (IS_8x8DCT(left_type[LBOT])) {
4411 nnz_cache[3 + 8 * 3] =
4412 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4415 if (IS_8x8DCT(mb_type)) {
4416 nnz_cache[scan8[0]] =
4417 nnz_cache[scan8[1]] =
4418 nnz_cache[scan8[2]] =
4419 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4421 nnz_cache[scan8[0 + 4]] =
4422 nnz_cache[scan8[1 + 4]] =
4423 nnz_cache[scan8[2 + 4]] =
4424 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4426 nnz_cache[scan8[0 + 8]] =
4427 nnz_cache[scan8[1 + 8]] =
4428 nnz_cache[scan8[2 + 8]] =
4429 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4431 nnz_cache[scan8[0 + 12]] =
4432 nnz_cache[scan8[1 + 12]] =
4433 nnz_cache[scan8[2 + 12]] =
4434 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4441 static void loop_filter(H264Context *h, int start_x, int end_x)
4443 uint8_t *dest_y, *dest_cb, *dest_cr;
4444 int linesize, uvlinesize, mb_x, mb_y;
4445 const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4446 const int old_slice_type = h->slice_type;
4447 const int pixel_shift = h->pixel_shift;
4448 const int block_h = 16 >> h->chroma_y_shift;
4450 if (h->deblocking_filter) {
4451 for (mb_x = start_x; mb_x < end_x; mb_x++)
4452 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4454 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4455 h->slice_num = h->slice_table[mb_xy];
4456 mb_type = h->cur_pic.mb_type[mb_xy];
4457 h->list_count = h->list_counts[mb_xy];
4461 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4465 dest_y = h->cur_pic.f.data[0] +
4466 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4467 dest_cb = h->cur_pic.f.data[1] +
4468 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4469 mb_y * h->uvlinesize * block_h;
4470 dest_cr = h->cur_pic.f.data[2] +
4471 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4472 mb_y * h->uvlinesize * block_h;
4473 // FIXME simplify above
4476 linesize = h->mb_linesize = h->linesize * 2;
4477 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4478 if (mb_y & 1) { // FIXME move out of this function?
4479 dest_y -= h->linesize * 15;
4480 dest_cb -= h->uvlinesize * (block_h - 1);
4481 dest_cr -= h->uvlinesize * (block_h - 1);
4484 linesize = h->mb_linesize = h->linesize;
4485 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4487 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4489 if (fill_filter_caches(h, mb_type))
4491 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4492 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4494 if (FRAME_MBAFF(h)) {
4495 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4496 linesize, uvlinesize);
4498 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4499 dest_cr, linesize, uvlinesize);
4503 h->slice_type = old_slice_type;
4505 h->mb_y = end_mb_y - FRAME_MBAFF(h);
4506 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4507 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4510 static void predict_field_decoding_flag(H264Context *h)
4512 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4513 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4514 h->cur_pic.mb_type[mb_xy - 1] :
4515 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4516 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4517 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4521 * Draw edges and report progress for the last MB row.
4523 static void decode_finish_row(H264Context *h)
4525 int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4526 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4527 int height = 16 << FRAME_MBAFF(h);
4528 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4530 if (h->deblocking_filter) {
4531 if ((top + height) >= pic_height)
4532 height += deblock_border;
4533 top -= deblock_border;
4536 if (top >= pic_height || (top + height) < 0)
4539 height = FFMIN(height, pic_height - top);
4541 height = top + height;
4545 ff_h264_draw_horiz_band(h, top, height);
4547 if (h->droppable || h->er.error_occurred)
4550 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4551 h->picture_structure == PICT_BOTTOM_FIELD);
4554 static void er_add_slice(H264Context *h, int startx, int starty,
4555 int endx, int endy, int status)
4557 if (CONFIG_ERROR_RESILIENCE) {
4558 ERContext *er = &h->er;
4560 ff_er_add_slice(er, startx, starty, endx, endy, status);
4564 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4566 H264Context *h = *(void **)arg;
4567 int lf_x_start = h->mb_x;
4569 h->mb_skip_run = -1;
4571 av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4573 h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4574 avctx->codec_id != AV_CODEC_ID_H264 ||
4575 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4577 if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
4578 const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
4580 int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
4581 prev_status &= ~ VP_START;
4582 if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
4583 h->er.error_occurred = 1;
4589 align_get_bits(&h->gb);
4592 ff_init_cabac_decoder(&h->cabac,
4593 h->gb.buffer + get_bits_count(&h->gb) / 8,
4594 (get_bits_left(&h->gb) + 7) / 8);
4596 ff_h264_init_cabac_states(h);
4600 int ret = ff_h264_decode_mb_cabac(h);
4602 // STOP_TIMER("decode_mb_cabac")
4605 ff_h264_hl_decode_mb(h);
4607 // FIXME optimal? or let mb_decode decode 16x32 ?
4608 if (ret >= 0 && FRAME_MBAFF(h)) {
4611 ret = ff_h264_decode_mb_cabac(h);
4614 ff_h264_hl_decode_mb(h);
4617 eos = get_cabac_terminate(&h->cabac);
4619 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4620 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4621 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4622 h->mb_y, ER_MB_END);
4623 if (h->mb_x >= lf_x_start)
4624 loop_filter(h, lf_x_start, h->mb_x + 1);
4627 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4628 av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4629 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4630 av_log(h->avctx, AV_LOG_ERROR,
4631 "error while decoding MB %d %d, bytestream %td\n",
4633 h->cabac.bytestream_end - h->cabac.bytestream);
4634 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4635 h->mb_y, ER_MB_ERROR);
4636 return AVERROR_INVALIDDATA;
4639 if (++h->mb_x >= h->mb_width) {
4640 loop_filter(h, lf_x_start, h->mb_x);
4641 h->mb_x = lf_x_start = 0;
4642 decode_finish_row(h);
4644 if (FIELD_OR_MBAFF_PICTURE(h)) {
4646 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4647 predict_field_decoding_flag(h);
4651 if (eos || h->mb_y >= h->mb_height) {
4652 tprintf(h->avctx, "slice end %d %d\n",
4653 get_bits_count(&h->gb), h->gb.size_in_bits);
4654 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4655 h->mb_y, ER_MB_END);
4656 if (h->mb_x > lf_x_start)
4657 loop_filter(h, lf_x_start, h->mb_x);
4663 int ret = ff_h264_decode_mb_cavlc(h);
4666 ff_h264_hl_decode_mb(h);
4668 // FIXME optimal? or let mb_decode decode 16x32 ?
4669 if (ret >= 0 && FRAME_MBAFF(h)) {
4671 ret = ff_h264_decode_mb_cavlc(h);
4674 ff_h264_hl_decode_mb(h);
4679 av_log(h->avctx, AV_LOG_ERROR,
4680 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4681 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4682 h->mb_y, ER_MB_ERROR);
4686 if (++h->mb_x >= h->mb_width) {
4687 loop_filter(h, lf_x_start, h->mb_x);
4688 h->mb_x = lf_x_start = 0;
4689 decode_finish_row(h);
4691 if (FIELD_OR_MBAFF_PICTURE(h)) {
4693 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4694 predict_field_decoding_flag(h);
4696 if (h->mb_y >= h->mb_height) {
4697 tprintf(h->avctx, "slice end %d %d\n",
4698 get_bits_count(&h->gb), h->gb.size_in_bits);
4700 if ( get_bits_left(&h->gb) == 0
4701 || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4702 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4703 h->mb_x - 1, h->mb_y,
4708 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4712 return AVERROR_INVALIDDATA;
4717 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4718 tprintf(h->avctx, "slice end %d %d\n",
4719 get_bits_count(&h->gb), h->gb.size_in_bits);
4721 if (get_bits_left(&h->gb) == 0) {
4722 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4723 h->mb_x - 1, h->mb_y,
4725 if (h->mb_x > lf_x_start)
4726 loop_filter(h, lf_x_start, h->mb_x);
4730 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4731 h->mb_y, ER_MB_ERROR);
4733 return AVERROR_INVALIDDATA;
4741 * Call decode_slice() for each context.
4743 * @param h h264 master context
4744 * @param context_count number of contexts to execute
4746 static int execute_decode_slices(H264Context *h, unsigned context_count)
4748 AVCodecContext *const avctx = h->avctx;
4752 av_assert0(h->mb_y < h->mb_height);
4754 if (h->avctx->hwaccel ||
4755 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4757 if (context_count == 1) {
4758 return decode_slice(avctx, &h);
4760 av_assert0(context_count > 0);
4761 for (i = 1; i < context_count; i++) {
4762 hx = h->thread_context[i];
4763 if (CONFIG_ERROR_RESILIENCE) {
4764 hx->er.error_count = 0;
4766 hx->x264_build = h->x264_build;
4769 avctx->execute(avctx, decode_slice, h->thread_context,
4770 NULL, context_count, sizeof(void *));
4772 /* pull back stuff from slices to master context */
4773 hx = h->thread_context[context_count - 1];
4776 h->droppable = hx->droppable;
4777 h->picture_structure = hx->picture_structure;
4778 if (CONFIG_ERROR_RESILIENCE) {
4779 for (i = 1; i < context_count; i++)
4780 h->er.error_count += h->thread_context[i]->er.error_count;
4787 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
4789 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4790 int parse_extradata)
4792 AVCodecContext *const avctx = h->avctx;
4793 H264Context *hx; ///< thread context
4795 unsigned context_count;
4797 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4798 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4801 int first_slice = 0;
4804 h->nal_unit_type= 0;
4806 if(!h->slice_context_count)
4807 h->slice_context_count= 1;
4808 h->max_contexts = h->slice_context_count;
4809 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4810 h->current_slice = 0;
4811 if (!h->first_field)
4812 h->cur_pic_ptr = NULL;
4813 ff_h264_reset_sei(h);
4816 if (h->nal_length_size == 4) {
4817 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4819 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4823 for (; pass <= 1; pass++) {
4826 next_avc = h->is_avc ? 0 : buf_size;
4836 if (buf_index >= next_avc) {
4837 if (buf_index >= buf_size - h->nal_length_size)
4840 for (i = 0; i < h->nal_length_size; i++)
4841 nalsize = (nalsize << 8) | buf[buf_index++];
4842 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4843 av_log(h->avctx, AV_LOG_ERROR,
4844 "AVC: nal size %d\n", nalsize);
4847 next_avc = buf_index + nalsize;
4849 // start code prefix search
4850 for (; buf_index + 3 < next_avc; buf_index++)
4851 // This should always succeed in the first iteration.
4852 if (buf[buf_index] == 0 &&
4853 buf[buf_index + 1] == 0 &&
4854 buf[buf_index + 2] == 1)
4857 if (buf_index + 3 >= buf_size) {
4858 buf_index = buf_size;
4863 if (buf_index >= next_avc)
4867 hx = h->thread_context[context_count];
4869 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4870 &consumed, next_avc - buf_index);
4871 if (ptr == NULL || dst_length < 0) {
4875 i = buf_index + consumed;
4876 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4877 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4878 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4879 h->workaround_bugs |= FF_BUG_TRUNCATED;
4881 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4882 while (dst_length > 0 && ptr[dst_length - 1] == 0)
4884 bit_length = !dst_length ? 0
4886 decode_rbsp_trailing(h, ptr + dst_length - 1));
4888 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4889 av_log(h->avctx, AV_LOG_DEBUG,
4890 "NAL %d/%d at %d/%d length %d pass %d\n",
4891 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
4893 if (h->is_avc && (nalsize != consumed) && nalsize)
4894 av_log(h->avctx, AV_LOG_DEBUG,
4895 "AVC: Consumed only %d bytes instead of %d\n",
4898 buf_index += consumed;
4902 /* packets can sometimes contain multiple PPS/SPS,
4903 * e.g. two PAFF field pictures in one packet, or a demuxer
4904 * which splits NALs strangely if so, when frame threading we
4905 * can't start the next thread until we've read all of them */
4906 switch (hx->nal_unit_type) {
4909 nals_needed = nal_index;
4914 init_get_bits(&hx->gb, ptr, bit_length);
4915 if (!get_ue_golomb(&hx->gb) ||
4917 first_slice != hx->nal_unit_type)
4918 nals_needed = nal_index;
4920 first_slice = hx->nal_unit_type;
4926 switch (hx->nal_unit_type) {
4930 first_slice = hx->nal_unit_type;
4933 if (avctx->skip_frame >= AVDISCARD_NONREF &&
4934 h->nal_ref_idc == 0 &&
4935 h->nal_unit_type != NAL_SEI)
4939 if ( !(avctx->active_thread_type & FF_THREAD_FRAME)
4940 || nals_needed >= nal_index)
4942 /* Ignore per frame NAL unit type during extradata
4943 * parsing. Decoding slices is not possible in codec init
4945 if (parse_extradata) {
4946 switch (hx->nal_unit_type) {
4952 av_log(h->avctx, AV_LOG_WARNING,
4953 "Ignoring NAL %d in global header/extradata\n",
4955 // fall through to next case
4956 case NAL_AUXILIARY_SLICE:
4957 hx->nal_unit_type = NAL_FF_IGNORE;
4963 switch (hx->nal_unit_type) {
4965 if (h->nal_unit_type != NAL_IDR_SLICE) {
4966 av_log(h->avctx, AV_LOG_ERROR,
4967 "Invalid mix of idr and non-idr slices\n");
4972 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4975 init_get_bits(&hx->gb, ptr, bit_length);
4977 hx->inter_gb_ptr = &hx->gb;
4978 hx->data_partitioning = 0;
4980 if ((err = decode_slice_header(hx, h)))
4983 if (h->sei_recovery_frame_cnt >= 0) {
4984 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
4985 h->valid_recovery_point = 1;
4987 if ( h->recovery_frame < 0
4988 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
4989 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4990 ((1 << h->sps.log2_max_frame_num) - 1);
4992 if (!h->valid_recovery_point)
4993 h->recovery_frame = h->frame_num;
4997 h->cur_pic_ptr->f.key_frame |=
4998 (hx->nal_unit_type == NAL_IDR_SLICE);
5000 if (hx->nal_unit_type == NAL_IDR_SLICE ||
5001 h->recovery_frame == h->frame_num) {
5002 h->recovery_frame = -1;
5003 h->cur_pic_ptr->recovered = 1;
5005 // If we have an IDR, all frames after it in decoded order are
5007 if (hx->nal_unit_type == NAL_IDR_SLICE)
5008 h->frame_recovered |= FRAME_RECOVERED_IDR;
5009 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
5010 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
5012 h->cur_pic_ptr->recovered |= h->frame_recovered;
5014 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
5017 if (h->current_slice == 1) {
5018 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
5019 decode_postinit(h, nal_index >= nals_needed);
5021 if (h->avctx->hwaccel &&
5022 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
5024 if (CONFIG_H264_VDPAU_DECODER &&
5025 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
5026 ff_vdpau_h264_picture_start(h);
5029 if (hx->redundant_pic_count == 0 &&
5030 (avctx->skip_frame < AVDISCARD_NONREF ||
5032 (avctx->skip_frame < AVDISCARD_BIDIR ||
5033 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
5034 (avctx->skip_frame < AVDISCARD_NONKEY ||
5035 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
5036 avctx->skip_frame < AVDISCARD_ALL) {
5037 if (avctx->hwaccel) {
5038 ret = avctx->hwaccel->decode_slice(avctx,
5039 &buf[buf_index - consumed],
5043 } else if (CONFIG_H264_VDPAU_DECODER &&
5044 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
5045 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
5047 sizeof(start_code));
5048 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
5049 &buf[buf_index - consumed],
5056 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
5057 av_log(h->avctx, AV_LOG_ERROR,
5058 "Decoding in chunks is not supported for "
5059 "partitioned slices.\n");
5060 return AVERROR(ENOSYS);
5063 init_get_bits(&hx->gb, ptr, bit_length);
5065 hx->inter_gb_ptr = NULL;
5067 if ((err = decode_slice_header(hx, h)) < 0) {
5068 /* make sure data_partitioning is cleared if it was set
5069 * before, so we don't try decoding a slice without a valid
5070 * slice header later */
5071 h->data_partitioning = 0;
5075 hx->data_partitioning = 1;
5078 init_get_bits(&hx->intra_gb, ptr, bit_length);
5079 hx->intra_gb_ptr = &hx->intra_gb;
5082 init_get_bits(&hx->inter_gb, ptr, bit_length);
5083 hx->inter_gb_ptr = &hx->inter_gb;
5085 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
5088 if (hx->redundant_pic_count == 0 &&
5090 hx->data_partitioning &&
5091 h->cur_pic_ptr && h->context_initialized &&
5092 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
5093 (avctx->skip_frame < AVDISCARD_BIDIR ||
5094 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
5095 (avctx->skip_frame < AVDISCARD_NONKEY ||
5096 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
5097 avctx->skip_frame < AVDISCARD_ALL)
5101 init_get_bits(&h->gb, ptr, bit_length);
5102 ff_h264_decode_sei(h);
5105 init_get_bits(&h->gb, ptr, bit_length);
5106 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
5107 av_log(h->avctx, AV_LOG_DEBUG,
5108 "SPS decoding failure, trying again with the complete NAL\n");
5110 av_assert0(next_avc - buf_index + consumed == nalsize);
5111 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
5113 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
5114 8*(next_avc - buf_index + consumed - 1));
5115 ff_h264_decode_seq_parameter_set(h);
5120 init_get_bits(&h->gb, ptr, bit_length);
5121 ff_h264_decode_picture_parameter_set(h, bit_length);
5124 case NAL_END_SEQUENCE:
5125 case NAL_END_STREAM:
5126 case NAL_FILLER_DATA:
5128 case NAL_AUXILIARY_SLICE:
5133 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
5134 hx->nal_unit_type, bit_length);
5137 if (context_count == h->max_contexts) {
5138 execute_decode_slices(h, context_count);
5143 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
5144 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
5145 } else if (err == 1) {
5146 /* Slice could not be decoded in parallel mode, copy down
5147 * NAL unit stuff to context 0 and restart. Note that
5148 * rbsp_buffer is not transferred, but since we no longer
5149 * run in parallel mode this should not be an issue. */
5150 h->nal_unit_type = hx->nal_unit_type;
5151 h->nal_ref_idc = hx->nal_ref_idc;
5158 execute_decode_slices(h, context_count);
5162 if (h->cur_pic_ptr && !h->droppable) {
5163 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
5164 h->picture_structure == PICT_BOTTOM_FIELD);
5167 return (ret < 0) ? ret : buf_index;
5171 * Return the number of bytes consumed for building the current frame.
5173 static int get_consumed_bytes(int pos, int buf_size)
5176 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
5177 if (pos + 10 > buf_size)
5178 pos = buf_size; // oops ;)
5183 static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
5185 AVFrame *src = &srcp->f;
5186 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
5188 int ret = av_frame_ref(dst, src);
5192 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
5197 for (i = 0; i < desc->nb_components; i++) {
5198 int hshift = (i > 0) ? desc->log2_chroma_w : 0;
5199 int vshift = (i > 0) ? desc->log2_chroma_h : 0;
5200 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
5201 (srcp->crop_top >> vshift) * dst->linesize[i];
5202 dst->data[i] += off;
5207 static int h264_decode_frame(AVCodecContext *avctx, void *data,
5208 int *got_frame, AVPacket *avpkt)
5210 const uint8_t *buf = avpkt->data;
5211 int buf_size = avpkt->size;
5212 H264Context *h = avctx->priv_data;
5213 AVFrame *pict = data;
5219 h->flags = avctx->flags;
5220 /* reset data partitioning here, to ensure GetBitContexts from previous
5221 * packets do not get used. */
5222 h->data_partitioning = 0;
5224 /* end of stream, output what is still in the buffers */
5225 if (buf_size == 0) {
5228 h->cur_pic_ptr = NULL;
5231 // FIXME factorize this with the output code below
5232 out = h->delayed_pic[0];
5235 h->delayed_pic[i] &&
5236 !h->delayed_pic[i]->f.key_frame &&
5237 !h->delayed_pic[i]->mmco_reset;
5239 if (h->delayed_pic[i]->poc < out->poc) {
5240 out = h->delayed_pic[i];
5244 for (i = out_idx; h->delayed_pic[i]; i++)
5245 h->delayed_pic[i] = h->delayed_pic[i + 1];
5248 out->reference &= ~DELAYED_PIC_REF;
5249 ret = output_frame(h, pict, out);
5257 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
5258 int cnt= buf[5]&0x1f;
5259 const uint8_t *p= buf+6;
5261 int nalsize= AV_RB16(p) + 2;
5262 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
5270 int nalsize= AV_RB16(p) + 2;
5271 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
5276 return ff_h264_decode_extradata(h, buf, buf_size);
5280 buf_index = decode_nal_units(h, buf, buf_size, 0);
5282 return AVERROR_INVALIDDATA;
5284 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
5285 av_assert0(buf_index <= buf_size);
5289 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
5290 if (avctx->skip_frame >= AVDISCARD_NONREF ||
5291 buf_size >= 4 && !memcmp("Q264", buf, 4))
5293 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
5294 return AVERROR_INVALIDDATA;
5297 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
5298 (h->mb_y >= h->mb_height && h->mb_height)) {
5299 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
5300 decode_postinit(h, 1);
5304 /* Wait for second field. */
5306 if (h->next_output_pic && (
5307 h->next_output_pic->recovered)) {
5308 if (!h->next_output_pic->recovered)
5309 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
5311 ret = output_frame(h, pict, h->next_output_pic);
5315 if (CONFIG_MPEGVIDEO) {
5316 ff_print_debug_info2(h->avctx, h->next_output_pic, pict, h->er.mbskip_table,
5318 h->mb_width, h->mb_height, h->mb_stride, 1);
5323 assert(pict->buf[0] || !*got_frame);
5325 return get_consumed_bytes(buf_index, buf_size);
5328 av_cold void ff_h264_free_context(H264Context *h)
5332 free_tables(h, 1); // FIXME cleanup init stuff perhaps
5334 for (i = 0; i < MAX_SPS_COUNT; i++)
5335 av_freep(h->sps_buffers + i);
5337 for (i = 0; i < MAX_PPS_COUNT; i++)
5338 av_freep(h->pps_buffers + i);
5341 static av_cold int h264_decode_end(AVCodecContext *avctx)
5343 H264Context *h = avctx->priv_data;
5345 ff_h264_remove_all_refs(h);
5346 ff_h264_free_context(h);
5348 unref_picture(h, &h->cur_pic);
5353 static const AVProfile profiles[] = {
5354 { FF_PROFILE_H264_BASELINE, "Baseline" },
5355 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
5356 { FF_PROFILE_H264_MAIN, "Main" },
5357 { FF_PROFILE_H264_EXTENDED, "Extended" },
5358 { FF_PROFILE_H264_HIGH, "High" },
5359 { FF_PROFILE_H264_HIGH_10, "High 10" },
5360 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
5361 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
5362 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
5363 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
5364 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
5365 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
5366 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
5367 { FF_PROFILE_UNKNOWN },
5370 static const AVOption h264_options[] = {
5371 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
5372 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
5376 static const AVClass h264_class = {
5377 .class_name = "H264 Decoder",
5378 .item_name = av_default_item_name,
5379 .option = h264_options,
5380 .version = LIBAVUTIL_VERSION_INT,
5383 static const AVClass h264_vdpau_class = {
5384 .class_name = "H264 VDPAU Decoder",
5385 .item_name = av_default_item_name,
5386 .option = h264_options,
5387 .version = LIBAVUTIL_VERSION_INT,
5390 AVCodec ff_h264_decoder = {
5392 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5393 .type = AVMEDIA_TYPE_VIDEO,
5394 .id = AV_CODEC_ID_H264,
5395 .priv_data_size = sizeof(H264Context),
5396 .init = ff_h264_decode_init,
5397 .close = h264_decode_end,
5398 .decode = h264_decode_frame,
5399 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5400 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
5401 CODEC_CAP_FRAME_THREADS,
5403 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
5404 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5405 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5406 .priv_class = &h264_class,
5409 #if CONFIG_H264_VDPAU_DECODER
5410 AVCodec ff_h264_vdpau_decoder = {
5411 .name = "h264_vdpau",
5412 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
5413 .type = AVMEDIA_TYPE_VIDEO,
5414 .id = AV_CODEC_ID_H264,
5415 .priv_data_size = sizeof(H264Context),
5416 .init = ff_h264_decode_init,
5417 .close = h264_decode_end,
5418 .decode = h264_decode_frame,
5419 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5421 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
5423 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5424 .priv_class = &h264_vdpau_class,