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"
36 #include "cabac_functions.h"
38 #include "error_resilience.h"
40 #include "mpegvideo.h"
43 #include "h264chroma.h"
44 #include "h264_mvpred.h"
47 #include "rectangle.h"
50 #include "vdpau_internal.h"
54 static void flush_change(H264Context *h);
56 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
58 static const uint8_t rem6[QP_MAX_NUM + 1] = {
59 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
60 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
61 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
62 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
66 static const uint8_t div6[QP_MAX_NUM + 1] = {
67 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
68 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
69 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
70 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
74 static const uint8_t field_scan[16+1] = {
75 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
76 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
77 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
78 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
81 static const uint8_t field_scan8x8[64+1] = {
82 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
83 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
84 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
85 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
86 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
87 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
88 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
89 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
90 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
91 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
92 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
93 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
94 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
95 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
96 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
97 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
100 static const uint8_t field_scan8x8_cavlc[64+1] = {
101 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
102 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
103 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
104 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
105 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
106 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
107 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
108 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
109 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
110 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
111 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
112 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
113 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
114 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
115 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
116 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
119 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
120 static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
121 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
122 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
123 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
124 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
125 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
126 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
127 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
128 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
129 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
130 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
131 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
132 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
133 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
134 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
135 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
136 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
139 static const uint8_t dequant4_coeff_init[6][3] = {
148 static const uint8_t dequant8_coeff_init_scan[16] = {
149 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
152 static const uint8_t dequant8_coeff_init[6][6] = {
153 { 20, 18, 32, 19, 25, 24 },
154 { 22, 19, 35, 21, 28, 26 },
155 { 26, 23, 42, 24, 33, 31 },
156 { 28, 25, 45, 26, 35, 33 },
157 { 32, 28, 51, 30, 40, 38 },
158 { 36, 32, 58, 34, 46, 43 },
161 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
162 #if CONFIG_H264_DXVA2_HWACCEL
163 AV_PIX_FMT_DXVA2_VLD,
165 #if CONFIG_H264_VAAPI_HWACCEL
166 AV_PIX_FMT_VAAPI_VLD,
168 #if CONFIG_H264_VDA_HWACCEL
171 #if CONFIG_H264_VDPAU_HWACCEL
178 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
179 #if CONFIG_H264_DXVA2_HWACCEL
180 AV_PIX_FMT_DXVA2_VLD,
182 #if CONFIG_H264_VAAPI_HWACCEL
183 AV_PIX_FMT_VAAPI_VLD,
185 #if CONFIG_H264_VDA_HWACCEL
188 #if CONFIG_H264_VDPAU_HWACCEL
195 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
197 H264Context *h = avctx->priv_data;
198 return h ? h->sps.num_reorder_frames : 0;
201 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
203 int mb_x, int mb_y, int mb_intra, int mb_skipped)
205 H264Context *h = opaque;
209 h->mb_xy = mb_x + mb_y * h->mb_stride;
210 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
211 av_assert1(ref >= 0);
212 /* FIXME: It is possible albeit uncommon that slice references
213 * differ between slices. We take the easy approach and ignore
214 * it for now. If this turns out to have any relevance in
215 * practice then correct remapping should be added. */
216 if (ref >= h->ref_count[0])
218 if (!h->ref_list[0][ref].f.data[0]) {
219 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
222 if ((h->ref_list[0][ref].reference&3) != 3) {
223 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
226 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
228 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
229 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
230 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
232 h->mb_field_decoding_flag = 0;
233 ff_h264_hl_decode_mb(h);
236 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
238 AVCodecContext *avctx = h->avctx;
239 Picture *cur = &h->cur_pic;
240 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
241 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
242 int vshift = desc->log2_chroma_h;
243 const int field_pic = h->picture_structure != PICT_FRAME;
249 height = FFMIN(height, avctx->height - y);
251 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
254 if (avctx->draw_horiz_band) {
256 int offset[AV_NUM_DATA_POINTERS];
259 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
260 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
267 offset[0] = y * src->linesize[0];
269 offset[2] = (y >> vshift) * src->linesize[1];
270 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
275 avctx->draw_horiz_band(avctx, src, offset,
276 y, h->picture_structure, height);
280 static void unref_picture(H264Context *h, Picture *pic)
282 int off = offsetof(Picture, tf) + sizeof(pic->tf);
288 ff_thread_release_buffer(h->avctx, &pic->tf);
289 av_buffer_unref(&pic->hwaccel_priv_buf);
291 av_buffer_unref(&pic->qscale_table_buf);
292 av_buffer_unref(&pic->mb_type_buf);
293 for (i = 0; i < 2; i++) {
294 av_buffer_unref(&pic->motion_val_buf[i]);
295 av_buffer_unref(&pic->ref_index_buf[i]);
298 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
301 static void release_unused_pictures(H264Context *h, int remove_current)
305 /* release non reference frames */
306 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
307 if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
308 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
309 unref_picture(h, &h->DPB[i]);
314 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
318 av_assert0(!dst->f.buf[0]);
319 av_assert0(src->f.buf[0]);
323 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
327 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
328 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
329 if (!dst->qscale_table_buf || !dst->mb_type_buf)
331 dst->qscale_table = src->qscale_table;
332 dst->mb_type = src->mb_type;
334 for (i = 0; i < 2; i++) {
335 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
336 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
337 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
339 dst->motion_val[i] = src->motion_val[i];
340 dst->ref_index[i] = src->ref_index[i];
343 if (src->hwaccel_picture_private) {
344 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
345 if (!dst->hwaccel_priv_buf)
347 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
350 for (i = 0; i < 2; i++)
351 dst->field_poc[i] = src->field_poc[i];
353 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
354 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
357 dst->frame_num = src->frame_num;
358 dst->mmco_reset = src->mmco_reset;
359 dst->pic_id = src->pic_id;
360 dst->long_ref = src->long_ref;
361 dst->mbaff = src->mbaff;
362 dst->field_picture = src->field_picture;
363 dst->needs_realloc = src->needs_realloc;
364 dst->reference = src->reference;
365 dst->crop = src->crop;
366 dst->crop_left = src->crop_left;
367 dst->crop_top = src->crop_top;
368 dst->recovered = src->recovered;
372 unref_picture(h, dst);
376 static int alloc_scratch_buffers(H264Context *h, int linesize)
378 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
380 if (h->bipred_scratchpad)
383 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
384 // edge emu needs blocksize + filter length - 1
385 // (= 21x21 for h264)
386 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
387 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
389 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
390 av_freep(&h->bipred_scratchpad);
391 av_freep(&h->edge_emu_buffer);
392 av_freep(&h->me.scratchpad);
393 return AVERROR(ENOMEM);
396 h->me.temp = h->me.scratchpad;
401 static int init_table_pools(H264Context *h)
403 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
404 const int mb_array_size = h->mb_stride * h->mb_height;
405 const int b4_stride = h->mb_width * 4 + 1;
406 const int b4_array_size = b4_stride * h->mb_height * 4;
408 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
410 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
411 sizeof(uint32_t), av_buffer_allocz);
412 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
413 sizeof(int16_t), av_buffer_allocz);
414 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
416 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
417 !h->ref_index_pool) {
418 av_buffer_pool_uninit(&h->qscale_table_pool);
419 av_buffer_pool_uninit(&h->mb_type_pool);
420 av_buffer_pool_uninit(&h->motion_val_pool);
421 av_buffer_pool_uninit(&h->ref_index_pool);
422 return AVERROR(ENOMEM);
428 static int alloc_picture(H264Context *h, Picture *pic)
432 av_assert0(!pic->f.data[0]);
435 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
436 AV_GET_BUFFER_FLAG_REF : 0);
440 h->linesize = pic->f.linesize[0];
441 h->uvlinesize = pic->f.linesize[1];
442 pic->crop = h->sps.crop;
443 pic->crop_top = h->sps.crop_top;
444 pic->crop_left= h->sps.crop_left;
446 if (h->avctx->hwaccel) {
447 const AVHWAccel *hwaccel = h->avctx->hwaccel;
448 av_assert0(!pic->hwaccel_picture_private);
449 if (hwaccel->priv_data_size) {
450 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
451 if (!pic->hwaccel_priv_buf)
452 return AVERROR(ENOMEM);
453 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
457 if (!h->qscale_table_pool) {
458 ret = init_table_pools(h);
463 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
464 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
465 if (!pic->qscale_table_buf || !pic->mb_type_buf)
468 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
469 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
471 for (i = 0; i < 2; i++) {
472 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
473 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
474 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
477 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
478 pic->ref_index[i] = pic->ref_index_buf[i]->data;
483 unref_picture(h, pic);
484 return (ret < 0) ? ret : AVERROR(ENOMEM);
487 static inline int pic_is_unused(H264Context *h, Picture *pic)
491 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
496 static int find_unused_picture(H264Context *h)
500 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
501 if (pic_is_unused(h, &h->DPB[i]))
504 if (i == MAX_PICTURE_COUNT)
505 return AVERROR_INVALIDDATA;
507 if (h->DPB[i].needs_realloc) {
508 h->DPB[i].needs_realloc = 0;
509 unref_picture(h, &h->DPB[i]);
516 * Check if the top & left blocks are available if needed and
517 * change the dc mode so it only uses the available blocks.
519 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
521 static const int8_t top[12] = {
522 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
524 static const int8_t left[12] = {
525 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
529 if (!(h->top_samples_available & 0x8000)) {
530 for (i = 0; i < 4; i++) {
531 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
533 av_log(h->avctx, AV_LOG_ERROR,
534 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
535 status, h->mb_x, h->mb_y);
536 return AVERROR_INVALIDDATA;
538 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
543 if ((h->left_samples_available & 0x8888) != 0x8888) {
544 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
545 for (i = 0; i < 4; i++)
546 if (!(h->left_samples_available & mask[i])) {
547 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
549 av_log(h->avctx, AV_LOG_ERROR,
550 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
551 status, h->mb_x, h->mb_y);
552 return AVERROR_INVALIDDATA;
554 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
560 } // FIXME cleanup like ff_h264_check_intra_pred_mode
563 * Check if the top & left blocks are available if needed and
564 * change the dc mode so it only uses the available blocks.
566 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
568 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
569 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
572 av_log(h->avctx, AV_LOG_ERROR,
573 "out of range intra chroma pred mode at %d %d\n",
575 return AVERROR_INVALIDDATA;
578 if (!(h->top_samples_available & 0x8000)) {
581 av_log(h->avctx, AV_LOG_ERROR,
582 "top block unavailable for requested intra mode at %d %d\n",
584 return AVERROR_INVALIDDATA;
588 if ((h->left_samples_available & 0x8080) != 0x8080) {
590 if (is_chroma && (h->left_samples_available & 0x8080)) {
591 // mad cow disease mode, aka MBAFF + constrained_intra_pred
592 mode = ALZHEIMER_DC_L0T_PRED8x8 +
593 (!(h->left_samples_available & 0x8000)) +
594 2 * (mode == DC_128_PRED8x8);
597 av_log(h->avctx, AV_LOG_ERROR,
598 "left block unavailable for requested intra mode at %d %d\n",
600 return AVERROR_INVALIDDATA;
607 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
608 int *dst_length, int *consumed, int length)
614 // src[0]&0x80; // forbidden bit
615 h->nal_ref_idc = src[0] >> 5;
616 h->nal_unit_type = src[0] & 0x1F;
621 #define STARTCODE_TEST \
622 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
623 if (src[i + 2] != 3) { \
624 /* startcode, so we must be past the end */ \
630 #if HAVE_FAST_UNALIGNED
631 #define FIND_FIRST_ZERO \
632 if (i > 0 && !src[i]) \
638 for (i = 0; i + 1 < length; i += 9) {
639 if (!((~AV_RN64A(src + i) &
640 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
641 0x8000800080008080ULL))
648 for (i = 0; i + 1 < length; i += 5) {
649 if (!((~AV_RN32A(src + i) &
650 (AV_RN32A(src + i) - 0x01000101U)) &
659 for (i = 0; i + 1 < length; i += 2) {
662 if (i > 0 && src[i - 1] == 0)
668 // use second escape buffer for inter data
669 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
671 si = h->rbsp_buffer_size[bufidx];
672 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
673 dst = h->rbsp_buffer[bufidx];
678 if(i>=length-1){ //no escaped 0
680 *consumed= length+1; //+1 for the header
681 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
684 memcpy(dst, src, length);
691 while (si + 2 < length) {
692 // remove escapes (very rare 1:2^22)
693 if (src[si + 2] > 3) {
694 dst[di++] = src[si++];
695 dst[di++] = src[si++];
696 } else if (src[si] == 0 && src[si + 1] == 0) {
697 if (src[si + 2] == 3) { // escape
702 } else // next start code
706 dst[di++] = src[si++];
709 dst[di++] = src[si++];
712 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
715 *consumed = si + 1; // +1 for the header
716 /* FIXME store exact number of bits in the getbitcontext
717 * (it is needed for decoding) */
722 * Identify the exact end of the bitstream
723 * @return the length of the trailing, or 0 if damaged
725 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
730 tprintf(h->avctx, "rbsp trailing %X\n", v);
732 for (r = 1; r < 9; r++) {
740 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
741 int height, int y_offset, int list)
743 int raw_my = h->mv_cache[list][scan8[n]][1];
744 int filter_height_down = (raw_my & 3) ? 3 : 0;
745 int full_my = (raw_my >> 2) + y_offset;
746 int bottom = full_my + filter_height_down + height;
748 av_assert2(height >= 0);
750 return FFMAX(0, bottom);
753 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
754 int height, int y_offset, int list0,
755 int list1, int *nrefs)
759 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
762 int ref_n = h->ref_cache[0][scan8[n]];
763 Picture *ref = &h->ref_list[0][ref_n];
765 // Error resilience puts the current picture in the ref list.
766 // Don't try to wait on these as it will cause a deadlock.
767 // Fields can wait on each other, though.
768 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
769 (ref->reference & 3) != h->picture_structure) {
770 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
771 if (refs[0][ref_n] < 0)
773 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
778 int ref_n = h->ref_cache[1][scan8[n]];
779 Picture *ref = &h->ref_list[1][ref_n];
781 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
782 (ref->reference & 3) != h->picture_structure) {
783 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
784 if (refs[1][ref_n] < 0)
786 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
792 * Wait until all reference frames are available for MC operations.
794 * @param h the H264 context
796 static void await_references(H264Context *h)
798 const int mb_xy = h->mb_xy;
799 const int mb_type = h->cur_pic.mb_type[mb_xy];
801 int nrefs[2] = { 0 };
804 memset(refs, -1, sizeof(refs));
806 if (IS_16X16(mb_type)) {
807 get_lowest_part_y(h, refs, 0, 16, 0,
808 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
809 } else if (IS_16X8(mb_type)) {
810 get_lowest_part_y(h, refs, 0, 8, 0,
811 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
812 get_lowest_part_y(h, refs, 8, 8, 8,
813 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
814 } else if (IS_8X16(mb_type)) {
815 get_lowest_part_y(h, refs, 0, 16, 0,
816 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
817 get_lowest_part_y(h, refs, 4, 16, 0,
818 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
822 av_assert2(IS_8X8(mb_type));
824 for (i = 0; i < 4; i++) {
825 const int sub_mb_type = h->sub_mb_type[i];
827 int y_offset = (i & 2) << 2;
829 if (IS_SUB_8X8(sub_mb_type)) {
830 get_lowest_part_y(h, refs, n, 8, y_offset,
831 IS_DIR(sub_mb_type, 0, 0),
832 IS_DIR(sub_mb_type, 0, 1),
834 } else if (IS_SUB_8X4(sub_mb_type)) {
835 get_lowest_part_y(h, refs, n, 4, y_offset,
836 IS_DIR(sub_mb_type, 0, 0),
837 IS_DIR(sub_mb_type, 0, 1),
839 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
840 IS_DIR(sub_mb_type, 0, 0),
841 IS_DIR(sub_mb_type, 0, 1),
843 } else if (IS_SUB_4X8(sub_mb_type)) {
844 get_lowest_part_y(h, refs, n, 8, y_offset,
845 IS_DIR(sub_mb_type, 0, 0),
846 IS_DIR(sub_mb_type, 0, 1),
848 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
849 IS_DIR(sub_mb_type, 0, 0),
850 IS_DIR(sub_mb_type, 0, 1),
854 av_assert2(IS_SUB_4X4(sub_mb_type));
855 for (j = 0; j < 4; j++) {
856 int sub_y_offset = y_offset + 2 * (j & 2);
857 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
858 IS_DIR(sub_mb_type, 0, 0),
859 IS_DIR(sub_mb_type, 0, 1),
866 for (list = h->list_count - 1; list >= 0; list--)
867 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
868 int row = refs[list][ref];
870 Picture *ref_pic = &h->ref_list[list][ref];
871 int ref_field = ref_pic->reference - 1;
872 int ref_field_picture = ref_pic->field_picture;
873 int pic_height = 16 * h->mb_height >> ref_field_picture;
878 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
879 ff_thread_await_progress(&ref_pic->tf,
880 FFMIN((row >> 1) - !(row & 1),
883 ff_thread_await_progress(&ref_pic->tf,
884 FFMIN((row >> 1), pic_height - 1),
886 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
887 ff_thread_await_progress(&ref_pic->tf,
888 FFMIN(row * 2 + ref_field,
891 } else if (FIELD_PICTURE(h)) {
892 ff_thread_await_progress(&ref_pic->tf,
893 FFMIN(row, pic_height - 1),
896 ff_thread_await_progress(&ref_pic->tf,
897 FFMIN(row, pic_height - 1),
904 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
905 int n, int square, int height,
907 uint8_t *dest_y, uint8_t *dest_cb,
909 int src_x_offset, int src_y_offset,
910 qpel_mc_func *qpix_op,
911 h264_chroma_mc_func chroma_op,
912 int pixel_shift, int chroma_idc)
914 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
915 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
916 const int luma_xy = (mx & 3) + ((my & 3) << 2);
917 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
918 uint8_t *src_y = pic->f.data[0] + offset;
919 uint8_t *src_cb, *src_cr;
921 int extra_height = 0;
923 const int full_mx = mx >> 2;
924 const int full_my = my >> 2;
925 const int pic_width = 16 * h->mb_width;
926 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
934 if (full_mx < 0 - extra_width ||
935 full_my < 0 - extra_height ||
936 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
937 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
938 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
939 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
940 h->mb_linesize, h->mb_linesize,
941 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
942 full_my - 2, pic_width, pic_height);
943 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
947 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
949 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
951 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
954 if (chroma_idc == 3 /* yuv444 */) {
955 src_cb = pic->f.data[1] + offset;
957 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
958 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
959 h->mb_linesize, h->mb_linesize,
960 16 + 5, 16 + 5 /*FIXME*/,
961 full_mx - 2, full_my - 2,
962 pic_width, pic_height);
963 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
965 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
967 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
969 src_cr = pic->f.data[2] + offset;
971 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
972 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
973 h->mb_linesize, h->mb_linesize,
974 16 + 5, 16 + 5 /*FIXME*/,
975 full_mx - 2, full_my - 2,
976 pic_width, pic_height);
977 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
979 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
981 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
985 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
986 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
987 // chroma offset when predicting from a field of opposite parity
988 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
989 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
992 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
993 (my >> ysh) * h->mb_uvlinesize;
994 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
995 (my >> ysh) * h->mb_uvlinesize;
998 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
999 h->mb_uvlinesize, h->mb_uvlinesize,
1000 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1001 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1002 src_cb = h->edge_emu_buffer;
1004 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
1005 height >> (chroma_idc == 1 /* yuv420 */),
1006 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1009 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
1010 h->mb_uvlinesize, h->mb_uvlinesize,
1011 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1012 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1013 src_cr = h->edge_emu_buffer;
1015 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
1016 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1019 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
1020 int height, int delta,
1021 uint8_t *dest_y, uint8_t *dest_cb,
1023 int x_offset, int y_offset,
1024 qpel_mc_func *qpix_put,
1025 h264_chroma_mc_func chroma_put,
1026 qpel_mc_func *qpix_avg,
1027 h264_chroma_mc_func chroma_avg,
1028 int list0, int list1,
1029 int pixel_shift, int chroma_idc)
1031 qpel_mc_func *qpix_op = qpix_put;
1032 h264_chroma_mc_func chroma_op = chroma_put;
1034 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1035 if (chroma_idc == 3 /* yuv444 */) {
1036 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1037 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1038 } else if (chroma_idc == 2 /* yuv422 */) {
1039 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1040 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1041 } else { /* yuv420 */
1042 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1043 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1045 x_offset += 8 * h->mb_x;
1046 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1049 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1050 mc_dir_part(h, ref, n, square, height, delta, 0,
1051 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1052 qpix_op, chroma_op, pixel_shift, chroma_idc);
1055 chroma_op = chroma_avg;
1059 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1060 mc_dir_part(h, ref, n, square, height, delta, 1,
1061 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1062 qpix_op, chroma_op, pixel_shift, chroma_idc);
1066 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1067 int height, int delta,
1068 uint8_t *dest_y, uint8_t *dest_cb,
1070 int x_offset, int y_offset,
1071 qpel_mc_func *qpix_put,
1072 h264_chroma_mc_func chroma_put,
1073 h264_weight_func luma_weight_op,
1074 h264_weight_func chroma_weight_op,
1075 h264_biweight_func luma_weight_avg,
1076 h264_biweight_func chroma_weight_avg,
1077 int list0, int list1,
1078 int pixel_shift, int chroma_idc)
1082 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1083 if (chroma_idc == 3 /* yuv444 */) {
1084 chroma_height = height;
1085 chroma_weight_avg = luma_weight_avg;
1086 chroma_weight_op = luma_weight_op;
1087 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1088 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1089 } else if (chroma_idc == 2 /* yuv422 */) {
1090 chroma_height = height;
1091 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1092 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1093 } else { /* yuv420 */
1094 chroma_height = height >> 1;
1095 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1096 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1098 x_offset += 8 * h->mb_x;
1099 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1101 if (list0 && list1) {
1102 /* don't optimize for luma-only case, since B-frames usually
1103 * use implicit weights => chroma too. */
1104 uint8_t *tmp_cb = h->bipred_scratchpad;
1105 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1106 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1107 int refn0 = h->ref_cache[0][scan8[n]];
1108 int refn1 = h->ref_cache[1][scan8[n]];
1110 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1111 dest_y, dest_cb, dest_cr,
1112 x_offset, y_offset, qpix_put, chroma_put,
1113 pixel_shift, chroma_idc);
1114 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1115 tmp_y, tmp_cb, tmp_cr,
1116 x_offset, y_offset, qpix_put, chroma_put,
1117 pixel_shift, chroma_idc);
1119 if (h->use_weight == 2) {
1120 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1121 int weight1 = 64 - weight0;
1122 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1123 height, 5, weight0, weight1, 0);
1124 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1125 chroma_height, 5, weight0, weight1, 0);
1126 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1127 chroma_height, 5, weight0, weight1, 0);
1129 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1130 h->luma_log2_weight_denom,
1131 h->luma_weight[refn0][0][0],
1132 h->luma_weight[refn1][1][0],
1133 h->luma_weight[refn0][0][1] +
1134 h->luma_weight[refn1][1][1]);
1135 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1136 h->chroma_log2_weight_denom,
1137 h->chroma_weight[refn0][0][0][0],
1138 h->chroma_weight[refn1][1][0][0],
1139 h->chroma_weight[refn0][0][0][1] +
1140 h->chroma_weight[refn1][1][0][1]);
1141 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1142 h->chroma_log2_weight_denom,
1143 h->chroma_weight[refn0][0][1][0],
1144 h->chroma_weight[refn1][1][1][0],
1145 h->chroma_weight[refn0][0][1][1] +
1146 h->chroma_weight[refn1][1][1][1]);
1149 int list = list1 ? 1 : 0;
1150 int refn = h->ref_cache[list][scan8[n]];
1151 Picture *ref = &h->ref_list[list][refn];
1152 mc_dir_part(h, ref, n, square, height, delta, list,
1153 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1154 qpix_put, chroma_put, pixel_shift, chroma_idc);
1156 luma_weight_op(dest_y, h->mb_linesize, height,
1157 h->luma_log2_weight_denom,
1158 h->luma_weight[refn][list][0],
1159 h->luma_weight[refn][list][1]);
1160 if (h->use_weight_chroma) {
1161 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1162 h->chroma_log2_weight_denom,
1163 h->chroma_weight[refn][list][0][0],
1164 h->chroma_weight[refn][list][0][1]);
1165 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1166 h->chroma_log2_weight_denom,
1167 h->chroma_weight[refn][list][1][0],
1168 h->chroma_weight[refn][list][1][1]);
1173 static av_always_inline void prefetch_motion(H264Context *h, int list,
1174 int pixel_shift, int chroma_idc)
1176 /* fetch pixels for estimated mv 4 macroblocks ahead
1177 * optimized for 64byte cache lines */
1178 const int refn = h->ref_cache[list][scan8[0]];
1180 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1181 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1182 uint8_t **src = h->ref_list[list][refn].f.data;
1183 int off = (mx << pixel_shift) +
1184 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1185 (64 << pixel_shift);
1186 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1187 if (chroma_idc == 3 /* yuv444 */) {
1188 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1189 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1191 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
1192 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1197 static void free_tables(H264Context *h, int free_rbsp)
1202 av_freep(&h->intra4x4_pred_mode);
1203 av_freep(&h->chroma_pred_mode_table);
1204 av_freep(&h->cbp_table);
1205 av_freep(&h->mvd_table[0]);
1206 av_freep(&h->mvd_table[1]);
1207 av_freep(&h->direct_table);
1208 av_freep(&h->non_zero_count);
1209 av_freep(&h->slice_table_base);
1210 h->slice_table = NULL;
1211 av_freep(&h->list_counts);
1213 av_freep(&h->mb2b_xy);
1214 av_freep(&h->mb2br_xy);
1216 av_buffer_pool_uninit(&h->qscale_table_pool);
1217 av_buffer_pool_uninit(&h->mb_type_pool);
1218 av_buffer_pool_uninit(&h->motion_val_pool);
1219 av_buffer_pool_uninit(&h->ref_index_pool);
1221 if (free_rbsp && h->DPB) {
1222 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1223 unref_picture(h, &h->DPB[i]);
1225 } else if (h->DPB) {
1226 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1227 h->DPB[i].needs_realloc = 1;
1230 h->cur_pic_ptr = NULL;
1232 for (i = 0; i < MAX_THREADS; i++) {
1233 hx = h->thread_context[i];
1236 av_freep(&hx->top_borders[1]);
1237 av_freep(&hx->top_borders[0]);
1238 av_freep(&hx->bipred_scratchpad);
1239 av_freep(&hx->edge_emu_buffer);
1240 av_freep(&hx->dc_val_base);
1241 av_freep(&hx->me.scratchpad);
1242 av_freep(&hx->er.mb_index2xy);
1243 av_freep(&hx->er.error_status_table);
1244 av_freep(&hx->er.er_temp_buffer);
1245 av_freep(&hx->er.mbintra_table);
1246 av_freep(&hx->er.mbskip_table);
1249 av_freep(&hx->rbsp_buffer[1]);
1250 av_freep(&hx->rbsp_buffer[0]);
1251 hx->rbsp_buffer_size[0] = 0;
1252 hx->rbsp_buffer_size[1] = 0;
1255 av_freep(&h->thread_context[i]);
1259 static void init_dequant8_coeff_table(H264Context *h)
1262 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1264 for (i = 0; i < 6; i++) {
1265 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1266 for (j = 0; j < i; j++)
1267 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1268 64 * sizeof(uint8_t))) {
1269 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1275 for (q = 0; q < max_qp + 1; q++) {
1276 int shift = div6[q];
1278 for (x = 0; x < 64; x++)
1279 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1280 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1281 h->pps.scaling_matrix8[i][x]) << shift;
1286 static void init_dequant4_coeff_table(H264Context *h)
1289 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1290 for (i = 0; i < 6; i++) {
1291 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1292 for (j = 0; j < i; j++)
1293 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1294 16 * sizeof(uint8_t))) {
1295 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1301 for (q = 0; q < max_qp + 1; q++) {
1302 int shift = div6[q] + 2;
1304 for (x = 0; x < 16; x++)
1305 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1306 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1307 h->pps.scaling_matrix4[i][x]) << shift;
1312 static void init_dequant_tables(H264Context *h)
1315 init_dequant4_coeff_table(h);
1316 if (h->pps.transform_8x8_mode)
1317 init_dequant8_coeff_table(h);
1318 if (h->sps.transform_bypass) {
1319 for (i = 0; i < 6; i++)
1320 for (x = 0; x < 16; x++)
1321 h->dequant4_coeff[i][0][x] = 1 << 6;
1322 if (h->pps.transform_8x8_mode)
1323 for (i = 0; i < 6; i++)
1324 for (x = 0; x < 64; x++)
1325 h->dequant8_coeff[i][0][x] = 1 << 6;
1329 int ff_h264_alloc_tables(H264Context *h)
1331 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1332 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1335 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1336 row_mb_num * 8 * sizeof(uint8_t), fail)
1337 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1338 big_mb_num * 48 * sizeof(uint8_t), fail)
1339 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1340 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1341 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1342 big_mb_num * sizeof(uint16_t), fail)
1343 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1344 big_mb_num * sizeof(uint8_t), fail)
1345 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1346 16 * row_mb_num * sizeof(uint8_t), fail);
1347 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1348 16 * row_mb_num * sizeof(uint8_t), fail);
1349 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1350 4 * big_mb_num * sizeof(uint8_t), fail);
1351 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1352 big_mb_num * sizeof(uint8_t), fail)
1354 memset(h->slice_table_base, -1,
1355 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1356 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1358 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1359 big_mb_num * sizeof(uint32_t), fail);
1360 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1361 big_mb_num * sizeof(uint32_t), fail);
1362 for (y = 0; y < h->mb_height; y++)
1363 for (x = 0; x < h->mb_width; x++) {
1364 const int mb_xy = x + y * h->mb_stride;
1365 const int b_xy = 4 * x + 4 * y * h->b_stride;
1367 h->mb2b_xy[mb_xy] = b_xy;
1368 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1371 if (!h->dequant4_coeff[0])
1372 init_dequant_tables(h);
1375 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1377 return AVERROR(ENOMEM);
1378 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1379 av_frame_unref(&h->DPB[i].f);
1380 av_frame_unref(&h->cur_pic.f);
1387 return AVERROR(ENOMEM);
1391 * Mimic alloc_tables(), but for every context thread.
1393 static void clone_tables(H264Context *dst, H264Context *src, int i)
1395 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1396 dst->non_zero_count = src->non_zero_count;
1397 dst->slice_table = src->slice_table;
1398 dst->cbp_table = src->cbp_table;
1399 dst->mb2b_xy = src->mb2b_xy;
1400 dst->mb2br_xy = src->mb2br_xy;
1401 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1402 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1403 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1404 dst->direct_table = src->direct_table;
1405 dst->list_counts = src->list_counts;
1406 dst->DPB = src->DPB;
1407 dst->cur_pic_ptr = src->cur_pic_ptr;
1408 dst->cur_pic = src->cur_pic;
1409 dst->bipred_scratchpad = NULL;
1410 dst->edge_emu_buffer = NULL;
1411 dst->me.scratchpad = NULL;
1412 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1413 src->sps.chroma_format_idc);
1418 * Allocate buffers which are not shared amongst multiple threads.
1420 static int context_init(H264Context *h)
1422 ERContext *er = &h->er;
1423 int mb_array_size = h->mb_height * h->mb_stride;
1424 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1425 int c_size = h->mb_stride * (h->mb_height + 1);
1426 int yc_size = y_size + 2 * c_size;
1429 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1430 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1431 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1432 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1434 h->ref_cache[0][scan8[5] + 1] =
1435 h->ref_cache[0][scan8[7] + 1] =
1436 h->ref_cache[0][scan8[13] + 1] =
1437 h->ref_cache[1][scan8[5] + 1] =
1438 h->ref_cache[1][scan8[7] + 1] =
1439 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1441 if (CONFIG_ERROR_RESILIENCE) {
1443 er->avctx = h->avctx;
1445 er->decode_mb = h264_er_decode_mb;
1447 er->quarter_sample = 1;
1449 er->mb_num = h->mb_num;
1450 er->mb_width = h->mb_width;
1451 er->mb_height = h->mb_height;
1452 er->mb_stride = h->mb_stride;
1453 er->b8_stride = h->mb_width * 2 + 1;
1455 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1456 fail); // error ressilience code looks cleaner with this
1457 for (y = 0; y < h->mb_height; y++)
1458 for (x = 0; x < h->mb_width; x++)
1459 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1461 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1462 h->mb_stride + h->mb_width;
1464 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1465 mb_array_size * sizeof(uint8_t), fail);
1467 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1468 memset(er->mbintra_table, 1, mb_array_size);
1470 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1472 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1475 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1476 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1477 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1478 er->dc_val[2] = er->dc_val[1] + c_size;
1479 for (i = 0; i < yc_size; i++)
1480 h->dc_val_base[i] = 1024;
1486 return AVERROR(ENOMEM); // free_tables will clean up for us
1489 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1490 int parse_extradata);
1492 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1494 AVCodecContext *avctx = h->avctx;
1497 if (!buf || size <= 0)
1501 int i, cnt, nalsize;
1502 const unsigned char *p = buf;
1507 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1508 return AVERROR_INVALIDDATA;
1510 /* sps and pps in the avcC always have length coded with 2 bytes,
1511 * so put a fake nal_length_size = 2 while parsing them */
1512 h->nal_length_size = 2;
1513 // Decode sps from avcC
1514 cnt = *(p + 5) & 0x1f; // Number of sps
1516 for (i = 0; i < cnt; i++) {
1517 nalsize = AV_RB16(p) + 2;
1518 if(nalsize > size - (p-buf))
1519 return AVERROR_INVALIDDATA;
1520 ret = decode_nal_units(h, p, nalsize, 1);
1522 av_log(avctx, AV_LOG_ERROR,
1523 "Decoding sps %d from avcC failed\n", i);
1528 // Decode pps from avcC
1529 cnt = *(p++); // Number of pps
1530 for (i = 0; i < cnt; i++) {
1531 nalsize = AV_RB16(p) + 2;
1532 if(nalsize > size - (p-buf))
1533 return AVERROR_INVALIDDATA;
1534 ret = decode_nal_units(h, p, nalsize, 1);
1536 av_log(avctx, AV_LOG_ERROR,
1537 "Decoding pps %d from avcC failed\n", i);
1542 // Now store right nal length size, that will be used to parse all other nals
1543 h->nal_length_size = (buf[4] & 0x03) + 1;
1546 ret = decode_nal_units(h, buf, size, 1);
1553 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1555 H264Context *h = avctx->priv_data;
1561 h->bit_depth_luma = 8;
1562 h->chroma_format_idc = 1;
1564 h->avctx->bits_per_raw_sample = 8;
1565 h->cur_chroma_format_idc = 1;
1567 ff_h264dsp_init(&h->h264dsp, 8, 1);
1568 av_assert0(h->sps.bit_depth_chroma == 0);
1569 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1570 ff_h264qpel_init(&h->h264qpel, 8);
1571 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1573 h->dequant_coeff_pps = -1;
1574 h->current_sps_id = -1;
1576 /* needed so that IDCT permutation is known early */
1577 if (CONFIG_ERROR_RESILIENCE)
1578 ff_dsputil_init(&h->dsp, h->avctx);
1579 ff_videodsp_init(&h->vdsp, 8);
1581 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1582 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1584 h->picture_structure = PICT_FRAME;
1585 h->slice_context_count = 1;
1586 h->workaround_bugs = avctx->workaround_bugs;
1587 h->flags = avctx->flags;
1590 // s->decode_mb = ff_h263_decode_mb;
1591 if (!avctx->has_b_frames)
1594 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1596 ff_h264_decode_init_vlc();
1598 ff_init_cabac_states();
1601 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1603 h->thread_context[0] = h;
1604 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1605 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1606 h->last_pocs[i] = INT_MIN;
1607 h->prev_poc_msb = 1 << 16;
1608 h->prev_frame_num = -1;
1610 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
1611 ff_h264_reset_sei(h);
1612 if (avctx->codec_id == AV_CODEC_ID_H264) {
1613 if (avctx->ticks_per_frame == 1) {
1614 if(h->avctx->time_base.den < INT_MAX/2) {
1615 h->avctx->time_base.den *= 2;
1617 h->avctx->time_base.num /= 2;
1619 avctx->ticks_per_frame = 2;
1622 if (avctx->extradata_size > 0 && avctx->extradata) {
1623 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
1625 ff_h264_free_context(h);
1630 if (h->sps.bitstream_restriction_flag &&
1631 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1632 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1636 avctx->internal->allocate_progress = 1;
1643 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1644 #undef REBASE_PICTURE
1645 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1646 ((pic && pic >= old_ctx->DPB && \
1647 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1648 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1650 static void copy_picture_range(Picture **to, Picture **from, int count,
1651 H264Context *new_base,
1652 H264Context *old_base)
1656 for (i = 0; i < count; i++) {
1657 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1658 IN_RANGE(from[i], old_base->DPB,
1659 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1661 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1665 static int copy_parameter_set(void **to, void **from, int count, int size)
1669 for (i = 0; i < count; i++) {
1670 if (to[i] && !from[i]) {
1672 } else if (from[i] && !to[i]) {
1673 to[i] = av_malloc(size);
1675 return AVERROR(ENOMEM);
1679 memcpy(to[i], from[i], size);
1685 static int decode_init_thread_copy(AVCodecContext *avctx)
1687 H264Context *h = avctx->priv_data;
1689 if (!avctx->internal->is_copy)
1691 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1692 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1694 h->rbsp_buffer[0] = NULL;
1695 h->rbsp_buffer[1] = NULL;
1696 h->rbsp_buffer_size[0] = 0;
1697 h->rbsp_buffer_size[1] = 0;
1698 h->context_initialized = 0;
1703 #define copy_fields(to, from, start_field, end_field) \
1704 memcpy(&to->start_field, &from->start_field, \
1705 (char *)&to->end_field - (char *)&to->start_field)
1707 static int h264_slice_header_init(H264Context *, int);
1709 static int h264_set_parameter_from_sps(H264Context *h);
1711 static int decode_update_thread_context(AVCodecContext *dst,
1712 const AVCodecContext *src)
1714 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1715 int inited = h->context_initialized, err = 0;
1716 int context_reinitialized = 0;
1723 (h->width != h1->width ||
1724 h->height != h1->height ||
1725 h->mb_width != h1->mb_width ||
1726 h->mb_height != h1->mb_height ||
1727 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1728 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1729 h->sps.colorspace != h1->sps.colorspace)) {
1731 /* set bits_per_raw_sample to the previous value. the check for changed
1732 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1733 * the current value */
1734 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1736 av_freep(&h->bipred_scratchpad);
1738 h->width = h1->width;
1739 h->height = h1->height;
1740 h->mb_height = h1->mb_height;
1741 h->mb_width = h1->mb_width;
1742 h->mb_num = h1->mb_num;
1743 h->mb_stride = h1->mb_stride;
1744 h->b_stride = h1->b_stride;
1746 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1747 (void **)h1->sps_buffers,
1748 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1751 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1752 (void **)h1->pps_buffers,
1753 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1757 if ((err = h264_slice_header_init(h, 1)) < 0) {
1758 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1761 context_reinitialized = 1;
1764 h264_set_parameter_from_sps(h);
1765 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1766 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1769 /* update linesize on resize for h264. The h264 decoder doesn't
1770 * necessarily call ff_MPV_frame_start in the new thread */
1771 h->linesize = h1->linesize;
1772 h->uvlinesize = h1->uvlinesize;
1774 /* copy block_offset since frame_start may not be called */
1775 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1778 for (i = 0; i < MAX_SPS_COUNT; i++)
1779 av_freep(h->sps_buffers + i);
1781 for (i = 0; i < MAX_PPS_COUNT; i++)
1782 av_freep(h->pps_buffers + i);
1784 av_freep(&h->rbsp_buffer[0]);
1785 av_freep(&h->rbsp_buffer[1]);
1786 memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1787 memcpy(&h->cabac, &h1->cabac,
1788 sizeof(H264Context) - offsetof(H264Context, cabac));
1789 av_assert0((void*)&h->cabac == &h->mb_padding + 1);
1791 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1792 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1794 memset(&h->er, 0, sizeof(h->er));
1795 memset(&h->me, 0, sizeof(h->me));
1796 memset(&h->mb, 0, sizeof(h->mb));
1797 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1798 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1802 h->qscale_table_pool = NULL;
1803 h->mb_type_pool = NULL;
1804 h->ref_index_pool = NULL;
1805 h->motion_val_pool = NULL;
1806 for (i = 0; i < 2; i++) {
1807 h->rbsp_buffer[i] = NULL;
1808 h->rbsp_buffer_size[i] = 0;
1811 if (h1->context_initialized) {
1812 h->context_initialized = 0;
1814 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1815 av_frame_unref(&h->cur_pic.f);
1816 h->cur_pic.tf.f = &h->cur_pic.f;
1818 ret = ff_h264_alloc_tables(h);
1820 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1823 ret = context_init(h);
1825 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1830 h->bipred_scratchpad = NULL;
1831 h->edge_emu_buffer = NULL;
1833 h->thread_context[0] = h;
1834 h->context_initialized = h1->context_initialized;
1837 h->avctx->coded_height = h1->avctx->coded_height;
1838 h->avctx->coded_width = h1->avctx->coded_width;
1839 h->avctx->width = h1->avctx->width;
1840 h->avctx->height = h1->avctx->height;
1841 h->coded_picture_number = h1->coded_picture_number;
1842 h->first_field = h1->first_field;
1843 h->picture_structure = h1->picture_structure;
1844 h->qscale = h1->qscale;
1845 h->droppable = h1->droppable;
1846 h->data_partitioning = h1->data_partitioning;
1847 h->low_delay = h1->low_delay;
1849 for (i = 0; h->DPB && i < MAX_PICTURE_COUNT; i++) {
1850 unref_picture(h, &h->DPB[i]);
1851 if (h1->DPB && h1->DPB[i].f.buf[0] &&
1852 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1856 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1857 unref_picture(h, &h->cur_pic);
1858 if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1861 h->workaround_bugs = h1->workaround_bugs;
1862 h->low_delay = h1->low_delay;
1863 h->droppable = h1->droppable;
1865 // extradata/NAL handling
1866 h->is_avc = h1->is_avc;
1869 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1870 (void **)h1->sps_buffers,
1871 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1874 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1875 (void **)h1->pps_buffers,
1876 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1880 // Dequantization matrices
1881 // FIXME these are big - can they be only copied when PPS changes?
1882 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1884 for (i = 0; i < 6; i++)
1885 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1886 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1888 for (i = 0; i < 6; i++)
1889 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1890 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1892 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1895 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1898 copy_fields(h, h1, short_ref, cabac_init_idc);
1900 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1901 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1902 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1903 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1905 h->frame_recovered = h1->frame_recovered;
1907 if (context_reinitialized)
1908 h264_set_parameter_from_sps(h);
1910 if (!h->cur_pic_ptr)
1913 if (!h->droppable) {
1914 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1915 h->prev_poc_msb = h->poc_msb;
1916 h->prev_poc_lsb = h->poc_lsb;
1918 h->prev_frame_num_offset = h->frame_num_offset;
1919 h->prev_frame_num = h->frame_num;
1920 h->outputed_poc = h->next_outputed_poc;
1922 h->recovery_frame = h1->recovery_frame;
1927 static int h264_frame_start(H264Context *h)
1931 const int pixel_shift = h->pixel_shift;
1933 1<<(h->sps.bit_depth_luma-1),
1934 1<<(h->sps.bit_depth_chroma-1),
1935 1<<(h->sps.bit_depth_chroma-1),
1939 if (!ff_thread_can_start_frame(h->avctx)) {
1940 av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1944 release_unused_pictures(h, 1);
1945 h->cur_pic_ptr = NULL;
1947 i = find_unused_picture(h);
1949 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1954 pic->reference = h->droppable ? 0 : h->picture_structure;
1955 pic->f.coded_picture_number = h->coded_picture_number++;
1956 pic->field_picture = h->picture_structure != PICT_FRAME;
1959 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1961 * See decode_nal_units().
1963 pic->f.key_frame = 0;
1964 pic->mmco_reset = 0;
1967 if ((ret = alloc_picture(h, pic)) < 0)
1969 if(!h->frame_recovered && !h->avctx->hwaccel &&
1970 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1971 avpriv_color_frame(&pic->f, c);
1973 h->cur_pic_ptr = pic;
1974 unref_picture(h, &h->cur_pic);
1975 if (CONFIG_ERROR_RESILIENCE) {
1976 h->er.cur_pic = NULL;
1979 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1982 if (CONFIG_ERROR_RESILIENCE) {
1983 ff_er_frame_start(&h->er);
1985 h->er.next_pic = NULL;
1988 assert(h->linesize && h->uvlinesize);
1990 for (i = 0; i < 16; i++) {
1991 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1992 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1994 for (i = 0; i < 16; i++) {
1995 h->block_offset[16 + i] =
1996 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1997 h->block_offset[48 + 16 + i] =
1998 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
2001 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
2002 // h->cur_pic.reference /* || h->contains_intra */ || 1;
2004 /* We mark the current picture as non-reference after allocating it, so
2005 * that if we break out due to an error it can be released automatically
2006 * in the next ff_MPV_frame_start().
2008 h->cur_pic_ptr->reference = 0;
2010 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
2012 h->next_output_pic = NULL;
2014 assert(h->cur_pic_ptr->long_ref == 0);
2020 * Run setup operations that must be run after slice header decoding.
2021 * This includes finding the next displayed frame.
2023 * @param h h264 master context
2024 * @param setup_finished enough NALs have been read that we can call
2025 * ff_thread_finish_setup()
2027 static void decode_postinit(H264Context *h, int setup_finished)
2029 Picture *out = h->cur_pic_ptr;
2030 Picture *cur = h->cur_pic_ptr;
2031 int i, pics, out_of_order, out_idx;
2033 h->cur_pic_ptr->f.pict_type = h->pict_type;
2035 if (h->next_output_pic)
2038 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
2039 /* FIXME: if we have two PAFF fields in one packet, we can't start
2040 * the next thread here. If we have one field per packet, we can.
2041 * The check in decode_nal_units() is not good enough to find this
2042 * yet, so we assume the worst for now. */
2043 // if (setup_finished)
2044 // ff_thread_finish_setup(h->avctx);
2048 cur->f.interlaced_frame = 0;
2049 cur->f.repeat_pict = 0;
2051 /* Signal interlacing information externally. */
2052 /* Prioritize picture timing SEI information over used
2053 * decoding process if it exists. */
2055 if (h->sps.pic_struct_present_flag) {
2056 switch (h->sei_pic_struct) {
2057 case SEI_PIC_STRUCT_FRAME:
2059 case SEI_PIC_STRUCT_TOP_FIELD:
2060 case SEI_PIC_STRUCT_BOTTOM_FIELD:
2061 cur->f.interlaced_frame = 1;
2063 case SEI_PIC_STRUCT_TOP_BOTTOM:
2064 case SEI_PIC_STRUCT_BOTTOM_TOP:
2065 if (FIELD_OR_MBAFF_PICTURE(h))
2066 cur->f.interlaced_frame = 1;
2068 // try to flag soft telecine progressive
2069 cur->f.interlaced_frame = h->prev_interlaced_frame;
2071 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
2072 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
2073 /* Signal the possibility of telecined film externally
2074 * (pic_struct 5,6). From these hints, let the applications
2075 * decide if they apply deinterlacing. */
2076 cur->f.repeat_pict = 1;
2078 case SEI_PIC_STRUCT_FRAME_DOUBLING:
2079 cur->f.repeat_pict = 2;
2081 case SEI_PIC_STRUCT_FRAME_TRIPLING:
2082 cur->f.repeat_pict = 4;
2086 if ((h->sei_ct_type & 3) &&
2087 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2088 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2090 /* Derive interlacing flag from used decoding process. */
2091 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2093 h->prev_interlaced_frame = cur->f.interlaced_frame;
2095 if (cur->field_poc[0] != cur->field_poc[1]) {
2096 /* Derive top_field_first from field pocs. */
2097 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2099 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2100 /* Use picture timing SEI information. Even if it is a
2101 * information of a past frame, better than nothing. */
2102 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2103 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2104 cur->f.top_field_first = 1;
2106 cur->f.top_field_first = 0;
2108 /* Most likely progressive */
2109 cur->f.top_field_first = 0;
2113 if (h->sei_frame_packing_present &&
2114 h->frame_packing_arrangement_type >= 0 &&
2115 h->frame_packing_arrangement_type <= 6 &&
2116 h->content_interpretation_type > 0 &&
2117 h->content_interpretation_type < 3) {
2118 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
2122 switch (h->frame_packing_arrangement_type) {
2124 stereo->type = AV_STEREO3D_CHECKERBOARD;
2127 stereo->type = AV_STEREO3D_LINES;
2130 stereo->type = AV_STEREO3D_COLUMNS;
2133 if (h->quincunx_subsampling)
2134 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2136 stereo->type = AV_STEREO3D_SIDEBYSIDE;
2139 stereo->type = AV_STEREO3D_TOPBOTTOM;
2142 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
2145 stereo->type = AV_STEREO3D_2D;
2149 if (h->content_interpretation_type == 2)
2150 stereo->flags = AV_STEREO3D_FLAG_INVERT;
2153 cur->mmco_reset = h->mmco_reset;
2156 // FIXME do something with unavailable reference frames
2158 /* Sort B-frames into display order */
2160 if (h->sps.bitstream_restriction_flag &&
2161 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2162 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2166 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2167 !h->sps.bitstream_restriction_flag) {
2168 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2172 for (i = 0; 1; i++) {
2173 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2175 h->last_pocs[i-1] = cur->poc;
2178 h->last_pocs[i-1]= h->last_pocs[i];
2181 out_of_order = MAX_DELAYED_PIC_COUNT - i;
2182 if( cur->f.pict_type == AV_PICTURE_TYPE_B
2183 || (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))
2184 out_of_order = FFMAX(out_of_order, 1);
2185 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2186 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2187 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2188 h->last_pocs[i] = INT_MIN;
2189 h->last_pocs[0] = cur->poc;
2190 cur->mmco_reset = 1;
2191 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2192 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2193 h->avctx->has_b_frames = out_of_order;
2198 while (h->delayed_pic[pics])
2201 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
2203 h->delayed_pic[pics++] = cur;
2204 if (cur->reference == 0)
2205 cur->reference = DELAYED_PIC_REF;
2207 out = h->delayed_pic[0];
2209 for (i = 1; h->delayed_pic[i] &&
2210 !h->delayed_pic[i]->f.key_frame &&
2211 !h->delayed_pic[i]->mmco_reset;
2213 if (h->delayed_pic[i]->poc < out->poc) {
2214 out = h->delayed_pic[i];
2217 if (h->avctx->has_b_frames == 0 &&
2218 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2219 h->next_outputed_poc = INT_MIN;
2220 out_of_order = out->poc < h->next_outputed_poc;
2222 if (out_of_order || pics > h->avctx->has_b_frames) {
2223 out->reference &= ~DELAYED_PIC_REF;
2224 // for frame threading, the owner must be the second field's thread or
2225 // else the first thread can release the picture and reuse it unsafely
2226 for (i = out_idx; h->delayed_pic[i]; i++)
2227 h->delayed_pic[i] = h->delayed_pic[i + 1];
2229 if (!out_of_order && pics > h->avctx->has_b_frames) {
2230 h->next_output_pic = out;
2231 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2232 h->next_outputed_poc = INT_MIN;
2234 h->next_outputed_poc = out->poc;
2236 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2239 if (h->next_output_pic) {
2240 if (h->next_output_pic->recovered) {
2241 // We have reached an recovery point and all frames after it in
2242 // display order are "recovered".
2243 h->frame_recovered |= FRAME_RECOVERED_SEI;
2245 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2248 if (setup_finished && !h->avctx->hwaccel)
2249 ff_thread_finish_setup(h->avctx);
2252 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2253 uint8_t *src_cb, uint8_t *src_cr,
2254 int linesize, int uvlinesize,
2257 uint8_t *top_border;
2259 const int pixel_shift = h->pixel_shift;
2260 int chroma444 = CHROMA444(h);
2261 int chroma422 = CHROMA422(h);
2264 src_cb -= uvlinesize;
2265 src_cr -= uvlinesize;
2267 if (!simple && FRAME_MBAFF(h)) {
2270 top_border = h->top_borders[0][h->mb_x];
2271 AV_COPY128(top_border, src_y + 15 * linesize);
2273 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2274 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2277 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2278 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2279 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2280 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2282 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2283 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2285 } else if (chroma422) {
2287 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2288 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2290 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2291 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2295 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2296 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2298 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2299 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2304 } else if (MB_MBAFF(h)) {
2310 top_border = h->top_borders[top_idx][h->mb_x];
2311 /* There are two lines saved, the line above the top macroblock
2312 * of a pair, and the line above the bottom macroblock. */
2313 AV_COPY128(top_border, src_y + 16 * linesize);
2315 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2317 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2320 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2321 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2322 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2323 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2325 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2326 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2328 } else if (chroma422) {
2330 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2331 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2333 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2334 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2338 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2339 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2341 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2342 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2348 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2349 uint8_t *src_cb, uint8_t *src_cr,
2350 int linesize, int uvlinesize,
2351 int xchg, int chroma444,
2352 int simple, int pixel_shift)
2354 int deblock_topleft;
2357 uint8_t *top_border_m1;
2358 uint8_t *top_border;
2360 if (!simple && FRAME_MBAFF(h)) {
2365 top_idx = MB_MBAFF(h) ? 0 : 1;
2369 if (h->deblocking_filter == 2) {
2370 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2371 deblock_top = h->top_type;
2373 deblock_topleft = (h->mb_x > 0);
2374 deblock_top = (h->mb_y > !!MB_FIELD(h));
2377 src_y -= linesize + 1 + pixel_shift;
2378 src_cb -= uvlinesize + 1 + pixel_shift;
2379 src_cr -= uvlinesize + 1 + pixel_shift;
2381 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2382 top_border = h->top_borders[top_idx][h->mb_x];
2384 #define XCHG(a, b, xchg) \
2385 if (pixel_shift) { \
2387 AV_SWAP64(b + 0, a + 0); \
2388 AV_SWAP64(b + 8, a + 8); \
2398 if (deblock_topleft) {
2399 XCHG(top_border_m1 + (8 << pixel_shift),
2400 src_y - (7 << pixel_shift), 1);
2402 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2403 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2404 if (h->mb_x + 1 < h->mb_width) {
2405 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2406 src_y + (17 << pixel_shift), 1);
2408 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2410 if (deblock_topleft) {
2411 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2412 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2414 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2415 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2416 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2417 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2418 if (h->mb_x + 1 < h->mb_width) {
2419 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2420 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2423 if (deblock_topleft) {
2424 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2425 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2427 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2428 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2434 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2437 if (high_bit_depth) {
2438 return AV_RN32A(((int32_t *)mb) + index);
2440 return AV_RN16A(mb + index);
2443 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2444 int index, int value)
2446 if (high_bit_depth) {
2447 AV_WN32A(((int32_t *)mb) + index, value);
2449 AV_WN16A(mb + index, value);
2452 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2453 int mb_type, int is_h264,
2455 int transform_bypass,
2459 uint8_t *dest_y, int p)
2461 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2462 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2464 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2465 block_offset += 16 * p;
2466 if (IS_INTRA4x4(mb_type)) {
2467 if (IS_8x8DCT(mb_type)) {
2468 if (transform_bypass) {
2470 idct_add = h->h264dsp.h264_add_pixels8_clear;
2472 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2473 idct_add = h->h264dsp.h264_idct8_add;
2475 for (i = 0; i < 16; i += 4) {
2476 uint8_t *const ptr = dest_y + block_offset[i];
2477 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2478 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2479 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2481 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2482 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2483 (h->topright_samples_available << i) & 0x4000, linesize);
2485 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2486 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2488 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2493 if (transform_bypass) {
2495 idct_add = h->h264dsp.h264_add_pixels4_clear;
2497 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2498 idct_add = h->h264dsp.h264_idct_add;
2500 for (i = 0; i < 16; i++) {
2501 uint8_t *const ptr = dest_y + block_offset[i];
2502 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2504 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2505 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2510 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2511 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2512 av_assert2(h->mb_y || linesize <= block_offset[i]);
2513 if (!topright_avail) {
2515 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2516 topright = (uint8_t *)&tr_high;
2518 tr = ptr[3 - linesize] * 0x01010101u;
2519 topright = (uint8_t *)&tr;
2522 topright = ptr + (4 << pixel_shift) - linesize;
2526 h->hpc.pred4x4[dir](ptr, topright, linesize);
2527 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2530 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2531 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2533 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2534 } else if (CONFIG_SVQ3_DECODER)
2535 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2541 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2543 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2544 if (!transform_bypass)
2545 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2547 h->dequant4_coeff[p][qscale][0]);
2549 static const uint8_t dc_mapping[16] = {
2550 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2551 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2552 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2553 10 * 16, 11 * 16, 14 * 16, 15 * 16
2555 for (i = 0; i < 16; i++)
2556 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2557 pixel_shift, dc_mapping[i],
2558 dctcoef_get(h->mb_luma_dc[p],
2562 } else if (CONFIG_SVQ3_DECODER)
2563 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2564 h->mb_luma_dc[p], qscale);
2568 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2569 int is_h264, int simple,
2570 int transform_bypass,
2574 uint8_t *dest_y, int p)
2576 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2578 block_offset += 16 * p;
2579 if (!IS_INTRA4x4(mb_type)) {
2581 if (IS_INTRA16x16(mb_type)) {
2582 if (transform_bypass) {
2583 if (h->sps.profile_idc == 244 &&
2584 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2585 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2586 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2587 h->mb + (p * 256 << pixel_shift),
2590 for (i = 0; i < 16; i++)
2591 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2592 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2593 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2594 h->mb + (i * 16 + p * 256 << pixel_shift),
2598 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2599 h->mb + (p * 256 << pixel_shift),
2601 h->non_zero_count_cache + p * 5 * 8);
2603 } else if (h->cbp & 15) {
2604 if (transform_bypass) {
2605 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2606 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2607 : h->h264dsp.h264_add_pixels4_clear;
2608 for (i = 0; i < 16; i += di)
2609 if (h->non_zero_count_cache[scan8[i + p * 16]])
2610 idct_add(dest_y + block_offset[i],
2611 h->mb + (i * 16 + p * 256 << pixel_shift),
2614 if (IS_8x8DCT(mb_type))
2615 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2616 h->mb + (p * 256 << pixel_shift),
2618 h->non_zero_count_cache + p * 5 * 8);
2620 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2621 h->mb + (p * 256 << pixel_shift),
2623 h->non_zero_count_cache + p * 5 * 8);
2626 } else if (CONFIG_SVQ3_DECODER) {
2627 for (i = 0; i < 16; i++)
2628 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2629 // FIXME benchmark weird rule, & below
2630 uint8_t *const ptr = dest_y + block_offset[i];
2631 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2632 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2640 #include "h264_mb_template.c"
2644 #include "h264_mb_template.c"
2648 #include "h264_mb_template.c"
2650 void ff_h264_hl_decode_mb(H264Context *h)
2652 const int mb_xy = h->mb_xy;
2653 const int mb_type = h->cur_pic.mb_type[mb_xy];
2654 int is_complex = CONFIG_SMALL || h->is_complex ||
2655 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2658 if (is_complex || h->pixel_shift)
2659 hl_decode_mb_444_complex(h);
2661 hl_decode_mb_444_simple_8(h);
2662 } else if (is_complex) {
2663 hl_decode_mb_complex(h);
2664 } else if (h->pixel_shift) {
2665 hl_decode_mb_simple_16(h);
2667 hl_decode_mb_simple_8(h);
2670 int ff_pred_weight_table(H264Context *h)
2673 int luma_def, chroma_def;
2676 h->use_weight_chroma = 0;
2677 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2678 if (h->sps.chroma_format_idc)
2679 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2680 luma_def = 1 << h->luma_log2_weight_denom;
2681 chroma_def = 1 << h->chroma_log2_weight_denom;
2683 for (list = 0; list < 2; list++) {
2684 h->luma_weight_flag[list] = 0;
2685 h->chroma_weight_flag[list] = 0;
2686 for (i = 0; i < h->ref_count[list]; i++) {
2687 int luma_weight_flag, chroma_weight_flag;
2689 luma_weight_flag = get_bits1(&h->gb);
2690 if (luma_weight_flag) {
2691 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2692 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2693 if (h->luma_weight[i][list][0] != luma_def ||
2694 h->luma_weight[i][list][1] != 0) {
2696 h->luma_weight_flag[list] = 1;
2699 h->luma_weight[i][list][0] = luma_def;
2700 h->luma_weight[i][list][1] = 0;
2703 if (h->sps.chroma_format_idc) {
2704 chroma_weight_flag = get_bits1(&h->gb);
2705 if (chroma_weight_flag) {
2707 for (j = 0; j < 2; j++) {
2708 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2709 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2710 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2711 h->chroma_weight[i][list][j][1] != 0) {
2712 h->use_weight_chroma = 1;
2713 h->chroma_weight_flag[list] = 1;
2718 for (j = 0; j < 2; j++) {
2719 h->chroma_weight[i][list][j][0] = chroma_def;
2720 h->chroma_weight[i][list][j][1] = 0;
2725 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2728 h->use_weight = h->use_weight || h->use_weight_chroma;
2733 * Initialize implicit_weight table.
2734 * @param field 0/1 initialize the weight for interlaced MBAFF
2735 * -1 initializes the rest
2737 static void implicit_weight_table(H264Context *h, int field)
2739 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2741 for (i = 0; i < 2; i++) {
2742 h->luma_weight_flag[i] = 0;
2743 h->chroma_weight_flag[i] = 0;
2747 if (h->picture_structure == PICT_FRAME) {
2748 cur_poc = h->cur_pic_ptr->poc;
2750 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2752 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2753 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2755 h->use_weight_chroma = 0;
2759 ref_count0 = h->ref_count[0];
2760 ref_count1 = h->ref_count[1];
2762 cur_poc = h->cur_pic_ptr->field_poc[field];
2764 ref_count0 = 16 + 2 * h->ref_count[0];
2765 ref_count1 = 16 + 2 * h->ref_count[1];
2769 h->use_weight_chroma = 2;
2770 h->luma_log2_weight_denom = 5;
2771 h->chroma_log2_weight_denom = 5;
2773 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2774 int poc0 = h->ref_list[0][ref0].poc;
2775 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2777 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2778 int poc1 = h->ref_list[1][ref1].poc;
2779 int td = av_clip(poc1 - poc0, -128, 127);
2781 int tb = av_clip(cur_poc - poc0, -128, 127);
2782 int tx = (16384 + (FFABS(td) >> 1)) / td;
2783 int dist_scale_factor = (tb * tx + 32) >> 8;
2784 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2785 w = 64 - dist_scale_factor;
2789 h->implicit_weight[ref0][ref1][0] =
2790 h->implicit_weight[ref0][ref1][1] = w;
2792 h->implicit_weight[ref0][ref1][field] = w;
2799 * instantaneous decoder refresh.
2801 static void idr(H264Context *h)
2804 ff_h264_remove_all_refs(h);
2805 h->prev_frame_num = 0;
2806 h->prev_frame_num_offset = 0;
2807 h->prev_poc_msb = 1<<16;
2808 h->prev_poc_lsb = 0;
2809 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2810 h->last_pocs[i] = INT_MIN;
2813 /* forget old pics after a seek */
2814 static void flush_change(H264Context *h)
2818 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2819 h->prev_interlaced_frame = 1;
2822 h->prev_frame_num = -1;
2823 if (h->cur_pic_ptr) {
2824 h->cur_pic_ptr->reference = 0;
2825 for (j=i=0; h->delayed_pic[i]; i++)
2826 if (h->delayed_pic[i] != h->cur_pic_ptr)
2827 h->delayed_pic[j++] = h->delayed_pic[i];
2828 h->delayed_pic[j] = NULL;
2831 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2832 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2833 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2834 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2835 ff_h264_reset_sei(h);
2836 h->recovery_frame = -1;
2837 h->frame_recovered = 0;
2839 h->current_slice = 0;
2843 /* forget old pics after a seek */
2844 static void flush_dpb(AVCodecContext *avctx)
2846 H264Context *h = avctx->priv_data;
2849 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2850 if (h->delayed_pic[i])
2851 h->delayed_pic[i]->reference = 0;
2852 h->delayed_pic[i] = NULL;
2858 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2859 unref_picture(h, &h->DPB[i]);
2860 h->cur_pic_ptr = NULL;
2861 unref_picture(h, &h->cur_pic);
2863 h->mb_x = h->mb_y = 0;
2865 h->parse_context.state = -1;
2866 h->parse_context.frame_start_found = 0;
2867 h->parse_context.overread = 0;
2868 h->parse_context.overread_index = 0;
2869 h->parse_context.index = 0;
2870 h->parse_context.last_index = 0;
2873 h->context_initialized = 0;
2876 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2878 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2881 h->frame_num_offset = h->prev_frame_num_offset;
2882 if (h->frame_num < h->prev_frame_num)
2883 h->frame_num_offset += max_frame_num;
2885 if (h->sps.poc_type == 0) {
2886 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2888 if (h->poc_lsb < h->prev_poc_lsb &&
2889 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2890 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2891 else if (h->poc_lsb > h->prev_poc_lsb &&
2892 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2893 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2895 h->poc_msb = h->prev_poc_msb;
2897 field_poc[1] = h->poc_msb + h->poc_lsb;
2898 if (h->picture_structure == PICT_FRAME)
2899 field_poc[1] += h->delta_poc_bottom;
2900 } else if (h->sps.poc_type == 1) {
2901 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2904 if (h->sps.poc_cycle_length != 0)
2905 abs_frame_num = h->frame_num_offset + h->frame_num;
2909 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2912 expected_delta_per_poc_cycle = 0;
2913 for (i = 0; i < h->sps.poc_cycle_length; i++)
2914 // FIXME integrate during sps parse
2915 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2917 if (abs_frame_num > 0) {
2918 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2919 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2921 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2922 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2923 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2927 if (h->nal_ref_idc == 0)
2928 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2930 field_poc[0] = expectedpoc + h->delta_poc[0];
2931 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2933 if (h->picture_structure == PICT_FRAME)
2934 field_poc[1] += h->delta_poc[1];
2936 int poc = 2 * (h->frame_num_offset + h->frame_num);
2938 if (!h->nal_ref_idc)
2945 if (h->picture_structure != PICT_BOTTOM_FIELD)
2946 pic_field_poc[0] = field_poc[0];
2947 if (h->picture_structure != PICT_TOP_FIELD)
2948 pic_field_poc[1] = field_poc[1];
2949 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2955 * initialize scan tables
2957 static void init_scan_tables(H264Context *h)
2960 for (i = 0; i < 16; i++) {
2961 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2962 h->zigzag_scan[i] = T(zigzag_scan[i]);
2963 h->field_scan[i] = T(field_scan[i]);
2966 for (i = 0; i < 64; i++) {
2967 #define T(x) (x >> 3) | ((x & 7) << 3)
2968 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2969 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2970 h->field_scan8x8[i] = T(field_scan8x8[i]);
2971 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2974 if (h->sps.transform_bypass) { // FIXME same ugly
2975 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2976 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2977 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2978 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2979 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2980 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2982 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2983 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2984 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2985 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2986 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2987 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2991 static int field_end(H264Context *h, int in_setup)
2993 AVCodecContext *const avctx = h->avctx;
2997 if (CONFIG_H264_VDPAU_DECODER &&
2998 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2999 ff_vdpau_h264_set_reference_frames(h);
3001 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
3002 if (!h->droppable) {
3003 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3004 h->prev_poc_msb = h->poc_msb;
3005 h->prev_poc_lsb = h->poc_lsb;
3007 h->prev_frame_num_offset = h->frame_num_offset;
3008 h->prev_frame_num = h->frame_num;
3009 h->outputed_poc = h->next_outputed_poc;
3012 if (avctx->hwaccel) {
3013 if (avctx->hwaccel->end_frame(avctx) < 0)
3014 av_log(avctx, AV_LOG_ERROR,
3015 "hardware accelerator failed to decode picture\n");
3018 if (CONFIG_H264_VDPAU_DECODER &&
3019 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3020 ff_vdpau_h264_picture_complete(h);
3023 * FIXME: Error handling code does not seem to support interlaced
3024 * when slices span multiple rows
3025 * The ff_er_add_slice calls don't work right for bottom
3026 * fields; they cause massive erroneous error concealing
3027 * Error marking covers both fields (top and bottom).
3028 * This causes a mismatched s->error_count
3029 * and a bad error table. Further, the error count goes to
3030 * INT_MAX when called for bottom field, because mb_y is
3031 * past end by one (callers fault) and resync_mb_y != 0
3032 * causes problems for the first MB line, too.
3034 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
3035 h->er.cur_pic = h->cur_pic_ptr;
3036 ff_er_frame_end(&h->er);
3038 if (!in_setup && !h->droppable)
3039 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3040 h->picture_structure == PICT_BOTTOM_FIELD);
3043 h->current_slice = 0;
3049 * Replicate H264 "master" context to thread contexts.
3051 static int clone_slice(H264Context *dst, H264Context *src)
3053 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
3054 dst->cur_pic_ptr = src->cur_pic_ptr;
3055 dst->cur_pic = src->cur_pic;
3056 dst->linesize = src->linesize;
3057 dst->uvlinesize = src->uvlinesize;
3058 dst->first_field = src->first_field;
3060 dst->prev_poc_msb = src->prev_poc_msb;
3061 dst->prev_poc_lsb = src->prev_poc_lsb;
3062 dst->prev_frame_num_offset = src->prev_frame_num_offset;
3063 dst->prev_frame_num = src->prev_frame_num;
3064 dst->short_ref_count = src->short_ref_count;
3066 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
3067 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
3068 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3070 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
3071 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
3077 * Compute profile from profile_idc and constraint_set?_flags.
3081 * @return profile as defined by FF_PROFILE_H264_*
3083 int ff_h264_get_profile(SPS *sps)
3085 int profile = sps->profile_idc;
3087 switch (sps->profile_idc) {
3088 case FF_PROFILE_H264_BASELINE:
3089 // constraint_set1_flag set to 1
3090 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3092 case FF_PROFILE_H264_HIGH_10:
3093 case FF_PROFILE_H264_HIGH_422:
3094 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3095 // constraint_set3_flag set to 1
3096 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3103 static int h264_set_parameter_from_sps(H264Context *h)
3105 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3106 (h->sps.bitstream_restriction_flag &&
3107 !h->sps.num_reorder_frames)) {
3108 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3109 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3110 "Reenabling low delay requires a codec flush.\n");
3115 if (h->avctx->has_b_frames < 2)
3116 h->avctx->has_b_frames = !h->low_delay;
3118 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
3119 avpriv_request_sample(h->avctx,
3120 "Different chroma and luma bit depth");
3121 return AVERROR_PATCHWELCOME;
3124 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3125 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
3126 if (h->avctx->codec &&
3127 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
3128 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
3129 av_log(h->avctx, AV_LOG_ERROR,
3130 "VDPAU decoding does not support video colorspace.\n");
3131 return AVERROR_INVALIDDATA;
3133 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
3134 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
3135 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3136 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
3137 h->pixel_shift = h->sps.bit_depth_luma > 8;
3139 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3140 h->sps.chroma_format_idc);
3141 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3142 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3143 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3144 h->sps.chroma_format_idc);
3146 if (CONFIG_ERROR_RESILIENCE)
3147 ff_dsputil_init(&h->dsp, h->avctx);
3148 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3150 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3151 h->sps.bit_depth_luma);
3152 return AVERROR_INVALIDDATA;
3158 static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3160 switch (h->sps.bit_depth_luma) {
3163 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3164 return AV_PIX_FMT_GBRP9;
3166 return AV_PIX_FMT_YUV444P9;
3167 } else if (CHROMA422(h))
3168 return AV_PIX_FMT_YUV422P9;
3170 return AV_PIX_FMT_YUV420P9;
3174 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3175 return AV_PIX_FMT_GBRP10;
3177 return AV_PIX_FMT_YUV444P10;
3178 } else if (CHROMA422(h))
3179 return AV_PIX_FMT_YUV422P10;
3181 return AV_PIX_FMT_YUV420P10;
3185 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3186 return AV_PIX_FMT_GBRP12;
3188 return AV_PIX_FMT_YUV444P12;
3189 } else if (CHROMA422(h))
3190 return AV_PIX_FMT_YUV422P12;
3192 return AV_PIX_FMT_YUV420P12;
3196 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3197 return AV_PIX_FMT_GBRP14;
3199 return AV_PIX_FMT_YUV444P14;
3200 } else if (CHROMA422(h))
3201 return AV_PIX_FMT_YUV422P14;
3203 return AV_PIX_FMT_YUV420P14;
3207 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3208 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
3209 return AV_PIX_FMT_GBR24P;
3210 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
3211 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
3213 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3214 : AV_PIX_FMT_YUV444P;
3215 } else if (CHROMA422(h)) {
3216 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3217 : AV_PIX_FMT_YUV422P;
3220 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
3221 h->avctx->codec->pix_fmts :
3222 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3223 h264_hwaccel_pixfmt_list_jpeg_420 :
3224 h264_hwaccel_pixfmt_list_420;
3226 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
3227 if (fmt[i] == h->avctx->pix_fmt && !force_callback)
3229 return ff_thread_get_format(h->avctx, fmt);
3233 av_log(h->avctx, AV_LOG_ERROR,
3234 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3235 return AVERROR_INVALIDDATA;
3239 /* export coded and cropped frame dimensions to AVCodecContext */
3240 static int init_dimensions(H264Context *h)
3242 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3243 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3244 av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
3245 av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
3247 /* handle container cropping */
3249 FFALIGN(h->avctx->width, 16) == h->width &&
3250 FFALIGN(h->avctx->height, 16) == h->height) {
3251 width = h->avctx->width;
3252 height = h->avctx->height;
3255 if (width <= 0 || height <= 0) {
3256 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3258 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3259 return AVERROR_INVALIDDATA;
3261 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3262 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3269 h->avctx->coded_width = h->width;
3270 h->avctx->coded_height = h->height;
3271 h->avctx->width = width;
3272 h->avctx->height = height;
3277 static int h264_slice_header_init(H264Context *h, int reinit)
3279 int nb_slices = (HAVE_THREADS &&
3280 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3281 h->avctx->thread_count : 1;
3284 h->avctx->sample_aspect_ratio = h->sps.sar;
3285 av_assert0(h->avctx->sample_aspect_ratio.den);
3286 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3287 &h->chroma_x_shift, &h->chroma_y_shift);
3289 if (h->sps.timing_info_present_flag) {
3290 int64_t den = h->sps.time_scale;
3291 if (h->x264_build < 44U)
3293 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3294 h->sps.num_units_in_tick, den, 1 << 30);
3297 h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3302 h->prev_interlaced_frame = 1;
3304 init_scan_tables(h);
3305 ret = ff_h264_alloc_tables(h);
3307 av_log(h->avctx, AV_LOG_ERROR,
3308 "Could not allocate memory for h264\n");
3312 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3315 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3317 max_slices = MAX_THREADS;
3318 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3319 " reducing to %d\n", nb_slices, max_slices);
3320 nb_slices = max_slices;
3322 h->slice_context_count = nb_slices;
3324 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3325 ret = context_init(h);
3327 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3331 for (i = 1; i < h->slice_context_count; i++) {
3333 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3335 return AVERROR(ENOMEM);
3336 c->avctx = h->avctx;
3337 if (CONFIG_ERROR_RESILIENCE) {
3341 c->h264dsp = h->h264dsp;
3342 c->h264qpel = h->h264qpel;
3343 c->h264chroma = h->h264chroma;
3346 c->pixel_shift = h->pixel_shift;
3347 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3348 c->width = h->width;
3349 c->height = h->height;
3350 c->linesize = h->linesize;
3351 c->uvlinesize = h->uvlinesize;
3352 c->chroma_x_shift = h->chroma_x_shift;
3353 c->chroma_y_shift = h->chroma_y_shift;
3354 c->qscale = h->qscale;
3355 c->droppable = h->droppable;
3356 c->data_partitioning = h->data_partitioning;
3357 c->low_delay = h->low_delay;
3358 c->mb_width = h->mb_width;
3359 c->mb_height = h->mb_height;
3360 c->mb_stride = h->mb_stride;
3361 c->mb_num = h->mb_num;
3362 c->flags = h->flags;
3363 c->workaround_bugs = h->workaround_bugs;
3364 c->pict_type = h->pict_type;
3366 init_scan_tables(c);
3367 clone_tables(c, h, i);
3368 c->context_initialized = 1;
3371 for (i = 0; i < h->slice_context_count; i++)
3372 if ((ret = context_init(h->thread_context[i])) < 0) {
3373 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3378 h->context_initialized = 1;
3383 int ff_set_ref_count(H264Context *h)
3385 int num_ref_idx_active_override_flag;
3387 // set defaults, might be overridden a few lines later
3388 h->ref_count[0] = h->pps.ref_count[0];
3389 h->ref_count[1] = h->pps.ref_count[1];
3391 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3393 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3395 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3396 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3397 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3399 if (num_ref_idx_active_override_flag) {
3400 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3401 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3402 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3404 // full range is spec-ok in this case, even for frames
3405 h->ref_count[1] = 1;
3408 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3409 av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
3410 h->ref_count[0] = h->ref_count[1] = 0;
3411 return AVERROR_INVALIDDATA;
3414 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3420 h->ref_count[0] = h->ref_count[1] = 0;
3427 * Decode a slice header.
3428 * This will also call ff_MPV_common_init() and frame_start() as needed.
3430 * @param h h264context
3431 * @param h0 h264 master context (differs from 'h' when doing sliced based
3432 * parallel decoding)
3434 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3436 static int decode_slice_header(H264Context *h, H264Context *h0)
3438 unsigned int first_mb_in_slice;
3439 unsigned int pps_id;
3441 unsigned int slice_type, tmp, i, j;
3442 int last_pic_structure, last_pic_droppable;
3444 int needs_reinit = 0;
3445 int field_pic_flag, bottom_field_flag;
3447 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3448 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3450 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3452 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3453 if (h0->current_slice && FIELD_PICTURE(h)) {
3457 h0->current_slice = 0;
3458 if (!h0->first_field) {
3459 if (h->cur_pic_ptr && !h->droppable) {
3460 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3461 h->picture_structure == PICT_BOTTOM_FIELD);
3463 h->cur_pic_ptr = NULL;
3467 slice_type = get_ue_golomb_31(&h->gb);
3468 if (slice_type > 9) {
3469 av_log(h->avctx, AV_LOG_ERROR,
3470 "slice type too large (%d) at %d %d\n",
3471 slice_type, h->mb_x, h->mb_y);
3472 return AVERROR_INVALIDDATA;
3474 if (slice_type > 4) {
3476 h->slice_type_fixed = 1;
3478 h->slice_type_fixed = 0;
3480 slice_type = golomb_to_pict_type[slice_type];
3481 h->slice_type = slice_type;
3482 h->slice_type_nos = slice_type & 3;
3484 // to make a few old functions happy, it's wrong though
3485 h->pict_type = h->slice_type;
3487 pps_id = get_ue_golomb(&h->gb);
3488 if (pps_id >= MAX_PPS_COUNT) {
3489 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3490 return AVERROR_INVALIDDATA;
3492 if (!h0->pps_buffers[pps_id]) {
3493 av_log(h->avctx, AV_LOG_ERROR,
3494 "non-existing PPS %u referenced\n",
3496 return AVERROR_INVALIDDATA;
3498 h->pps = *h0->pps_buffers[pps_id];
3500 if (!h0->sps_buffers[h->pps.sps_id]) {
3501 av_log(h->avctx, AV_LOG_ERROR,
3502 "non-existing SPS %u referenced\n",
3504 return AVERROR_INVALIDDATA;
3507 if (h->pps.sps_id != h->current_sps_id ||
3508 h0->sps_buffers[h->pps.sps_id]->new) {
3509 h0->sps_buffers[h->pps.sps_id]->new = 0;
3511 h->current_sps_id = h->pps.sps_id;
3512 h->sps = *h0->sps_buffers[h->pps.sps_id];
3514 if (h->mb_width != h->sps.mb_width ||
3515 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3516 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3517 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3521 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3522 h->chroma_format_idc != h->sps.chroma_format_idc) {
3523 h->bit_depth_luma = h->sps.bit_depth_luma;
3524 h->chroma_format_idc = h->sps.chroma_format_idc;
3527 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3531 h->avctx->profile = ff_h264_get_profile(&h->sps);
3532 h->avctx->level = h->sps.level_idc;
3533 h->avctx->refs = h->sps.ref_frame_count;
3535 must_reinit = (h->context_initialized &&
3536 ( 16*h->sps.mb_width != h->avctx->coded_width
3537 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3538 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3539 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3540 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
3541 || h->mb_width != h->sps.mb_width
3542 || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
3544 if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3547 h->mb_width = h->sps.mb_width;
3548 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3549 h->mb_num = h->mb_width * h->mb_height;
3550 h->mb_stride = h->mb_width + 1;
3552 h->b_stride = h->mb_width * 4;
3554 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3556 h->width = 16 * h->mb_width;
3557 h->height = 16 * h->mb_height;
3559 ret = init_dimensions(h);
3563 if (h->sps.video_signal_type_present_flag) {
3564 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3566 if (h->sps.colour_description_present_flag) {
3567 if (h->avctx->colorspace != h->sps.colorspace)
3569 h->avctx->color_primaries = h->sps.color_primaries;
3570 h->avctx->color_trc = h->sps.color_trc;
3571 h->avctx->colorspace = h->sps.colorspace;
3575 if (h->context_initialized &&
3576 (h->width != h->avctx->coded_width ||
3577 h->height != h->avctx->coded_height ||
3581 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3582 "slice %d\n", h0->current_slice + 1);
3583 return AVERROR_INVALIDDATA;
3588 if ((ret = get_pixel_format(h, 1)) < 0)
3590 h->avctx->pix_fmt = ret;
3592 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3593 "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
3595 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3596 av_log(h->avctx, AV_LOG_ERROR,
3597 "h264_slice_header_init() failed\n");
3601 if (!h->context_initialized) {
3603 av_log(h->avctx, AV_LOG_ERROR,
3604 "Cannot (re-)initialize context during parallel decoding.\n");
3605 return AVERROR_PATCHWELCOME;
3608 if ((ret = get_pixel_format(h, 1)) < 0)
3610 h->avctx->pix_fmt = ret;
3612 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3613 av_log(h->avctx, AV_LOG_ERROR,
3614 "h264_slice_header_init() failed\n");
3619 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3620 h->dequant_coeff_pps = pps_id;
3621 init_dequant_tables(h);
3624 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3627 h->mb_aff_frame = 0;
3628 last_pic_structure = h0->picture_structure;
3629 last_pic_droppable = h0->droppable;
3630 h->droppable = h->nal_ref_idc == 0;
3631 if (h->sps.frame_mbs_only_flag) {
3632 h->picture_structure = PICT_FRAME;
3634 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3635 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3638 field_pic_flag = get_bits1(&h->gb);
3639 if (field_pic_flag) {
3640 bottom_field_flag = get_bits1(&h->gb);
3641 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3643 h->picture_structure = PICT_FRAME;
3644 h->mb_aff_frame = h->sps.mb_aff;
3647 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3649 if (h0->current_slice != 0) {
3650 if (last_pic_structure != h->picture_structure ||
3651 last_pic_droppable != h->droppable) {
3652 av_log(h->avctx, AV_LOG_ERROR,
3653 "Changing field mode (%d -> %d) between slices is not allowed\n",
3654 last_pic_structure, h->picture_structure);
3655 h->picture_structure = last_pic_structure;
3656 h->droppable = last_pic_droppable;
3657 return AVERROR_INVALIDDATA;
3658 } else if (!h0->cur_pic_ptr) {
3659 av_log(h->avctx, AV_LOG_ERROR,
3660 "unset cur_pic_ptr on %d. slice\n",
3661 h0->current_slice + 1);
3662 return AVERROR_INVALIDDATA;
3665 /* Shorten frame num gaps so we don't have to allocate reference
3666 * frames just to throw them away */
3667 if (h->frame_num != h->prev_frame_num) {
3668 int unwrap_prev_frame_num = h->prev_frame_num;
3669 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3671 if (unwrap_prev_frame_num > h->frame_num)
3672 unwrap_prev_frame_num -= max_frame_num;
3674 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3675 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3676 if (unwrap_prev_frame_num < 0)
3677 unwrap_prev_frame_num += max_frame_num;
3679 h->prev_frame_num = unwrap_prev_frame_num;
3683 /* See if we have a decoded first field looking for a pair...
3684 * Here, we're using that to see if we should mark previously
3685 * decode frames as "finished".
3686 * We have to do that before the "dummy" in-between frame allocation,
3687 * since that can modify h->cur_pic_ptr. */
3688 if (h0->first_field) {
3689 assert(h0->cur_pic_ptr);
3690 assert(h0->cur_pic_ptr->f.buf[0]);
3691 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3693 /* Mark old field/frame as completed */
3694 if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
3695 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3696 last_pic_structure == PICT_BOTTOM_FIELD);
3699 /* figure out if we have a complementary field pair */
3700 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3701 /* Previous field is unmatched. Don't display it, but let it
3702 * remain for reference if marked as such. */
3703 if (last_pic_structure != PICT_FRAME) {
3704 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3705 last_pic_structure == PICT_TOP_FIELD);
3708 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3709 /* This and previous field were reference, but had
3710 * different frame_nums. Consider this field first in
3711 * pair. Throw away previous field except for reference
3713 if (last_pic_structure != PICT_FRAME) {
3714 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3715 last_pic_structure == PICT_TOP_FIELD);
3718 /* Second field in complementary pair */
3719 if (!((last_pic_structure == PICT_TOP_FIELD &&
3720 h->picture_structure == PICT_BOTTOM_FIELD) ||
3721 (last_pic_structure == PICT_BOTTOM_FIELD &&
3722 h->picture_structure == PICT_TOP_FIELD))) {
3723 av_log(h->avctx, AV_LOG_ERROR,
3724 "Invalid field mode combination %d/%d\n",
3725 last_pic_structure, h->picture_structure);
3726 h->picture_structure = last_pic_structure;
3727 h->droppable = last_pic_droppable;
3728 return AVERROR_INVALIDDATA;
3729 } else if (last_pic_droppable != h->droppable) {
3730 avpriv_request_sample(h->avctx,
3731 "Found reference and non-reference fields in the same frame, which");
3732 h->picture_structure = last_pic_structure;
3733 h->droppable = last_pic_droppable;
3734 return AVERROR_PATCHWELCOME;
3740 while (h->frame_num != h->prev_frame_num && !h0->first_field &&
3741 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3742 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3743 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3744 h->frame_num, h->prev_frame_num);
3745 if (!h->sps.gaps_in_frame_num_allowed_flag)
3746 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3747 h->last_pocs[i] = INT_MIN;
3748 ret = h264_frame_start(h);
3751 h->prev_frame_num++;
3752 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3753 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3754 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3755 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3756 ret = ff_generate_sliding_window_mmcos(h, 1);
3757 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3759 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3760 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3762 /* Error concealment: If a ref is missing, copy the previous ref
3764 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3765 * many assumptions about there being no actual duplicates.
3766 * FIXME: This does not copy padding for out-of-frame motion
3767 * vectors. Given we are concealing a lost frame, this probably
3768 * is not noticeable by comparison, but it should be fixed. */
3769 if (h->short_ref_count) {
3771 av_image_copy(h->short_ref[0]->f.data,
3772 h->short_ref[0]->f.linesize,
3773 (const uint8_t **)prev->f.data,
3778 h->short_ref[0]->poc = prev->poc + 2;
3780 h->short_ref[0]->frame_num = h->prev_frame_num;
3784 /* See if we have a decoded first field looking for a pair...
3785 * We're using that to see whether to continue decoding in that
3786 * frame, or to allocate a new one. */
3787 if (h0->first_field) {
3788 assert(h0->cur_pic_ptr);
3789 assert(h0->cur_pic_ptr->f.buf[0]);
3790 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3792 /* figure out if we have a complementary field pair */
3793 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3794 /* Previous field is unmatched. Don't display it, but let it
3795 * remain for reference if marked as such. */
3796 h0->cur_pic_ptr = NULL;
3797 h0->first_field = FIELD_PICTURE(h);
3799 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3800 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3801 h0->picture_structure==PICT_BOTTOM_FIELD);
3802 /* This and the previous field had different frame_nums.
3803 * Consider this field first in pair. Throw away previous
3804 * one except for reference purposes. */
3805 h0->first_field = 1;
3806 h0->cur_pic_ptr = NULL;
3808 /* Second field in complementary pair */
3809 h0->first_field = 0;
3813 /* Frame or first field in a potentially complementary pair */
3814 h0->first_field = FIELD_PICTURE(h);
3817 if (!FIELD_PICTURE(h) || h0->first_field) {
3818 if (h264_frame_start(h) < 0) {
3819 h0->first_field = 0;
3820 return AVERROR_INVALIDDATA;
3823 release_unused_pictures(h, 0);
3825 /* Some macroblocks can be accessed before they're available in case
3826 * of lost slices, MBAFF or threading. */
3827 if (FIELD_PICTURE(h)) {
3828 for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
3829 memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
3831 memset(h->slice_table, -1,
3832 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
3834 h0->last_slice_type = -1;
3836 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3839 /* can't be in alloc_tables because linesize isn't known there.
3840 * FIXME: redo bipred weight to not require extra buffer? */
3841 for (i = 0; i < h->slice_context_count; i++)
3842 if (h->thread_context[i]) {
3843 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
3848 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3850 av_assert1(h->mb_num == h->mb_width * h->mb_height);
3851 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3852 first_mb_in_slice >= h->mb_num) {
3853 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3854 return AVERROR_INVALIDDATA;
3856 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3857 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3858 FIELD_OR_MBAFF_PICTURE(h);
3859 if (h->picture_structure == PICT_BOTTOM_FIELD)
3860 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3861 av_assert1(h->mb_y < h->mb_height);
3863 if (h->picture_structure == PICT_FRAME) {
3864 h->curr_pic_num = h->frame_num;
3865 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3867 h->curr_pic_num = 2 * h->frame_num + 1;
3868 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3871 if (h->nal_unit_type == NAL_IDR_SLICE)
3872 get_ue_golomb(&h->gb); /* idr_pic_id */
3874 if (h->sps.poc_type == 0) {
3875 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3877 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3878 h->delta_poc_bottom = get_se_golomb(&h->gb);
3881 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3882 h->delta_poc[0] = get_se_golomb(&h->gb);
3884 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3885 h->delta_poc[1] = get_se_golomb(&h->gb);
3888 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3890 if (h->pps.redundant_pic_cnt_present)
3891 h->redundant_pic_count = get_ue_golomb(&h->gb);
3893 ret = ff_set_ref_count(h);
3897 if (slice_type != AV_PICTURE_TYPE_I &&
3898 (h0->current_slice == 0 ||
3899 slice_type != h0->last_slice_type ||
3900 memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3902 ff_h264_fill_default_ref_list(h);
3905 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3906 ret = ff_h264_decode_ref_pic_list_reordering(h);
3908 h->ref_count[1] = h->ref_count[0] = 0;
3913 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3914 (h->pps.weighted_bipred_idc == 1 &&
3915 h->slice_type_nos == AV_PICTURE_TYPE_B))
3916 ff_pred_weight_table(h);
3917 else if (h->pps.weighted_bipred_idc == 2 &&
3918 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3919 implicit_weight_table(h, -1);
3922 for (i = 0; i < 2; i++) {
3923 h->luma_weight_flag[i] = 0;
3924 h->chroma_weight_flag[i] = 0;
3928 // If frame-mt is enabled, only update mmco tables for the first slice
3929 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3930 // or h->mmco, which will cause ref list mix-ups and decoding errors
3931 // further down the line. This may break decoding if the first slice is
3932 // corrupt, thus we only do this if frame-mt is enabled.
3933 if (h->nal_ref_idc) {
3934 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3935 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3936 h0->current_slice == 0);
3937 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3938 return AVERROR_INVALIDDATA;
3941 if (FRAME_MBAFF(h)) {
3942 ff_h264_fill_mbaff_ref_list(h);
3944 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3945 implicit_weight_table(h, 0);
3946 implicit_weight_table(h, 1);
3950 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3951 ff_h264_direct_dist_scale_factor(h);
3952 ff_h264_direct_ref_list_init(h);
3954 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3955 tmp = get_ue_golomb_31(&h->gb);
3957 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3958 return AVERROR_INVALIDDATA;
3960 h->cabac_init_idc = tmp;
3963 h->last_qscale_diff = 0;
3964 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3965 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3966 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3967 return AVERROR_INVALIDDATA;
3970 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3971 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3972 // FIXME qscale / qp ... stuff
3973 if (h->slice_type == AV_PICTURE_TYPE_SP)
3974 get_bits1(&h->gb); /* sp_for_switch_flag */
3975 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3976 h->slice_type == AV_PICTURE_TYPE_SI)
3977 get_se_golomb(&h->gb); /* slice_qs_delta */
3979 h->deblocking_filter = 1;
3980 h->slice_alpha_c0_offset = 52;
3981 h->slice_beta_offset = 52;
3982 if (h->pps.deblocking_filter_parameters_present) {
3983 tmp = get_ue_golomb_31(&h->gb);
3985 av_log(h->avctx, AV_LOG_ERROR,
3986 "deblocking_filter_idc %u out of range\n", tmp);
3987 return AVERROR_INVALIDDATA;
3989 h->deblocking_filter = tmp;
3990 if (h->deblocking_filter < 2)
3991 h->deblocking_filter ^= 1; // 1<->0
3993 if (h->deblocking_filter) {
3994 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3995 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3996 if (h->slice_alpha_c0_offset > 104U ||
3997 h->slice_beta_offset > 104U) {
3998 av_log(h->avctx, AV_LOG_ERROR,
3999 "deblocking filter parameters %d %d out of range\n",
4000 h->slice_alpha_c0_offset, h->slice_beta_offset);
4001 return AVERROR_INVALIDDATA;
4006 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
4007 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
4008 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
4009 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
4010 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
4011 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
4012 h->nal_ref_idc == 0))
4013 h->deblocking_filter = 0;
4015 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
4016 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
4017 /* Cheat slightly for speed:
4018 * Do not bother to deblock across slices. */
4019 h->deblocking_filter = 2;
4021 h0->max_contexts = 1;
4022 if (!h0->single_decode_warning) {
4023 av_log(h->avctx, AV_LOG_INFO,
4024 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
4025 h0->single_decode_warning = 1;
4028 av_log(h->avctx, AV_LOG_ERROR,
4029 "Deblocking switched inside frame.\n");
4034 h->qp_thresh = 15 + 52 -
4035 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
4037 h->pps.chroma_qp_index_offset[0],
4038 h->pps.chroma_qp_index_offset[1]) +
4039 6 * (h->sps.bit_depth_luma - 8);
4041 h0->last_slice_type = slice_type;
4042 memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
4043 h->slice_num = ++h0->current_slice;
4046 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
4047 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
4048 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
4049 && h->slice_num >= MAX_SLICES) {
4050 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
4051 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);
4054 for (j = 0; j < 2; j++) {
4056 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
4057 for (i = 0; i < 16; i++) {
4059 if (j < h->list_count && i < h->ref_count[j] &&
4060 h->ref_list[j][i].f.buf[0]) {
4062 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
4063 for (k = 0; k < h->short_ref_count; k++)
4064 if (h->short_ref[k]->f.buf[0]->buffer == buf) {
4068 for (k = 0; k < h->long_ref_count; k++)
4069 if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
4070 id_list[i] = h->short_ref_count + k;
4078 for (i = 0; i < 16; i++)
4079 ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
4081 ref2frm[18 + 1] = -1;
4082 for (i = 16; i < 48; i++)
4083 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
4084 (h->ref_list[j][i].reference & 3);
4087 if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
4088 if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
4089 h->er.ref_count = h->ref_count[0];
4091 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
4092 av_log(h->avctx, AV_LOG_DEBUG,
4093 "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",
4095 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
4097 av_get_picture_type_char(h->slice_type),
4098 h->slice_type_fixed ? " fix" : "",
4099 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
4100 pps_id, h->frame_num,
4101 h->cur_pic_ptr->field_poc[0],
4102 h->cur_pic_ptr->field_poc[1],
4103 h->ref_count[0], h->ref_count[1],
4105 h->deblocking_filter,
4106 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
4108 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
4109 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
4115 int ff_h264_get_slice_type(const H264Context *h)
4117 switch (h->slice_type) {
4118 case AV_PICTURE_TYPE_P:
4120 case AV_PICTURE_TYPE_B:
4122 case AV_PICTURE_TYPE_I:
4124 case AV_PICTURE_TYPE_SP:
4126 case AV_PICTURE_TYPE_SI:
4129 return AVERROR_INVALIDDATA;
4133 static av_always_inline void fill_filter_caches_inter(H264Context *h,
4134 int mb_type, int top_xy,
4135 int left_xy[LEFT_MBS],
4137 int left_type[LEFT_MBS],
4138 int mb_xy, int list)
4140 int b_stride = h->b_stride;
4141 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4142 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4143 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4144 if (USES_LIST(top_type, list)) {
4145 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
4146 const int b8_xy = 4 * top_xy + 2;
4147 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4148 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4149 ref_cache[0 - 1 * 8] =
4150 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4151 ref_cache[2 - 1 * 8] =
4152 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4154 AV_ZERO128(mv_dst - 1 * 8);
4155 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4158 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4159 if (USES_LIST(left_type[LTOP], list)) {
4160 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
4161 const int b8_xy = 4 * left_xy[LTOP] + 1;
4162 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4163 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4164 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4165 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4166 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4168 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4169 ref_cache[-1 + 16] =
4170 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4172 AV_ZERO32(mv_dst - 1 + 0);
4173 AV_ZERO32(mv_dst - 1 + 8);
4174 AV_ZERO32(mv_dst - 1 + 16);
4175 AV_ZERO32(mv_dst - 1 + 24);
4178 ref_cache[-1 + 16] =
4179 ref_cache[-1 + 24] = LIST_NOT_USED;
4184 if (!USES_LIST(mb_type, list)) {
4185 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4186 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4187 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4188 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4189 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4194 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4195 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4196 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4197 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4198 AV_WN32A(&ref_cache[0 * 8], ref01);
4199 AV_WN32A(&ref_cache[1 * 8], ref01);
4200 AV_WN32A(&ref_cache[2 * 8], ref23);
4201 AV_WN32A(&ref_cache[3 * 8], ref23);
4205 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4206 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4207 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4208 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4209 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4215 * @return non zero if the loop filter can be skipped
4217 static int fill_filter_caches(H264Context *h, int mb_type)
4219 const int mb_xy = h->mb_xy;
4220 int top_xy, left_xy[LEFT_MBS];
4221 int top_type, left_type[LEFT_MBS];
4225 top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4227 /* Wow, what a mess, why didn't they simplify the interlacing & intra
4228 * stuff, I can't imagine that these complex rules are worth it. */
4230 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4231 if (FRAME_MBAFF(h)) {
4232 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4233 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4235 if (left_mb_field_flag != curr_mb_field_flag)
4236 left_xy[LTOP] -= h->mb_stride;
4238 if (curr_mb_field_flag)
4239 top_xy += h->mb_stride &
4240 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4241 if (left_mb_field_flag != curr_mb_field_flag)
4242 left_xy[LBOT] += h->mb_stride;
4246 h->top_mb_xy = top_xy;
4247 h->left_mb_xy[LTOP] = left_xy[LTOP];
4248 h->left_mb_xy[LBOT] = left_xy[LBOT];
4250 /* For sufficiently low qp, filtering wouldn't do anything.
4251 * This is a conservative estimate: could also check beta_offset
4252 * and more accurate chroma_qp. */
4253 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4254 int qp = h->cur_pic.qscale_table[mb_xy];
4255 if (qp <= qp_thresh &&
4256 (left_xy[LTOP] < 0 ||
4257 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4259 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4260 if (!FRAME_MBAFF(h))
4262 if ((left_xy[LTOP] < 0 ||
4263 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4264 (top_xy < h->mb_stride ||
4265 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4270 top_type = h->cur_pic.mb_type[top_xy];
4271 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4272 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4273 if (h->deblocking_filter == 2) {
4274 if (h->slice_table[top_xy] != h->slice_num)
4276 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4277 left_type[LTOP] = left_type[LBOT] = 0;
4279 if (h->slice_table[top_xy] == 0xFFFF)
4281 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4282 left_type[LTOP] = left_type[LBOT] = 0;
4284 h->top_type = top_type;
4285 h->left_type[LTOP] = left_type[LTOP];
4286 h->left_type[LBOT] = left_type[LBOT];
4288 if (IS_INTRA(mb_type))
4291 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4292 top_type, left_type, mb_xy, 0);
4293 if (h->list_count == 2)
4294 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4295 top_type, left_type, mb_xy, 1);
4297 nnz = h->non_zero_count[mb_xy];
4298 nnz_cache = h->non_zero_count_cache;
4299 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4300 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4301 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4302 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4303 h->cbp = h->cbp_table[mb_xy];
4306 nnz = h->non_zero_count[top_xy];
4307 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4310 if (left_type[LTOP]) {
4311 nnz = h->non_zero_count[left_xy[LTOP]];
4312 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4313 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4314 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4315 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4318 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4319 * from what the loop filter needs */
4320 if (!CABAC(h) && h->pps.transform_8x8_mode) {
4321 if (IS_8x8DCT(top_type)) {
4322 nnz_cache[4 + 8 * 0] =
4323 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4324 nnz_cache[6 + 8 * 0] =
4325 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4327 if (IS_8x8DCT(left_type[LTOP])) {
4328 nnz_cache[3 + 8 * 1] =
4329 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4331 if (IS_8x8DCT(left_type[LBOT])) {
4332 nnz_cache[3 + 8 * 3] =
4333 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4336 if (IS_8x8DCT(mb_type)) {
4337 nnz_cache[scan8[0]] =
4338 nnz_cache[scan8[1]] =
4339 nnz_cache[scan8[2]] =
4340 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4342 nnz_cache[scan8[0 + 4]] =
4343 nnz_cache[scan8[1 + 4]] =
4344 nnz_cache[scan8[2 + 4]] =
4345 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4347 nnz_cache[scan8[0 + 8]] =
4348 nnz_cache[scan8[1 + 8]] =
4349 nnz_cache[scan8[2 + 8]] =
4350 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4352 nnz_cache[scan8[0 + 12]] =
4353 nnz_cache[scan8[1 + 12]] =
4354 nnz_cache[scan8[2 + 12]] =
4355 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4362 static void loop_filter(H264Context *h, int start_x, int end_x)
4364 uint8_t *dest_y, *dest_cb, *dest_cr;
4365 int linesize, uvlinesize, mb_x, mb_y;
4366 const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4367 const int old_slice_type = h->slice_type;
4368 const int pixel_shift = h->pixel_shift;
4369 const int block_h = 16 >> h->chroma_y_shift;
4371 if (h->deblocking_filter) {
4372 for (mb_x = start_x; mb_x < end_x; mb_x++)
4373 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4375 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4376 h->slice_num = h->slice_table[mb_xy];
4377 mb_type = h->cur_pic.mb_type[mb_xy];
4378 h->list_count = h->list_counts[mb_xy];
4382 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4386 dest_y = h->cur_pic.f.data[0] +
4387 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4388 dest_cb = h->cur_pic.f.data[1] +
4389 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4390 mb_y * h->uvlinesize * block_h;
4391 dest_cr = h->cur_pic.f.data[2] +
4392 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4393 mb_y * h->uvlinesize * block_h;
4394 // FIXME simplify above
4397 linesize = h->mb_linesize = h->linesize * 2;
4398 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4399 if (mb_y & 1) { // FIXME move out of this function?
4400 dest_y -= h->linesize * 15;
4401 dest_cb -= h->uvlinesize * (block_h - 1);
4402 dest_cr -= h->uvlinesize * (block_h - 1);
4405 linesize = h->mb_linesize = h->linesize;
4406 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4408 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4410 if (fill_filter_caches(h, mb_type))
4412 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4413 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4415 if (FRAME_MBAFF(h)) {
4416 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4417 linesize, uvlinesize);
4419 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4420 dest_cr, linesize, uvlinesize);
4424 h->slice_type = old_slice_type;
4426 h->mb_y = end_mb_y - FRAME_MBAFF(h);
4427 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4428 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4431 static void predict_field_decoding_flag(H264Context *h)
4433 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4434 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4435 h->cur_pic.mb_type[mb_xy - 1] :
4436 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4437 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4438 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4442 * Draw edges and report progress for the last MB row.
4444 static void decode_finish_row(H264Context *h)
4446 int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4447 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4448 int height = 16 << FRAME_MBAFF(h);
4449 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4451 if (h->deblocking_filter) {
4452 if ((top + height) >= pic_height)
4453 height += deblock_border;
4454 top -= deblock_border;
4457 if (top >= pic_height || (top + height) < 0)
4460 height = FFMIN(height, pic_height - top);
4462 height = top + height;
4466 ff_h264_draw_horiz_band(h, top, height);
4468 if (h->droppable || h->er.error_occurred)
4471 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4472 h->picture_structure == PICT_BOTTOM_FIELD);
4475 static void er_add_slice(H264Context *h, int startx, int starty,
4476 int endx, int endy, int status)
4478 if (CONFIG_ERROR_RESILIENCE) {
4479 ERContext *er = &h->er;
4481 ff_er_add_slice(er, startx, starty, endx, endy, status);
4485 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4487 H264Context *h = *(void **)arg;
4488 int lf_x_start = h->mb_x;
4490 h->mb_skip_run = -1;
4492 av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4494 h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4495 avctx->codec_id != AV_CODEC_ID_H264 ||
4496 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4498 if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
4499 const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
4501 int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
4502 prev_status &= ~ VP_START;
4503 if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
4504 h->er.error_occurred = 1;
4510 align_get_bits(&h->gb);
4513 ff_init_cabac_decoder(&h->cabac,
4514 h->gb.buffer + get_bits_count(&h->gb) / 8,
4515 (get_bits_left(&h->gb) + 7) / 8);
4517 ff_h264_init_cabac_states(h);
4521 int ret = ff_h264_decode_mb_cabac(h);
4523 // STOP_TIMER("decode_mb_cabac")
4526 ff_h264_hl_decode_mb(h);
4528 // FIXME optimal? or let mb_decode decode 16x32 ?
4529 if (ret >= 0 && FRAME_MBAFF(h)) {
4532 ret = ff_h264_decode_mb_cabac(h);
4535 ff_h264_hl_decode_mb(h);
4538 eos = get_cabac_terminate(&h->cabac);
4540 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4541 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4542 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4543 h->mb_y, ER_MB_END);
4544 if (h->mb_x >= lf_x_start)
4545 loop_filter(h, lf_x_start, h->mb_x + 1);
4548 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4549 av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4550 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4551 av_log(h->avctx, AV_LOG_ERROR,
4552 "error while decoding MB %d %d, bytestream (%td)\n",
4554 h->cabac.bytestream_end - h->cabac.bytestream);
4555 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4556 h->mb_y, ER_MB_ERROR);
4557 return AVERROR_INVALIDDATA;
4560 if (++h->mb_x >= h->mb_width) {
4561 loop_filter(h, lf_x_start, h->mb_x);
4562 h->mb_x = lf_x_start = 0;
4563 decode_finish_row(h);
4565 if (FIELD_OR_MBAFF_PICTURE(h)) {
4567 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4568 predict_field_decoding_flag(h);
4572 if (eos || h->mb_y >= h->mb_height) {
4573 tprintf(h->avctx, "slice end %d %d\n",
4574 get_bits_count(&h->gb), h->gb.size_in_bits);
4575 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4576 h->mb_y, ER_MB_END);
4577 if (h->mb_x > lf_x_start)
4578 loop_filter(h, lf_x_start, h->mb_x);
4584 int ret = ff_h264_decode_mb_cavlc(h);
4587 ff_h264_hl_decode_mb(h);
4589 // FIXME optimal? or let mb_decode decode 16x32 ?
4590 if (ret >= 0 && FRAME_MBAFF(h)) {
4592 ret = ff_h264_decode_mb_cavlc(h);
4595 ff_h264_hl_decode_mb(h);
4600 av_log(h->avctx, AV_LOG_ERROR,
4601 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4602 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4603 h->mb_y, ER_MB_ERROR);
4607 if (++h->mb_x >= h->mb_width) {
4608 loop_filter(h, lf_x_start, h->mb_x);
4609 h->mb_x = lf_x_start = 0;
4610 decode_finish_row(h);
4612 if (FIELD_OR_MBAFF_PICTURE(h)) {
4614 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4615 predict_field_decoding_flag(h);
4617 if (h->mb_y >= h->mb_height) {
4618 tprintf(h->avctx, "slice end %d %d\n",
4619 get_bits_count(&h->gb), h->gb.size_in_bits);
4621 if ( get_bits_left(&h->gb) == 0
4622 || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4623 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4624 h->mb_x - 1, h->mb_y,
4629 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4633 return AVERROR_INVALIDDATA;
4638 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4639 tprintf(h->avctx, "slice end %d %d\n",
4640 get_bits_count(&h->gb), h->gb.size_in_bits);
4642 if (get_bits_left(&h->gb) == 0) {
4643 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4644 h->mb_x - 1, h->mb_y,
4646 if (h->mb_x > lf_x_start)
4647 loop_filter(h, lf_x_start, h->mb_x);
4651 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4652 h->mb_y, ER_MB_ERROR);
4654 return AVERROR_INVALIDDATA;
4662 * Call decode_slice() for each context.
4664 * @param h h264 master context
4665 * @param context_count number of contexts to execute
4667 static int execute_decode_slices(H264Context *h, int context_count)
4669 AVCodecContext *const avctx = h->avctx;
4673 if (h->avctx->hwaccel ||
4674 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4676 if (context_count == 1) {
4677 return decode_slice(avctx, &h);
4679 av_assert0(context_count > 0);
4680 for (i = 1; i < context_count; i++) {
4681 hx = h->thread_context[i];
4682 if (CONFIG_ERROR_RESILIENCE) {
4683 hx->er.error_count = 0;
4685 hx->x264_build = h->x264_build;
4688 avctx->execute(avctx, decode_slice, h->thread_context,
4689 NULL, context_count, sizeof(void *));
4691 /* pull back stuff from slices to master context */
4692 hx = h->thread_context[context_count - 1];
4695 h->droppable = hx->droppable;
4696 h->picture_structure = hx->picture_structure;
4697 if (CONFIG_ERROR_RESILIENCE) {
4698 for (i = 1; i < context_count; i++)
4699 h->er.error_count += h->thread_context[i]->er.error_count;
4706 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
4708 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4709 int parse_extradata)
4711 AVCodecContext *const avctx = h->avctx;
4712 H264Context *hx; ///< thread context
4716 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4717 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4720 int first_slice = 0;
4723 h->nal_unit_type= 0;
4725 if(!h->slice_context_count)
4726 h->slice_context_count= 1;
4727 h->max_contexts = h->slice_context_count;
4728 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4729 h->current_slice = 0;
4730 if (!h->first_field)
4731 h->cur_pic_ptr = NULL;
4732 ff_h264_reset_sei(h);
4735 if (h->nal_length_size == 4) {
4736 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4738 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4742 for (; pass <= 1; pass++) {
4745 next_avc = h->is_avc ? 0 : buf_size;
4755 if (buf_index >= next_avc) {
4756 if (buf_index >= buf_size - h->nal_length_size)
4759 for (i = 0; i < h->nal_length_size; i++)
4760 nalsize = (nalsize << 8) | buf[buf_index++];
4761 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4762 av_log(h->avctx, AV_LOG_ERROR,
4763 "AVC: nal size %d\n", nalsize);
4766 next_avc = buf_index + nalsize;
4768 // start code prefix search
4769 for (; buf_index + 3 < next_avc; buf_index++)
4770 // This should always succeed in the first iteration.
4771 if (buf[buf_index] == 0 &&
4772 buf[buf_index + 1] == 0 &&
4773 buf[buf_index + 2] == 1)
4776 if (buf_index + 3 >= buf_size) {
4777 buf_index = buf_size;
4782 if (buf_index >= next_avc)
4786 hx = h->thread_context[context_count];
4788 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4789 &consumed, next_avc - buf_index);
4790 if (ptr == NULL || dst_length < 0) {
4794 i = buf_index + consumed;
4795 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4796 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4797 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4798 h->workaround_bugs |= FF_BUG_TRUNCATED;
4800 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4801 while (dst_length > 0 && ptr[dst_length - 1] == 0)
4803 bit_length = !dst_length ? 0
4805 decode_rbsp_trailing(h, ptr + dst_length - 1));
4807 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4808 av_log(h->avctx, AV_LOG_DEBUG,
4809 "NAL %d/%d at %d/%d length %d pass %d\n",
4810 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
4812 if (h->is_avc && (nalsize != consumed) && nalsize)
4813 av_log(h->avctx, AV_LOG_DEBUG,
4814 "AVC: Consumed only %d bytes instead of %d\n",
4817 buf_index += consumed;
4821 /* packets can sometimes contain multiple PPS/SPS,
4822 * e.g. two PAFF field pictures in one packet, or a demuxer
4823 * which splits NALs strangely if so, when frame threading we
4824 * can't start the next thread until we've read all of them */
4825 switch (hx->nal_unit_type) {
4828 nals_needed = nal_index;
4833 init_get_bits(&hx->gb, ptr, bit_length);
4834 if (!get_ue_golomb(&hx->gb) || !first_slice)
4835 nals_needed = nal_index;
4837 first_slice = hx->nal_unit_type;
4843 switch (hx->nal_unit_type) {
4847 first_slice = hx->nal_unit_type;
4850 if (avctx->skip_frame >= AVDISCARD_NONREF &&
4851 h->nal_ref_idc == 0 &&
4852 h->nal_unit_type != NAL_SEI)
4856 /* Ignore per frame NAL unit type during extradata
4857 * parsing. Decoding slices is not possible in codec init
4859 if (parse_extradata) {
4860 switch (hx->nal_unit_type) {
4866 av_log(h->avctx, AV_LOG_WARNING,
4867 "Ignoring NAL %d in global header/extradata\n",
4869 // fall through to next case
4870 case NAL_AUXILIARY_SLICE:
4871 hx->nal_unit_type = NAL_FF_IGNORE;
4877 switch (hx->nal_unit_type) {
4879 if (first_slice != NAL_IDR_SLICE) {
4880 av_log(h->avctx, AV_LOG_ERROR,
4881 "Invalid mix of idr and non-idr slices\n");
4886 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4889 init_get_bits(&hx->gb, ptr, bit_length);
4891 hx->inter_gb_ptr = &hx->gb;
4892 hx->data_partitioning = 0;
4894 if ((err = decode_slice_header(hx, h)))
4897 if (h->sei_recovery_frame_cnt >= 0) {
4898 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
4899 h->valid_recovery_point = 1;
4901 if ( h->recovery_frame < 0
4902 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
4903 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4904 ((1 << h->sps.log2_max_frame_num) - 1);
4906 if (!h->valid_recovery_point)
4907 h->recovery_frame = h->frame_num;
4911 h->cur_pic_ptr->f.key_frame |=
4912 (hx->nal_unit_type == NAL_IDR_SLICE);
4914 if (hx->nal_unit_type == NAL_IDR_SLICE ||
4915 h->recovery_frame == h->frame_num) {
4916 h->recovery_frame = -1;
4917 h->cur_pic_ptr->recovered = 1;
4919 // If we have an IDR, all frames after it in decoded order are
4921 if (hx->nal_unit_type == NAL_IDR_SLICE)
4922 h->frame_recovered |= FRAME_RECOVERED_IDR;
4923 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
4924 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
4926 h->cur_pic_ptr->recovered |= h->frame_recovered;
4928 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
4931 if (h->current_slice == 1) {
4932 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4933 decode_postinit(h, nal_index >= nals_needed);
4935 if (h->avctx->hwaccel &&
4936 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4938 if (CONFIG_H264_VDPAU_DECODER &&
4939 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4940 ff_vdpau_h264_picture_start(h);
4943 if (hx->redundant_pic_count == 0 &&
4944 (avctx->skip_frame < AVDISCARD_NONREF ||
4946 (avctx->skip_frame < AVDISCARD_BIDIR ||
4947 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4948 (avctx->skip_frame < AVDISCARD_NONKEY ||
4949 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4950 avctx->skip_frame < AVDISCARD_ALL) {
4951 if (avctx->hwaccel) {
4952 ret = avctx->hwaccel->decode_slice(avctx,
4953 &buf[buf_index - consumed],
4957 } else if (CONFIG_H264_VDPAU_DECODER &&
4958 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4959 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4961 sizeof(start_code));
4962 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4963 &buf[buf_index - consumed],
4970 init_get_bits(&hx->gb, ptr, bit_length);
4972 hx->inter_gb_ptr = NULL;
4974 if ((err = decode_slice_header(hx, h)) < 0) {
4975 /* make sure data_partitioning is cleared if it was set
4976 * before, so we don't try decoding a slice without a valid
4977 * slice header later */
4978 h->data_partitioning = 0;
4982 hx->data_partitioning = 1;
4985 init_get_bits(&hx->intra_gb, ptr, bit_length);
4986 hx->intra_gb_ptr = &hx->intra_gb;
4989 init_get_bits(&hx->inter_gb, ptr, bit_length);
4990 hx->inter_gb_ptr = &hx->inter_gb;
4992 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
4995 if (hx->redundant_pic_count == 0 &&
4997 hx->data_partitioning &&
4998 h->cur_pic_ptr && h->context_initialized &&
4999 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
5000 (avctx->skip_frame < AVDISCARD_BIDIR ||
5001 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
5002 (avctx->skip_frame < AVDISCARD_NONKEY ||
5003 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
5004 avctx->skip_frame < AVDISCARD_ALL)
5008 init_get_bits(&h->gb, ptr, bit_length);
5009 ff_h264_decode_sei(h);
5012 init_get_bits(&h->gb, ptr, bit_length);
5013 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
5014 av_log(h->avctx, AV_LOG_DEBUG,
5015 "SPS decoding failure, trying again with the complete NAL\n");
5017 av_assert0(next_avc - buf_index + consumed == nalsize);
5018 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
5020 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
5021 8*(next_avc - buf_index + consumed - 1));
5022 ff_h264_decode_seq_parameter_set(h);
5027 init_get_bits(&h->gb, ptr, bit_length);
5028 ff_h264_decode_picture_parameter_set(h, bit_length);
5031 case NAL_END_SEQUENCE:
5032 case NAL_END_STREAM:
5033 case NAL_FILLER_DATA:
5035 case NAL_AUXILIARY_SLICE:
5040 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
5041 hx->nal_unit_type, bit_length);
5044 if (context_count == h->max_contexts) {
5045 execute_decode_slices(h, context_count);
5050 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
5051 else if (err == 1) {
5052 /* Slice could not be decoded in parallel mode, copy down
5053 * NAL unit stuff to context 0 and restart. Note that
5054 * rbsp_buffer is not transferred, but since we no longer
5055 * run in parallel mode this should not be an issue. */
5056 h->nal_unit_type = hx->nal_unit_type;
5057 h->nal_ref_idc = hx->nal_ref_idc;
5064 execute_decode_slices(h, context_count);
5068 if (h->cur_pic_ptr && !h->droppable) {
5069 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
5070 h->picture_structure == PICT_BOTTOM_FIELD);
5073 return (ret < 0) ? ret : buf_index;
5077 * Return the number of bytes consumed for building the current frame.
5079 static int get_consumed_bytes(int pos, int buf_size)
5082 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
5083 if (pos + 10 > buf_size)
5084 pos = buf_size; // oops ;)
5089 static int output_frame(H264Context *h, AVFrame *dst, Picture *srcp)
5091 AVFrame *src = &srcp->f;
5093 int ret = av_frame_ref(dst, src);
5097 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
5102 for (i = 0; i < 3; i++) {
5103 int hshift = (i > 0) ? h->chroma_x_shift : 0;
5104 int vshift = (i > 0) ? h->chroma_y_shift : 0;
5105 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
5106 (srcp->crop_top >> vshift) * dst->linesize[i];
5107 dst->data[i] += off;
5112 static int h264_decode_frame(AVCodecContext *avctx, void *data,
5113 int *got_frame, AVPacket *avpkt)
5115 const uint8_t *buf = avpkt->data;
5116 int buf_size = avpkt->size;
5117 H264Context *h = avctx->priv_data;
5118 AVFrame *pict = data;
5124 h->flags = avctx->flags;
5126 /* end of stream, output what is still in the buffers */
5127 if (buf_size == 0) {
5130 h->cur_pic_ptr = NULL;
5133 // FIXME factorize this with the output code below
5134 out = h->delayed_pic[0];
5137 h->delayed_pic[i] &&
5138 !h->delayed_pic[i]->f.key_frame &&
5139 !h->delayed_pic[i]->mmco_reset;
5141 if (h->delayed_pic[i]->poc < out->poc) {
5142 out = h->delayed_pic[i];
5146 for (i = out_idx; h->delayed_pic[i]; i++)
5147 h->delayed_pic[i] = h->delayed_pic[i + 1];
5150 out->reference &= ~DELAYED_PIC_REF;
5151 ret = output_frame(h, pict, out);
5159 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
5160 int cnt= buf[5]&0x1f;
5161 const uint8_t *p= buf+6;
5163 int nalsize= AV_RB16(p) + 2;
5164 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
5172 int nalsize= AV_RB16(p) + 2;
5173 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
5178 return ff_h264_decode_extradata(h, buf, buf_size);
5182 buf_index = decode_nal_units(h, buf, buf_size, 0);
5184 return AVERROR_INVALIDDATA;
5186 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
5187 av_assert0(buf_index <= buf_size);
5191 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
5192 if (avctx->skip_frame >= AVDISCARD_NONREF ||
5193 buf_size >= 4 && !memcmp("Q264", buf, 4))
5195 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
5196 return AVERROR_INVALIDDATA;
5199 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
5200 (h->mb_y >= h->mb_height && h->mb_height)) {
5201 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
5202 decode_postinit(h, 1);
5206 /* Wait for second field. */
5208 if (h->next_output_pic && (
5209 h->next_output_pic->recovered)) {
5210 if (!h->next_output_pic->recovered)
5211 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
5213 ret = output_frame(h, pict, h->next_output_pic);
5217 if (CONFIG_MPEGVIDEO) {
5218 ff_print_debug_info2(h->avctx, h->next_output_pic, pict, h->er.mbskip_table,
5220 h->mb_width, h->mb_height, h->mb_stride, 1);
5225 assert(pict->buf[0] || !*got_frame);
5227 return get_consumed_bytes(buf_index, buf_size);
5230 av_cold void ff_h264_free_context(H264Context *h)
5234 free_tables(h, 1); // FIXME cleanup init stuff perhaps
5236 for (i = 0; i < MAX_SPS_COUNT; i++)
5237 av_freep(h->sps_buffers + i);
5239 for (i = 0; i < MAX_PPS_COUNT; i++)
5240 av_freep(h->pps_buffers + i);
5243 static av_cold int h264_decode_end(AVCodecContext *avctx)
5245 H264Context *h = avctx->priv_data;
5247 ff_h264_remove_all_refs(h);
5248 ff_h264_free_context(h);
5250 unref_picture(h, &h->cur_pic);
5255 static const AVProfile profiles[] = {
5256 { FF_PROFILE_H264_BASELINE, "Baseline" },
5257 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
5258 { FF_PROFILE_H264_MAIN, "Main" },
5259 { FF_PROFILE_H264_EXTENDED, "Extended" },
5260 { FF_PROFILE_H264_HIGH, "High" },
5261 { FF_PROFILE_H264_HIGH_10, "High 10" },
5262 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
5263 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
5264 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
5265 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
5266 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
5267 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
5268 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
5269 { FF_PROFILE_UNKNOWN },
5272 static const AVOption h264_options[] = {
5273 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
5274 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
5278 static const AVClass h264_class = {
5279 .class_name = "H264 Decoder",
5280 .item_name = av_default_item_name,
5281 .option = h264_options,
5282 .version = LIBAVUTIL_VERSION_INT,
5285 static const AVClass h264_vdpau_class = {
5286 .class_name = "H264 VDPAU Decoder",
5287 .item_name = av_default_item_name,
5288 .option = h264_options,
5289 .version = LIBAVUTIL_VERSION_INT,
5292 AVCodec ff_h264_decoder = {
5294 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5295 .type = AVMEDIA_TYPE_VIDEO,
5296 .id = AV_CODEC_ID_H264,
5297 .priv_data_size = sizeof(H264Context),
5298 .init = ff_h264_decode_init,
5299 .close = h264_decode_end,
5300 .decode = h264_decode_frame,
5301 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5302 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
5303 CODEC_CAP_FRAME_THREADS,
5305 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
5306 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5307 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5308 .priv_class = &h264_class,
5311 #if CONFIG_H264_VDPAU_DECODER
5312 AVCodec ff_h264_vdpau_decoder = {
5313 .name = "h264_vdpau",
5314 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
5315 .type = AVMEDIA_TYPE_VIDEO,
5316 .id = AV_CODEC_ID_H264,
5317 .priv_data_size = sizeof(H264Context),
5318 .init = ff_h264_decode_init,
5319 .close = h264_decode_end,
5320 .decode = h264_decode_frame,
5321 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5323 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
5325 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5326 .priv_class = &h264_vdpau_class,