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 ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1978 if (CONFIG_ERROR_RESILIENCE) {
1979 ff_er_frame_start(&h->er);
1981 h->er.next_pic = NULL;
1984 assert(h->linesize && h->uvlinesize);
1986 for (i = 0; i < 16; i++) {
1987 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1988 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1990 for (i = 0; i < 16; i++) {
1991 h->block_offset[16 + i] =
1992 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1993 h->block_offset[48 + 16 + i] =
1994 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1997 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
1998 // h->cur_pic.reference /* || h->contains_intra */ || 1;
2000 /* We mark the current picture as non-reference after allocating it, so
2001 * that if we break out due to an error it can be released automatically
2002 * in the next ff_MPV_frame_start().
2004 h->cur_pic_ptr->reference = 0;
2006 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
2008 h->next_output_pic = NULL;
2010 assert(h->cur_pic_ptr->long_ref == 0);
2016 * Run setup operations that must be run after slice header decoding.
2017 * This includes finding the next displayed frame.
2019 * @param h h264 master context
2020 * @param setup_finished enough NALs have been read that we can call
2021 * ff_thread_finish_setup()
2023 static void decode_postinit(H264Context *h, int setup_finished)
2025 Picture *out = h->cur_pic_ptr;
2026 Picture *cur = h->cur_pic_ptr;
2027 int i, pics, out_of_order, out_idx;
2029 h->cur_pic_ptr->f.pict_type = h->pict_type;
2031 if (h->next_output_pic)
2034 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
2035 /* FIXME: if we have two PAFF fields in one packet, we can't start
2036 * the next thread here. If we have one field per packet, we can.
2037 * The check in decode_nal_units() is not good enough to find this
2038 * yet, so we assume the worst for now. */
2039 // if (setup_finished)
2040 // ff_thread_finish_setup(h->avctx);
2044 cur->f.interlaced_frame = 0;
2045 cur->f.repeat_pict = 0;
2047 /* Signal interlacing information externally. */
2048 /* Prioritize picture timing SEI information over used
2049 * decoding process if it exists. */
2051 if (h->sps.pic_struct_present_flag) {
2052 switch (h->sei_pic_struct) {
2053 case SEI_PIC_STRUCT_FRAME:
2055 case SEI_PIC_STRUCT_TOP_FIELD:
2056 case SEI_PIC_STRUCT_BOTTOM_FIELD:
2057 cur->f.interlaced_frame = 1;
2059 case SEI_PIC_STRUCT_TOP_BOTTOM:
2060 case SEI_PIC_STRUCT_BOTTOM_TOP:
2061 if (FIELD_OR_MBAFF_PICTURE(h))
2062 cur->f.interlaced_frame = 1;
2064 // try to flag soft telecine progressive
2065 cur->f.interlaced_frame = h->prev_interlaced_frame;
2067 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
2068 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
2069 /* Signal the possibility of telecined film externally
2070 * (pic_struct 5,6). From these hints, let the applications
2071 * decide if they apply deinterlacing. */
2072 cur->f.repeat_pict = 1;
2074 case SEI_PIC_STRUCT_FRAME_DOUBLING:
2075 cur->f.repeat_pict = 2;
2077 case SEI_PIC_STRUCT_FRAME_TRIPLING:
2078 cur->f.repeat_pict = 4;
2082 if ((h->sei_ct_type & 3) &&
2083 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2084 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2086 /* Derive interlacing flag from used decoding process. */
2087 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2089 h->prev_interlaced_frame = cur->f.interlaced_frame;
2091 if (cur->field_poc[0] != cur->field_poc[1]) {
2092 /* Derive top_field_first from field pocs. */
2093 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2095 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2096 /* Use picture timing SEI information. Even if it is a
2097 * information of a past frame, better than nothing. */
2098 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2099 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2100 cur->f.top_field_first = 1;
2102 cur->f.top_field_first = 0;
2104 /* Most likely progressive */
2105 cur->f.top_field_first = 0;
2109 if (h->sei_frame_packing_present &&
2110 h->frame_packing_arrangement_type >= 0 &&
2111 h->frame_packing_arrangement_type <= 6 &&
2112 h->content_interpretation_type > 0 &&
2113 h->content_interpretation_type < 3) {
2114 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
2118 switch (h->frame_packing_arrangement_type) {
2120 stereo->type = AV_STEREO3D_CHECKERBOARD;
2123 stereo->type = AV_STEREO3D_LINES;
2126 stereo->type = AV_STEREO3D_COLUMNS;
2129 if (h->quincunx_subsampling)
2130 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2132 stereo->type = AV_STEREO3D_SIDEBYSIDE;
2135 stereo->type = AV_STEREO3D_TOPBOTTOM;
2138 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
2141 stereo->type = AV_STEREO3D_2D;
2145 if (h->content_interpretation_type == 2)
2146 stereo->flags = AV_STEREO3D_FLAG_INVERT;
2149 cur->mmco_reset = h->mmco_reset;
2152 // FIXME do something with unavailable reference frames
2154 /* Sort B-frames into display order */
2156 if (h->sps.bitstream_restriction_flag &&
2157 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2158 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2162 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2163 !h->sps.bitstream_restriction_flag) {
2164 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2168 for (i = 0; 1; i++) {
2169 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2171 h->last_pocs[i-1] = cur->poc;
2174 h->last_pocs[i-1]= h->last_pocs[i];
2177 out_of_order = MAX_DELAYED_PIC_COUNT - i;
2178 if( cur->f.pict_type == AV_PICTURE_TYPE_B
2179 || (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))
2180 out_of_order = FFMAX(out_of_order, 1);
2181 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2182 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2183 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2184 h->last_pocs[i] = INT_MIN;
2185 h->last_pocs[0] = cur->poc;
2186 cur->mmco_reset = 1;
2187 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2188 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2189 h->avctx->has_b_frames = out_of_order;
2194 while (h->delayed_pic[pics])
2197 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
2199 h->delayed_pic[pics++] = cur;
2200 if (cur->reference == 0)
2201 cur->reference = DELAYED_PIC_REF;
2203 out = h->delayed_pic[0];
2205 for (i = 1; h->delayed_pic[i] &&
2206 !h->delayed_pic[i]->f.key_frame &&
2207 !h->delayed_pic[i]->mmco_reset;
2209 if (h->delayed_pic[i]->poc < out->poc) {
2210 out = h->delayed_pic[i];
2213 if (h->avctx->has_b_frames == 0 &&
2214 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2215 h->next_outputed_poc = INT_MIN;
2216 out_of_order = out->poc < h->next_outputed_poc;
2218 if (out_of_order || pics > h->avctx->has_b_frames) {
2219 out->reference &= ~DELAYED_PIC_REF;
2220 // for frame threading, the owner must be the second field's thread or
2221 // else the first thread can release the picture and reuse it unsafely
2222 for (i = out_idx; h->delayed_pic[i]; i++)
2223 h->delayed_pic[i] = h->delayed_pic[i + 1];
2225 if (!out_of_order && pics > h->avctx->has_b_frames) {
2226 h->next_output_pic = out;
2227 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2228 h->next_outputed_poc = INT_MIN;
2230 h->next_outputed_poc = out->poc;
2232 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2235 if (h->next_output_pic) {
2236 if (h->next_output_pic->recovered) {
2237 // We have reached an recovery point and all frames after it in
2238 // display order are "recovered".
2239 h->frame_recovered |= FRAME_RECOVERED_SEI;
2241 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2244 if (setup_finished && !h->avctx->hwaccel)
2245 ff_thread_finish_setup(h->avctx);
2248 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2249 uint8_t *src_cb, uint8_t *src_cr,
2250 int linesize, int uvlinesize,
2253 uint8_t *top_border;
2255 const int pixel_shift = h->pixel_shift;
2256 int chroma444 = CHROMA444(h);
2257 int chroma422 = CHROMA422(h);
2260 src_cb -= uvlinesize;
2261 src_cr -= uvlinesize;
2263 if (!simple && FRAME_MBAFF(h)) {
2266 top_border = h->top_borders[0][h->mb_x];
2267 AV_COPY128(top_border, src_y + 15 * linesize);
2269 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2270 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2273 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2274 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2275 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2276 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2278 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2279 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2281 } else if (chroma422) {
2283 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2284 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2286 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2287 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2291 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2292 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2294 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2295 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2300 } else if (MB_MBAFF(h)) {
2306 top_border = h->top_borders[top_idx][h->mb_x];
2307 /* There are two lines saved, the line above the top macroblock
2308 * of a pair, and the line above the bottom macroblock. */
2309 AV_COPY128(top_border, src_y + 16 * linesize);
2311 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2313 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2316 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2317 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2318 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2319 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2321 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2322 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2324 } else if (chroma422) {
2326 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2327 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2329 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2330 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2334 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2335 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2337 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2338 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2344 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2345 uint8_t *src_cb, uint8_t *src_cr,
2346 int linesize, int uvlinesize,
2347 int xchg, int chroma444,
2348 int simple, int pixel_shift)
2350 int deblock_topleft;
2353 uint8_t *top_border_m1;
2354 uint8_t *top_border;
2356 if (!simple && FRAME_MBAFF(h)) {
2361 top_idx = MB_MBAFF(h) ? 0 : 1;
2365 if (h->deblocking_filter == 2) {
2366 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2367 deblock_top = h->top_type;
2369 deblock_topleft = (h->mb_x > 0);
2370 deblock_top = (h->mb_y > !!MB_FIELD(h));
2373 src_y -= linesize + 1 + pixel_shift;
2374 src_cb -= uvlinesize + 1 + pixel_shift;
2375 src_cr -= uvlinesize + 1 + pixel_shift;
2377 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2378 top_border = h->top_borders[top_idx][h->mb_x];
2380 #define XCHG(a, b, xchg) \
2381 if (pixel_shift) { \
2383 AV_SWAP64(b + 0, a + 0); \
2384 AV_SWAP64(b + 8, a + 8); \
2394 if (deblock_topleft) {
2395 XCHG(top_border_m1 + (8 << pixel_shift),
2396 src_y - (7 << pixel_shift), 1);
2398 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2399 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2400 if (h->mb_x + 1 < h->mb_width) {
2401 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2402 src_y + (17 << pixel_shift), 1);
2404 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2406 if (deblock_topleft) {
2407 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2408 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2410 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2411 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2412 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2413 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2414 if (h->mb_x + 1 < h->mb_width) {
2415 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2416 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2419 if (deblock_topleft) {
2420 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2421 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2423 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2424 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2430 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2433 if (high_bit_depth) {
2434 return AV_RN32A(((int32_t *)mb) + index);
2436 return AV_RN16A(mb + index);
2439 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2440 int index, int value)
2442 if (high_bit_depth) {
2443 AV_WN32A(((int32_t *)mb) + index, value);
2445 AV_WN16A(mb + index, value);
2448 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2449 int mb_type, int is_h264,
2451 int transform_bypass,
2455 uint8_t *dest_y, int p)
2457 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2458 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2460 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2461 block_offset += 16 * p;
2462 if (IS_INTRA4x4(mb_type)) {
2463 if (IS_8x8DCT(mb_type)) {
2464 if (transform_bypass) {
2466 idct_add = h->h264dsp.h264_add_pixels8_clear;
2468 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2469 idct_add = h->h264dsp.h264_idct8_add;
2471 for (i = 0; i < 16; i += 4) {
2472 uint8_t *const ptr = dest_y + block_offset[i];
2473 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2474 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2475 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2477 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2478 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2479 (h->topright_samples_available << i) & 0x4000, linesize);
2481 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2482 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2484 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2489 if (transform_bypass) {
2491 idct_add = h->h264dsp.h264_add_pixels4_clear;
2493 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2494 idct_add = h->h264dsp.h264_idct_add;
2496 for (i = 0; i < 16; i++) {
2497 uint8_t *const ptr = dest_y + block_offset[i];
2498 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2500 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2501 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2506 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2507 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2508 av_assert2(h->mb_y || linesize <= block_offset[i]);
2509 if (!topright_avail) {
2511 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2512 topright = (uint8_t *)&tr_high;
2514 tr = ptr[3 - linesize] * 0x01010101u;
2515 topright = (uint8_t *)&tr;
2518 topright = ptr + (4 << pixel_shift) - linesize;
2522 h->hpc.pred4x4[dir](ptr, topright, linesize);
2523 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2526 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2527 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2529 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2530 } else if (CONFIG_SVQ3_DECODER)
2531 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2537 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2539 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2540 if (!transform_bypass)
2541 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2543 h->dequant4_coeff[p][qscale][0]);
2545 static const uint8_t dc_mapping[16] = {
2546 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2547 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2548 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2549 10 * 16, 11 * 16, 14 * 16, 15 * 16
2551 for (i = 0; i < 16; i++)
2552 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2553 pixel_shift, dc_mapping[i],
2554 dctcoef_get(h->mb_luma_dc[p],
2558 } else if (CONFIG_SVQ3_DECODER)
2559 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2560 h->mb_luma_dc[p], qscale);
2564 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2565 int is_h264, int simple,
2566 int transform_bypass,
2570 uint8_t *dest_y, int p)
2572 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2574 block_offset += 16 * p;
2575 if (!IS_INTRA4x4(mb_type)) {
2577 if (IS_INTRA16x16(mb_type)) {
2578 if (transform_bypass) {
2579 if (h->sps.profile_idc == 244 &&
2580 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2581 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2582 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2583 h->mb + (p * 256 << pixel_shift),
2586 for (i = 0; i < 16; i++)
2587 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2588 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2589 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2590 h->mb + (i * 16 + p * 256 << pixel_shift),
2594 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2595 h->mb + (p * 256 << pixel_shift),
2597 h->non_zero_count_cache + p * 5 * 8);
2599 } else if (h->cbp & 15) {
2600 if (transform_bypass) {
2601 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2602 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2603 : h->h264dsp.h264_add_pixels4_clear;
2604 for (i = 0; i < 16; i += di)
2605 if (h->non_zero_count_cache[scan8[i + p * 16]])
2606 idct_add(dest_y + block_offset[i],
2607 h->mb + (i * 16 + p * 256 << pixel_shift),
2610 if (IS_8x8DCT(mb_type))
2611 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2612 h->mb + (p * 256 << pixel_shift),
2614 h->non_zero_count_cache + p * 5 * 8);
2616 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2617 h->mb + (p * 256 << pixel_shift),
2619 h->non_zero_count_cache + p * 5 * 8);
2622 } else if (CONFIG_SVQ3_DECODER) {
2623 for (i = 0; i < 16; i++)
2624 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2625 // FIXME benchmark weird rule, & below
2626 uint8_t *const ptr = dest_y + block_offset[i];
2627 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2628 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2636 #include "h264_mb_template.c"
2640 #include "h264_mb_template.c"
2644 #include "h264_mb_template.c"
2646 void ff_h264_hl_decode_mb(H264Context *h)
2648 const int mb_xy = h->mb_xy;
2649 const int mb_type = h->cur_pic.mb_type[mb_xy];
2650 int is_complex = CONFIG_SMALL || h->is_complex ||
2651 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2654 if (is_complex || h->pixel_shift)
2655 hl_decode_mb_444_complex(h);
2657 hl_decode_mb_444_simple_8(h);
2658 } else if (is_complex) {
2659 hl_decode_mb_complex(h);
2660 } else if (h->pixel_shift) {
2661 hl_decode_mb_simple_16(h);
2663 hl_decode_mb_simple_8(h);
2666 int ff_pred_weight_table(H264Context *h)
2669 int luma_def, chroma_def;
2672 h->use_weight_chroma = 0;
2673 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2674 if (h->sps.chroma_format_idc)
2675 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2676 luma_def = 1 << h->luma_log2_weight_denom;
2677 chroma_def = 1 << h->chroma_log2_weight_denom;
2679 for (list = 0; list < 2; list++) {
2680 h->luma_weight_flag[list] = 0;
2681 h->chroma_weight_flag[list] = 0;
2682 for (i = 0; i < h->ref_count[list]; i++) {
2683 int luma_weight_flag, chroma_weight_flag;
2685 luma_weight_flag = get_bits1(&h->gb);
2686 if (luma_weight_flag) {
2687 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2688 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2689 if (h->luma_weight[i][list][0] != luma_def ||
2690 h->luma_weight[i][list][1] != 0) {
2692 h->luma_weight_flag[list] = 1;
2695 h->luma_weight[i][list][0] = luma_def;
2696 h->luma_weight[i][list][1] = 0;
2699 if (h->sps.chroma_format_idc) {
2700 chroma_weight_flag = get_bits1(&h->gb);
2701 if (chroma_weight_flag) {
2703 for (j = 0; j < 2; j++) {
2704 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2705 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2706 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2707 h->chroma_weight[i][list][j][1] != 0) {
2708 h->use_weight_chroma = 1;
2709 h->chroma_weight_flag[list] = 1;
2714 for (j = 0; j < 2; j++) {
2715 h->chroma_weight[i][list][j][0] = chroma_def;
2716 h->chroma_weight[i][list][j][1] = 0;
2721 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2724 h->use_weight = h->use_weight || h->use_weight_chroma;
2729 * Initialize implicit_weight table.
2730 * @param field 0/1 initialize the weight for interlaced MBAFF
2731 * -1 initializes the rest
2733 static void implicit_weight_table(H264Context *h, int field)
2735 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2737 for (i = 0; i < 2; i++) {
2738 h->luma_weight_flag[i] = 0;
2739 h->chroma_weight_flag[i] = 0;
2743 if (h->picture_structure == PICT_FRAME) {
2744 cur_poc = h->cur_pic_ptr->poc;
2746 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2748 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2749 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2751 h->use_weight_chroma = 0;
2755 ref_count0 = h->ref_count[0];
2756 ref_count1 = h->ref_count[1];
2758 cur_poc = h->cur_pic_ptr->field_poc[field];
2760 ref_count0 = 16 + 2 * h->ref_count[0];
2761 ref_count1 = 16 + 2 * h->ref_count[1];
2765 h->use_weight_chroma = 2;
2766 h->luma_log2_weight_denom = 5;
2767 h->chroma_log2_weight_denom = 5;
2769 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2770 int poc0 = h->ref_list[0][ref0].poc;
2771 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2773 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2774 int poc1 = h->ref_list[1][ref1].poc;
2775 int td = av_clip(poc1 - poc0, -128, 127);
2777 int tb = av_clip(cur_poc - poc0, -128, 127);
2778 int tx = (16384 + (FFABS(td) >> 1)) / td;
2779 int dist_scale_factor = (tb * tx + 32) >> 8;
2780 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2781 w = 64 - dist_scale_factor;
2785 h->implicit_weight[ref0][ref1][0] =
2786 h->implicit_weight[ref0][ref1][1] = w;
2788 h->implicit_weight[ref0][ref1][field] = w;
2795 * instantaneous decoder refresh.
2797 static void idr(H264Context *h)
2800 ff_h264_remove_all_refs(h);
2801 h->prev_frame_num = 0;
2802 h->prev_frame_num_offset = 0;
2803 h->prev_poc_msb = 1<<16;
2804 h->prev_poc_lsb = 0;
2805 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2806 h->last_pocs[i] = INT_MIN;
2809 /* forget old pics after a seek */
2810 static void flush_change(H264Context *h)
2814 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2815 h->prev_interlaced_frame = 1;
2818 h->prev_frame_num = -1;
2819 if (h->cur_pic_ptr) {
2820 h->cur_pic_ptr->reference = 0;
2821 for (j=i=0; h->delayed_pic[i]; i++)
2822 if (h->delayed_pic[i] != h->cur_pic_ptr)
2823 h->delayed_pic[j++] = h->delayed_pic[i];
2824 h->delayed_pic[j] = NULL;
2827 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2828 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2829 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2830 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2831 ff_h264_reset_sei(h);
2832 h->recovery_frame = -1;
2833 h->frame_recovered = 0;
2835 h->current_slice = 0;
2839 /* forget old pics after a seek */
2840 static void flush_dpb(AVCodecContext *avctx)
2842 H264Context *h = avctx->priv_data;
2845 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2846 if (h->delayed_pic[i])
2847 h->delayed_pic[i]->reference = 0;
2848 h->delayed_pic[i] = NULL;
2854 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2855 unref_picture(h, &h->DPB[i]);
2856 h->cur_pic_ptr = NULL;
2857 unref_picture(h, &h->cur_pic);
2859 h->mb_x = h->mb_y = 0;
2861 h->parse_context.state = -1;
2862 h->parse_context.frame_start_found = 0;
2863 h->parse_context.overread = 0;
2864 h->parse_context.overread_index = 0;
2865 h->parse_context.index = 0;
2866 h->parse_context.last_index = 0;
2869 h->context_initialized = 0;
2872 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2874 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2877 h->frame_num_offset = h->prev_frame_num_offset;
2878 if (h->frame_num < h->prev_frame_num)
2879 h->frame_num_offset += max_frame_num;
2881 if (h->sps.poc_type == 0) {
2882 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2884 if (h->poc_lsb < h->prev_poc_lsb &&
2885 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2886 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2887 else if (h->poc_lsb > h->prev_poc_lsb &&
2888 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2889 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2891 h->poc_msb = h->prev_poc_msb;
2893 field_poc[1] = h->poc_msb + h->poc_lsb;
2894 if (h->picture_structure == PICT_FRAME)
2895 field_poc[1] += h->delta_poc_bottom;
2896 } else if (h->sps.poc_type == 1) {
2897 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2900 if (h->sps.poc_cycle_length != 0)
2901 abs_frame_num = h->frame_num_offset + h->frame_num;
2905 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2908 expected_delta_per_poc_cycle = 0;
2909 for (i = 0; i < h->sps.poc_cycle_length; i++)
2910 // FIXME integrate during sps parse
2911 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2913 if (abs_frame_num > 0) {
2914 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2915 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2917 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2918 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2919 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2923 if (h->nal_ref_idc == 0)
2924 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2926 field_poc[0] = expectedpoc + h->delta_poc[0];
2927 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2929 if (h->picture_structure == PICT_FRAME)
2930 field_poc[1] += h->delta_poc[1];
2932 int poc = 2 * (h->frame_num_offset + h->frame_num);
2934 if (!h->nal_ref_idc)
2941 if (h->picture_structure != PICT_BOTTOM_FIELD)
2942 pic_field_poc[0] = field_poc[0];
2943 if (h->picture_structure != PICT_TOP_FIELD)
2944 pic_field_poc[1] = field_poc[1];
2945 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2951 * initialize scan tables
2953 static void init_scan_tables(H264Context *h)
2956 for (i = 0; i < 16; i++) {
2957 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2958 h->zigzag_scan[i] = T(zigzag_scan[i]);
2959 h->field_scan[i] = T(field_scan[i]);
2962 for (i = 0; i < 64; i++) {
2963 #define T(x) (x >> 3) | ((x & 7) << 3)
2964 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2965 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2966 h->field_scan8x8[i] = T(field_scan8x8[i]);
2967 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2970 if (h->sps.transform_bypass) { // FIXME same ugly
2971 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2972 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2973 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2974 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2975 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2976 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2978 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2979 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2980 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2981 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2982 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2983 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2987 static int field_end(H264Context *h, int in_setup)
2989 AVCodecContext *const avctx = h->avctx;
2993 if (CONFIG_H264_VDPAU_DECODER &&
2994 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
2995 ff_vdpau_h264_set_reference_frames(h);
2997 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
2998 if (!h->droppable) {
2999 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3000 h->prev_poc_msb = h->poc_msb;
3001 h->prev_poc_lsb = h->poc_lsb;
3003 h->prev_frame_num_offset = h->frame_num_offset;
3004 h->prev_frame_num = h->frame_num;
3005 h->outputed_poc = h->next_outputed_poc;
3008 if (avctx->hwaccel) {
3009 if (avctx->hwaccel->end_frame(avctx) < 0)
3010 av_log(avctx, AV_LOG_ERROR,
3011 "hardware accelerator failed to decode picture\n");
3014 if (CONFIG_H264_VDPAU_DECODER &&
3015 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3016 ff_vdpau_h264_picture_complete(h);
3019 * FIXME: Error handling code does not seem to support interlaced
3020 * when slices span multiple rows
3021 * The ff_er_add_slice calls don't work right for bottom
3022 * fields; they cause massive erroneous error concealing
3023 * Error marking covers both fields (top and bottom).
3024 * This causes a mismatched s->error_count
3025 * and a bad error table. Further, the error count goes to
3026 * INT_MAX when called for bottom field, because mb_y is
3027 * past end by one (callers fault) and resync_mb_y != 0
3028 * causes problems for the first MB line, too.
3030 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
3031 h->er.cur_pic = h->cur_pic_ptr;
3032 ff_er_frame_end(&h->er);
3034 if (!in_setup && !h->droppable)
3035 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3036 h->picture_structure == PICT_BOTTOM_FIELD);
3039 h->current_slice = 0;
3045 * Replicate H264 "master" context to thread contexts.
3047 static int clone_slice(H264Context *dst, H264Context *src)
3049 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
3050 dst->cur_pic_ptr = src->cur_pic_ptr;
3051 dst->cur_pic = src->cur_pic;
3052 dst->linesize = src->linesize;
3053 dst->uvlinesize = src->uvlinesize;
3054 dst->first_field = src->first_field;
3056 dst->prev_poc_msb = src->prev_poc_msb;
3057 dst->prev_poc_lsb = src->prev_poc_lsb;
3058 dst->prev_frame_num_offset = src->prev_frame_num_offset;
3059 dst->prev_frame_num = src->prev_frame_num;
3060 dst->short_ref_count = src->short_ref_count;
3062 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
3063 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
3064 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3066 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
3067 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
3073 * Compute profile from profile_idc and constraint_set?_flags.
3077 * @return profile as defined by FF_PROFILE_H264_*
3079 int ff_h264_get_profile(SPS *sps)
3081 int profile = sps->profile_idc;
3083 switch (sps->profile_idc) {
3084 case FF_PROFILE_H264_BASELINE:
3085 // constraint_set1_flag set to 1
3086 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3088 case FF_PROFILE_H264_HIGH_10:
3089 case FF_PROFILE_H264_HIGH_422:
3090 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3091 // constraint_set3_flag set to 1
3092 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3099 static int h264_set_parameter_from_sps(H264Context *h)
3101 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3102 (h->sps.bitstream_restriction_flag &&
3103 !h->sps.num_reorder_frames)) {
3104 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3105 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3106 "Reenabling low delay requires a codec flush.\n");
3111 if (h->avctx->has_b_frames < 2)
3112 h->avctx->has_b_frames = !h->low_delay;
3114 if (h->sps.bit_depth_luma != h->sps.bit_depth_chroma) {
3115 avpriv_request_sample(h->avctx,
3116 "Different chroma and luma bit depth");
3117 return AVERROR_PATCHWELCOME;
3120 if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3121 h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
3122 if (h->avctx->codec &&
3123 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
3124 (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
3125 av_log(h->avctx, AV_LOG_ERROR,
3126 "VDPAU decoding does not support video colorspace.\n");
3127 return AVERROR_INVALIDDATA;
3129 if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
3130 h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
3131 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
3132 h->cur_chroma_format_idc = h->sps.chroma_format_idc;
3133 h->pixel_shift = h->sps.bit_depth_luma > 8;
3135 ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
3136 h->sps.chroma_format_idc);
3137 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
3138 ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
3139 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
3140 h->sps.chroma_format_idc);
3142 if (CONFIG_ERROR_RESILIENCE)
3143 ff_dsputil_init(&h->dsp, h->avctx);
3144 ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
3146 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
3147 h->sps.bit_depth_luma);
3148 return AVERROR_INVALIDDATA;
3154 static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3156 switch (h->sps.bit_depth_luma) {
3159 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3160 return AV_PIX_FMT_GBRP9;
3162 return AV_PIX_FMT_YUV444P9;
3163 } else if (CHROMA422(h))
3164 return AV_PIX_FMT_YUV422P9;
3166 return AV_PIX_FMT_YUV420P9;
3170 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3171 return AV_PIX_FMT_GBRP10;
3173 return AV_PIX_FMT_YUV444P10;
3174 } else if (CHROMA422(h))
3175 return AV_PIX_FMT_YUV422P10;
3177 return AV_PIX_FMT_YUV420P10;
3181 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3182 return AV_PIX_FMT_GBRP12;
3184 return AV_PIX_FMT_YUV444P12;
3185 } else if (CHROMA422(h))
3186 return AV_PIX_FMT_YUV422P12;
3188 return AV_PIX_FMT_YUV420P12;
3192 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3193 return AV_PIX_FMT_GBRP14;
3195 return AV_PIX_FMT_YUV444P14;
3196 } else if (CHROMA422(h))
3197 return AV_PIX_FMT_YUV422P14;
3199 return AV_PIX_FMT_YUV420P14;
3203 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
3204 av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
3205 return AV_PIX_FMT_GBR24P;
3206 } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
3207 av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
3209 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
3210 : AV_PIX_FMT_YUV444P;
3211 } else if (CHROMA422(h)) {
3212 return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
3213 : AV_PIX_FMT_YUV422P;
3216 const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
3217 h->avctx->codec->pix_fmts :
3218 h->avctx->color_range == AVCOL_RANGE_JPEG ?
3219 h264_hwaccel_pixfmt_list_jpeg_420 :
3220 h264_hwaccel_pixfmt_list_420;
3222 for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
3223 if (fmt[i] == h->avctx->pix_fmt && !force_callback)
3225 return ff_thread_get_format(h->avctx, fmt);
3229 av_log(h->avctx, AV_LOG_ERROR,
3230 "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
3231 return AVERROR_INVALIDDATA;
3235 /* export coded and cropped frame dimensions to AVCodecContext */
3236 static int init_dimensions(H264Context *h)
3238 int width = h->width - (h->sps.crop_right + h->sps.crop_left);
3239 int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
3240 av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
3241 av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
3243 /* handle container cropping */
3245 FFALIGN(h->avctx->width, 16) == h->width &&
3246 FFALIGN(h->avctx->height, 16) == h->height) {
3247 width = h->avctx->width;
3248 height = h->avctx->height;
3251 if (width <= 0 || height <= 0) {
3252 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
3254 if (h->avctx->err_recognition & AV_EF_EXPLODE)
3255 return AVERROR_INVALIDDATA;
3257 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
3258 h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
3265 h->avctx->coded_width = h->width;
3266 h->avctx->coded_height = h->height;
3267 h->avctx->width = width;
3268 h->avctx->height = height;
3273 static int h264_slice_header_init(H264Context *h, int reinit)
3275 int nb_slices = (HAVE_THREADS &&
3276 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
3277 h->avctx->thread_count : 1;
3280 h->avctx->sample_aspect_ratio = h->sps.sar;
3281 av_assert0(h->avctx->sample_aspect_ratio.den);
3282 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
3283 &h->chroma_x_shift, &h->chroma_y_shift);
3285 if (h->sps.timing_info_present_flag) {
3286 int64_t den = h->sps.time_scale;
3287 if (h->x264_build < 44U)
3289 av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
3290 h->sps.num_units_in_tick, den, 1 << 30);
3293 h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
3298 h->prev_interlaced_frame = 1;
3300 init_scan_tables(h);
3301 ret = ff_h264_alloc_tables(h);
3303 av_log(h->avctx, AV_LOG_ERROR,
3304 "Could not allocate memory for h264\n");
3308 if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
3311 max_slices = FFMIN(MAX_THREADS, h->mb_height);
3313 max_slices = MAX_THREADS;
3314 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
3315 " reducing to %d\n", nb_slices, max_slices);
3316 nb_slices = max_slices;
3318 h->slice_context_count = nb_slices;
3320 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
3321 ret = context_init(h);
3323 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3327 for (i = 1; i < h->slice_context_count; i++) {
3329 c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
3331 return AVERROR(ENOMEM);
3332 c->avctx = h->avctx;
3333 if (CONFIG_ERROR_RESILIENCE) {
3337 c->h264dsp = h->h264dsp;
3338 c->h264qpel = h->h264qpel;
3339 c->h264chroma = h->h264chroma;
3342 c->pixel_shift = h->pixel_shift;
3343 c->cur_chroma_format_idc = h->cur_chroma_format_idc;
3344 c->width = h->width;
3345 c->height = h->height;
3346 c->linesize = h->linesize;
3347 c->uvlinesize = h->uvlinesize;
3348 c->chroma_x_shift = h->chroma_x_shift;
3349 c->chroma_y_shift = h->chroma_y_shift;
3350 c->qscale = h->qscale;
3351 c->droppable = h->droppable;
3352 c->data_partitioning = h->data_partitioning;
3353 c->low_delay = h->low_delay;
3354 c->mb_width = h->mb_width;
3355 c->mb_height = h->mb_height;
3356 c->mb_stride = h->mb_stride;
3357 c->mb_num = h->mb_num;
3358 c->flags = h->flags;
3359 c->workaround_bugs = h->workaround_bugs;
3360 c->pict_type = h->pict_type;
3362 init_scan_tables(c);
3363 clone_tables(c, h, i);
3364 c->context_initialized = 1;
3367 for (i = 0; i < h->slice_context_count; i++)
3368 if ((ret = context_init(h->thread_context[i])) < 0) {
3369 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
3374 h->context_initialized = 1;
3379 int ff_set_ref_count(H264Context *h)
3381 int num_ref_idx_active_override_flag;
3383 // set defaults, might be overridden a few lines later
3384 h->ref_count[0] = h->pps.ref_count[0];
3385 h->ref_count[1] = h->pps.ref_count[1];
3387 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3389 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3391 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3392 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3393 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3395 if (num_ref_idx_active_override_flag) {
3396 h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
3397 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3398 h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
3400 // full range is spec-ok in this case, even for frames
3401 h->ref_count[1] = 1;
3404 if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
3405 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]);
3406 h->ref_count[0] = h->ref_count[1] = 0;
3407 return AVERROR_INVALIDDATA;
3410 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3416 h->ref_count[0] = h->ref_count[1] = 0;
3423 * Decode a slice header.
3424 * This will also call ff_MPV_common_init() and frame_start() as needed.
3426 * @param h h264context
3427 * @param h0 h264 master context (differs from 'h' when doing sliced based
3428 * parallel decoding)
3430 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3432 static int decode_slice_header(H264Context *h, H264Context *h0)
3434 unsigned int first_mb_in_slice;
3435 unsigned int pps_id;
3437 unsigned int slice_type, tmp, i, j;
3438 int last_pic_structure, last_pic_droppable;
3440 int needs_reinit = 0;
3441 int field_pic_flag, bottom_field_flag;
3443 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3444 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3446 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3448 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3449 if (h0->current_slice && FIELD_PICTURE(h)) {
3453 h0->current_slice = 0;
3454 if (!h0->first_field) {
3455 if (h->cur_pic_ptr && !h->droppable) {
3456 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3457 h->picture_structure == PICT_BOTTOM_FIELD);
3459 h->cur_pic_ptr = NULL;
3463 slice_type = get_ue_golomb_31(&h->gb);
3464 if (slice_type > 9) {
3465 av_log(h->avctx, AV_LOG_ERROR,
3466 "slice type too large (%d) at %d %d\n",
3467 slice_type, h->mb_x, h->mb_y);
3468 return AVERROR_INVALIDDATA;
3470 if (slice_type > 4) {
3472 h->slice_type_fixed = 1;
3474 h->slice_type_fixed = 0;
3476 slice_type = golomb_to_pict_type[slice_type];
3477 h->slice_type = slice_type;
3478 h->slice_type_nos = slice_type & 3;
3480 // to make a few old functions happy, it's wrong though
3481 h->pict_type = h->slice_type;
3483 pps_id = get_ue_golomb(&h->gb);
3484 if (pps_id >= MAX_PPS_COUNT) {
3485 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3486 return AVERROR_INVALIDDATA;
3488 if (!h0->pps_buffers[pps_id]) {
3489 av_log(h->avctx, AV_LOG_ERROR,
3490 "non-existing PPS %u referenced\n",
3492 return AVERROR_INVALIDDATA;
3494 h->pps = *h0->pps_buffers[pps_id];
3496 if (!h0->sps_buffers[h->pps.sps_id]) {
3497 av_log(h->avctx, AV_LOG_ERROR,
3498 "non-existing SPS %u referenced\n",
3500 return AVERROR_INVALIDDATA;
3503 if (h->pps.sps_id != h->current_sps_id ||
3504 h0->sps_buffers[h->pps.sps_id]->new) {
3505 h0->sps_buffers[h->pps.sps_id]->new = 0;
3507 h->current_sps_id = h->pps.sps_id;
3508 h->sps = *h0->sps_buffers[h->pps.sps_id];
3510 if (h->mb_width != h->sps.mb_width ||
3511 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3512 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3513 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3517 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3518 h->chroma_format_idc != h->sps.chroma_format_idc) {
3519 h->bit_depth_luma = h->sps.bit_depth_luma;
3520 h->chroma_format_idc = h->sps.chroma_format_idc;
3523 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3527 h->avctx->profile = ff_h264_get_profile(&h->sps);
3528 h->avctx->level = h->sps.level_idc;
3529 h->avctx->refs = h->sps.ref_frame_count;
3531 must_reinit = (h->context_initialized &&
3532 ( 16*h->sps.mb_width != h->avctx->coded_width
3533 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3534 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3535 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3536 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
3537 || h->mb_width != h->sps.mb_width
3538 || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
3540 if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3543 h->mb_width = h->sps.mb_width;
3544 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3545 h->mb_num = h->mb_width * h->mb_height;
3546 h->mb_stride = h->mb_width + 1;
3548 h->b_stride = h->mb_width * 4;
3550 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3552 h->width = 16 * h->mb_width;
3553 h->height = 16 * h->mb_height;
3555 ret = init_dimensions(h);
3559 if (h->sps.video_signal_type_present_flag) {
3560 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3562 if (h->sps.colour_description_present_flag) {
3563 if (h->avctx->colorspace != h->sps.colorspace)
3565 h->avctx->color_primaries = h->sps.color_primaries;
3566 h->avctx->color_trc = h->sps.color_trc;
3567 h->avctx->colorspace = h->sps.colorspace;
3571 if (h->context_initialized &&
3572 (h->width != h->avctx->coded_width ||
3573 h->height != h->avctx->coded_height ||
3577 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3578 "slice %d\n", h0->current_slice + 1);
3579 return AVERROR_INVALIDDATA;
3584 if ((ret = get_pixel_format(h, 1)) < 0)
3586 h->avctx->pix_fmt = ret;
3588 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3589 "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
3591 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3592 av_log(h->avctx, AV_LOG_ERROR,
3593 "h264_slice_header_init() failed\n");
3597 if (!h->context_initialized) {
3599 av_log(h->avctx, AV_LOG_ERROR,
3600 "Cannot (re-)initialize context during parallel decoding.\n");
3601 return AVERROR_PATCHWELCOME;
3604 if ((ret = get_pixel_format(h, 1)) < 0)
3606 h->avctx->pix_fmt = ret;
3608 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3609 av_log(h->avctx, AV_LOG_ERROR,
3610 "h264_slice_header_init() failed\n");
3615 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3616 h->dequant_coeff_pps = pps_id;
3617 init_dequant_tables(h);
3620 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3623 h->mb_aff_frame = 0;
3624 last_pic_structure = h0->picture_structure;
3625 last_pic_droppable = h0->droppable;
3626 h->droppable = h->nal_ref_idc == 0;
3627 if (h->sps.frame_mbs_only_flag) {
3628 h->picture_structure = PICT_FRAME;
3630 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3631 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3634 field_pic_flag = get_bits1(&h->gb);
3635 if (field_pic_flag) {
3636 bottom_field_flag = get_bits1(&h->gb);
3637 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3639 h->picture_structure = PICT_FRAME;
3640 h->mb_aff_frame = h->sps.mb_aff;
3643 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3645 if (h0->current_slice != 0) {
3646 if (last_pic_structure != h->picture_structure ||
3647 last_pic_droppable != h->droppable) {
3648 av_log(h->avctx, AV_LOG_ERROR,
3649 "Changing field mode (%d -> %d) between slices is not allowed\n",
3650 last_pic_structure, h->picture_structure);
3651 h->picture_structure = last_pic_structure;
3652 h->droppable = last_pic_droppable;
3653 return AVERROR_INVALIDDATA;
3654 } else if (!h0->cur_pic_ptr) {
3655 av_log(h->avctx, AV_LOG_ERROR,
3656 "unset cur_pic_ptr on %d. slice\n",
3657 h0->current_slice + 1);
3658 return AVERROR_INVALIDDATA;
3661 /* Shorten frame num gaps so we don't have to allocate reference
3662 * frames just to throw them away */
3663 if (h->frame_num != h->prev_frame_num) {
3664 int unwrap_prev_frame_num = h->prev_frame_num;
3665 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3667 if (unwrap_prev_frame_num > h->frame_num)
3668 unwrap_prev_frame_num -= max_frame_num;
3670 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3671 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3672 if (unwrap_prev_frame_num < 0)
3673 unwrap_prev_frame_num += max_frame_num;
3675 h->prev_frame_num = unwrap_prev_frame_num;
3679 /* See if we have a decoded first field looking for a pair...
3680 * Here, we're using that to see if we should mark previously
3681 * decode frames as "finished".
3682 * We have to do that before the "dummy" in-between frame allocation,
3683 * since that can modify h->cur_pic_ptr. */
3684 if (h0->first_field) {
3685 assert(h0->cur_pic_ptr);
3686 assert(h0->cur_pic_ptr->f.buf[0]);
3687 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3689 /* Mark old field/frame as completed */
3690 if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
3691 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3692 last_pic_structure == PICT_BOTTOM_FIELD);
3695 /* figure out if we have a complementary field pair */
3696 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3697 /* Previous field is unmatched. Don't display it, but let it
3698 * remain for reference if marked as such. */
3699 if (last_pic_structure != PICT_FRAME) {
3700 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3701 last_pic_structure == PICT_TOP_FIELD);
3704 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3705 /* This and previous field were reference, but had
3706 * different frame_nums. Consider this field first in
3707 * pair. Throw away previous field except for reference
3709 if (last_pic_structure != PICT_FRAME) {
3710 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3711 last_pic_structure == PICT_TOP_FIELD);
3714 /* Second field in complementary pair */
3715 if (!((last_pic_structure == PICT_TOP_FIELD &&
3716 h->picture_structure == PICT_BOTTOM_FIELD) ||
3717 (last_pic_structure == PICT_BOTTOM_FIELD &&
3718 h->picture_structure == PICT_TOP_FIELD))) {
3719 av_log(h->avctx, AV_LOG_ERROR,
3720 "Invalid field mode combination %d/%d\n",
3721 last_pic_structure, h->picture_structure);
3722 h->picture_structure = last_pic_structure;
3723 h->droppable = last_pic_droppable;
3724 return AVERROR_INVALIDDATA;
3725 } else if (last_pic_droppable != h->droppable) {
3726 avpriv_request_sample(h->avctx,
3727 "Found reference and non-reference fields in the same frame, which");
3728 h->picture_structure = last_pic_structure;
3729 h->droppable = last_pic_droppable;
3730 return AVERROR_PATCHWELCOME;
3736 while (h->frame_num != h->prev_frame_num && !h0->first_field &&
3737 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3738 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3739 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3740 h->frame_num, h->prev_frame_num);
3741 if (!h->sps.gaps_in_frame_num_allowed_flag)
3742 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3743 h->last_pocs[i] = INT_MIN;
3744 ret = h264_frame_start(h);
3747 h->prev_frame_num++;
3748 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3749 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3750 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3751 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3752 ret = ff_generate_sliding_window_mmcos(h, 1);
3753 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3755 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3756 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3758 /* Error concealment: If a ref is missing, copy the previous ref
3760 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3761 * many assumptions about there being no actual duplicates.
3762 * FIXME: This does not copy padding for out-of-frame motion
3763 * vectors. Given we are concealing a lost frame, this probably
3764 * is not noticeable by comparison, but it should be fixed. */
3765 if (h->short_ref_count) {
3767 av_image_copy(h->short_ref[0]->f.data,
3768 h->short_ref[0]->f.linesize,
3769 (const uint8_t **)prev->f.data,
3774 h->short_ref[0]->poc = prev->poc + 2;
3776 h->short_ref[0]->frame_num = h->prev_frame_num;
3780 /* See if we have a decoded first field looking for a pair...
3781 * We're using that to see whether to continue decoding in that
3782 * frame, or to allocate a new one. */
3783 if (h0->first_field) {
3784 assert(h0->cur_pic_ptr);
3785 assert(h0->cur_pic_ptr->f.buf[0]);
3786 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3788 /* figure out if we have a complementary field pair */
3789 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3790 /* Previous field is unmatched. Don't display it, but let it
3791 * remain for reference if marked as such. */
3792 h0->cur_pic_ptr = NULL;
3793 h0->first_field = FIELD_PICTURE(h);
3795 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3796 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3797 h0->picture_structure==PICT_BOTTOM_FIELD);
3798 /* This and the previous field had different frame_nums.
3799 * Consider this field first in pair. Throw away previous
3800 * one except for reference purposes. */
3801 h0->first_field = 1;
3802 h0->cur_pic_ptr = NULL;
3804 /* Second field in complementary pair */
3805 h0->first_field = 0;
3809 /* Frame or first field in a potentially complementary pair */
3810 h0->first_field = FIELD_PICTURE(h);
3813 if (!FIELD_PICTURE(h) || h0->first_field) {
3814 if (h264_frame_start(h) < 0) {
3815 h0->first_field = 0;
3816 return AVERROR_INVALIDDATA;
3819 release_unused_pictures(h, 0);
3821 /* Some macroblocks can be accessed before they're available in case
3822 * of lost slices, MBAFF or threading. */
3823 if (FIELD_PICTURE(h)) {
3824 for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
3825 memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
3827 memset(h->slice_table, -1,
3828 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
3830 h0->last_slice_type = -1;
3832 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3835 /* can't be in alloc_tables because linesize isn't known there.
3836 * FIXME: redo bipred weight to not require extra buffer? */
3837 for (i = 0; i < h->slice_context_count; i++)
3838 if (h->thread_context[i]) {
3839 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
3844 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3846 av_assert1(h->mb_num == h->mb_width * h->mb_height);
3847 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3848 first_mb_in_slice >= h->mb_num) {
3849 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3850 return AVERROR_INVALIDDATA;
3852 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3853 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3854 FIELD_OR_MBAFF_PICTURE(h);
3855 if (h->picture_structure == PICT_BOTTOM_FIELD)
3856 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3857 av_assert1(h->mb_y < h->mb_height);
3859 if (h->picture_structure == PICT_FRAME) {
3860 h->curr_pic_num = h->frame_num;
3861 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3863 h->curr_pic_num = 2 * h->frame_num + 1;
3864 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3867 if (h->nal_unit_type == NAL_IDR_SLICE)
3868 get_ue_golomb(&h->gb); /* idr_pic_id */
3870 if (h->sps.poc_type == 0) {
3871 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3873 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3874 h->delta_poc_bottom = get_se_golomb(&h->gb);
3877 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3878 h->delta_poc[0] = get_se_golomb(&h->gb);
3880 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3881 h->delta_poc[1] = get_se_golomb(&h->gb);
3884 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3886 if (h->pps.redundant_pic_cnt_present)
3887 h->redundant_pic_count = get_ue_golomb(&h->gb);
3889 ret = ff_set_ref_count(h);
3893 if (slice_type != AV_PICTURE_TYPE_I &&
3894 (h0->current_slice == 0 ||
3895 slice_type != h0->last_slice_type ||
3896 memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3898 ff_h264_fill_default_ref_list(h);
3901 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3902 ret = ff_h264_decode_ref_pic_list_reordering(h);
3904 h->ref_count[1] = h->ref_count[0] = 0;
3909 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3910 (h->pps.weighted_bipred_idc == 1 &&
3911 h->slice_type_nos == AV_PICTURE_TYPE_B))
3912 ff_pred_weight_table(h);
3913 else if (h->pps.weighted_bipred_idc == 2 &&
3914 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3915 implicit_weight_table(h, -1);
3918 for (i = 0; i < 2; i++) {
3919 h->luma_weight_flag[i] = 0;
3920 h->chroma_weight_flag[i] = 0;
3924 // If frame-mt is enabled, only update mmco tables for the first slice
3925 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3926 // or h->mmco, which will cause ref list mix-ups and decoding errors
3927 // further down the line. This may break decoding if the first slice is
3928 // corrupt, thus we only do this if frame-mt is enabled.
3929 if (h->nal_ref_idc) {
3930 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3931 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3932 h0->current_slice == 0);
3933 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3934 return AVERROR_INVALIDDATA;
3937 if (FRAME_MBAFF(h)) {
3938 ff_h264_fill_mbaff_ref_list(h);
3940 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3941 implicit_weight_table(h, 0);
3942 implicit_weight_table(h, 1);
3946 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3947 ff_h264_direct_dist_scale_factor(h);
3948 ff_h264_direct_ref_list_init(h);
3950 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3951 tmp = get_ue_golomb_31(&h->gb);
3953 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3954 return AVERROR_INVALIDDATA;
3956 h->cabac_init_idc = tmp;
3959 h->last_qscale_diff = 0;
3960 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3961 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3962 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3963 return AVERROR_INVALIDDATA;
3966 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3967 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3968 // FIXME qscale / qp ... stuff
3969 if (h->slice_type == AV_PICTURE_TYPE_SP)
3970 get_bits1(&h->gb); /* sp_for_switch_flag */
3971 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3972 h->slice_type == AV_PICTURE_TYPE_SI)
3973 get_se_golomb(&h->gb); /* slice_qs_delta */
3975 h->deblocking_filter = 1;
3976 h->slice_alpha_c0_offset = 52;
3977 h->slice_beta_offset = 52;
3978 if (h->pps.deblocking_filter_parameters_present) {
3979 tmp = get_ue_golomb_31(&h->gb);
3981 av_log(h->avctx, AV_LOG_ERROR,
3982 "deblocking_filter_idc %u out of range\n", tmp);
3983 return AVERROR_INVALIDDATA;
3985 h->deblocking_filter = tmp;
3986 if (h->deblocking_filter < 2)
3987 h->deblocking_filter ^= 1; // 1<->0
3989 if (h->deblocking_filter) {
3990 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
3991 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
3992 if (h->slice_alpha_c0_offset > 104U ||
3993 h->slice_beta_offset > 104U) {
3994 av_log(h->avctx, AV_LOG_ERROR,
3995 "deblocking filter parameters %d %d out of range\n",
3996 h->slice_alpha_c0_offset, h->slice_beta_offset);
3997 return AVERROR_INVALIDDATA;
4002 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
4003 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
4004 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
4005 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
4006 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
4007 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
4008 h->nal_ref_idc == 0))
4009 h->deblocking_filter = 0;
4011 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
4012 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
4013 /* Cheat slightly for speed:
4014 * Do not bother to deblock across slices. */
4015 h->deblocking_filter = 2;
4017 h0->max_contexts = 1;
4018 if (!h0->single_decode_warning) {
4019 av_log(h->avctx, AV_LOG_INFO,
4020 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
4021 h0->single_decode_warning = 1;
4024 av_log(h->avctx, AV_LOG_ERROR,
4025 "Deblocking switched inside frame.\n");
4030 h->qp_thresh = 15 + 52 -
4031 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
4033 h->pps.chroma_qp_index_offset[0],
4034 h->pps.chroma_qp_index_offset[1]) +
4035 6 * (h->sps.bit_depth_luma - 8);
4037 h0->last_slice_type = slice_type;
4038 memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
4039 h->slice_num = ++h0->current_slice;
4042 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
4043 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
4044 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
4045 && h->slice_num >= MAX_SLICES) {
4046 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
4047 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);
4050 for (j = 0; j < 2; j++) {
4052 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
4053 for (i = 0; i < 16; i++) {
4055 if (j < h->list_count && i < h->ref_count[j] &&
4056 h->ref_list[j][i].f.buf[0]) {
4058 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
4059 for (k = 0; k < h->short_ref_count; k++)
4060 if (h->short_ref[k]->f.buf[0]->buffer == buf) {
4064 for (k = 0; k < h->long_ref_count; k++)
4065 if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
4066 id_list[i] = h->short_ref_count + k;
4074 for (i = 0; i < 16; i++)
4075 ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
4077 ref2frm[18 + 1] = -1;
4078 for (i = 16; i < 48; i++)
4079 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
4080 (h->ref_list[j][i].reference & 3);
4083 if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
4084 if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
4085 h->er.ref_count = h->ref_count[0];
4087 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
4088 av_log(h->avctx, AV_LOG_DEBUG,
4089 "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",
4091 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
4093 av_get_picture_type_char(h->slice_type),
4094 h->slice_type_fixed ? " fix" : "",
4095 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
4096 pps_id, h->frame_num,
4097 h->cur_pic_ptr->field_poc[0],
4098 h->cur_pic_ptr->field_poc[1],
4099 h->ref_count[0], h->ref_count[1],
4101 h->deblocking_filter,
4102 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
4104 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
4105 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
4111 int ff_h264_get_slice_type(const H264Context *h)
4113 switch (h->slice_type) {
4114 case AV_PICTURE_TYPE_P:
4116 case AV_PICTURE_TYPE_B:
4118 case AV_PICTURE_TYPE_I:
4120 case AV_PICTURE_TYPE_SP:
4122 case AV_PICTURE_TYPE_SI:
4125 return AVERROR_INVALIDDATA;
4129 static av_always_inline void fill_filter_caches_inter(H264Context *h,
4130 int mb_type, int top_xy,
4131 int left_xy[LEFT_MBS],
4133 int left_type[LEFT_MBS],
4134 int mb_xy, int list)
4136 int b_stride = h->b_stride;
4137 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4138 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4139 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4140 if (USES_LIST(top_type, list)) {
4141 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
4142 const int b8_xy = 4 * top_xy + 2;
4143 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4144 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4145 ref_cache[0 - 1 * 8] =
4146 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4147 ref_cache[2 - 1 * 8] =
4148 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4150 AV_ZERO128(mv_dst - 1 * 8);
4151 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4154 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4155 if (USES_LIST(left_type[LTOP], list)) {
4156 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
4157 const int b8_xy = 4 * left_xy[LTOP] + 1;
4158 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4159 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4160 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4161 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4162 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4164 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4165 ref_cache[-1 + 16] =
4166 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4168 AV_ZERO32(mv_dst - 1 + 0);
4169 AV_ZERO32(mv_dst - 1 + 8);
4170 AV_ZERO32(mv_dst - 1 + 16);
4171 AV_ZERO32(mv_dst - 1 + 24);
4174 ref_cache[-1 + 16] =
4175 ref_cache[-1 + 24] = LIST_NOT_USED;
4180 if (!USES_LIST(mb_type, list)) {
4181 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4182 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4183 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4184 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4185 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4190 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4191 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4192 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4193 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4194 AV_WN32A(&ref_cache[0 * 8], ref01);
4195 AV_WN32A(&ref_cache[1 * 8], ref01);
4196 AV_WN32A(&ref_cache[2 * 8], ref23);
4197 AV_WN32A(&ref_cache[3 * 8], ref23);
4201 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4202 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4203 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4204 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4205 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4211 * @return non zero if the loop filter can be skipped
4213 static int fill_filter_caches(H264Context *h, int mb_type)
4215 const int mb_xy = h->mb_xy;
4216 int top_xy, left_xy[LEFT_MBS];
4217 int top_type, left_type[LEFT_MBS];
4221 top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4223 /* Wow, what a mess, why didn't they simplify the interlacing & intra
4224 * stuff, I can't imagine that these complex rules are worth it. */
4226 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4227 if (FRAME_MBAFF(h)) {
4228 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4229 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4231 if (left_mb_field_flag != curr_mb_field_flag)
4232 left_xy[LTOP] -= h->mb_stride;
4234 if (curr_mb_field_flag)
4235 top_xy += h->mb_stride &
4236 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4237 if (left_mb_field_flag != curr_mb_field_flag)
4238 left_xy[LBOT] += h->mb_stride;
4242 h->top_mb_xy = top_xy;
4243 h->left_mb_xy[LTOP] = left_xy[LTOP];
4244 h->left_mb_xy[LBOT] = left_xy[LBOT];
4246 /* For sufficiently low qp, filtering wouldn't do anything.
4247 * This is a conservative estimate: could also check beta_offset
4248 * and more accurate chroma_qp. */
4249 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4250 int qp = h->cur_pic.qscale_table[mb_xy];
4251 if (qp <= qp_thresh &&
4252 (left_xy[LTOP] < 0 ||
4253 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4255 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4256 if (!FRAME_MBAFF(h))
4258 if ((left_xy[LTOP] < 0 ||
4259 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4260 (top_xy < h->mb_stride ||
4261 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4266 top_type = h->cur_pic.mb_type[top_xy];
4267 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4268 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4269 if (h->deblocking_filter == 2) {
4270 if (h->slice_table[top_xy] != h->slice_num)
4272 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4273 left_type[LTOP] = left_type[LBOT] = 0;
4275 if (h->slice_table[top_xy] == 0xFFFF)
4277 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4278 left_type[LTOP] = left_type[LBOT] = 0;
4280 h->top_type = top_type;
4281 h->left_type[LTOP] = left_type[LTOP];
4282 h->left_type[LBOT] = left_type[LBOT];
4284 if (IS_INTRA(mb_type))
4287 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4288 top_type, left_type, mb_xy, 0);
4289 if (h->list_count == 2)
4290 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4291 top_type, left_type, mb_xy, 1);
4293 nnz = h->non_zero_count[mb_xy];
4294 nnz_cache = h->non_zero_count_cache;
4295 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4296 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4297 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4298 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4299 h->cbp = h->cbp_table[mb_xy];
4302 nnz = h->non_zero_count[top_xy];
4303 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4306 if (left_type[LTOP]) {
4307 nnz = h->non_zero_count[left_xy[LTOP]];
4308 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4309 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4310 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4311 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4314 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4315 * from what the loop filter needs */
4316 if (!CABAC(h) && h->pps.transform_8x8_mode) {
4317 if (IS_8x8DCT(top_type)) {
4318 nnz_cache[4 + 8 * 0] =
4319 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4320 nnz_cache[6 + 8 * 0] =
4321 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4323 if (IS_8x8DCT(left_type[LTOP])) {
4324 nnz_cache[3 + 8 * 1] =
4325 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4327 if (IS_8x8DCT(left_type[LBOT])) {
4328 nnz_cache[3 + 8 * 3] =
4329 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4332 if (IS_8x8DCT(mb_type)) {
4333 nnz_cache[scan8[0]] =
4334 nnz_cache[scan8[1]] =
4335 nnz_cache[scan8[2]] =
4336 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4338 nnz_cache[scan8[0 + 4]] =
4339 nnz_cache[scan8[1 + 4]] =
4340 nnz_cache[scan8[2 + 4]] =
4341 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4343 nnz_cache[scan8[0 + 8]] =
4344 nnz_cache[scan8[1 + 8]] =
4345 nnz_cache[scan8[2 + 8]] =
4346 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4348 nnz_cache[scan8[0 + 12]] =
4349 nnz_cache[scan8[1 + 12]] =
4350 nnz_cache[scan8[2 + 12]] =
4351 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4358 static void loop_filter(H264Context *h, int start_x, int end_x)
4360 uint8_t *dest_y, *dest_cb, *dest_cr;
4361 int linesize, uvlinesize, mb_x, mb_y;
4362 const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4363 const int old_slice_type = h->slice_type;
4364 const int pixel_shift = h->pixel_shift;
4365 const int block_h = 16 >> h->chroma_y_shift;
4367 if (h->deblocking_filter) {
4368 for (mb_x = start_x; mb_x < end_x; mb_x++)
4369 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4371 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4372 h->slice_num = h->slice_table[mb_xy];
4373 mb_type = h->cur_pic.mb_type[mb_xy];
4374 h->list_count = h->list_counts[mb_xy];
4378 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4382 dest_y = h->cur_pic.f.data[0] +
4383 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4384 dest_cb = h->cur_pic.f.data[1] +
4385 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4386 mb_y * h->uvlinesize * block_h;
4387 dest_cr = h->cur_pic.f.data[2] +
4388 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4389 mb_y * h->uvlinesize * block_h;
4390 // FIXME simplify above
4393 linesize = h->mb_linesize = h->linesize * 2;
4394 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4395 if (mb_y & 1) { // FIXME move out of this function?
4396 dest_y -= h->linesize * 15;
4397 dest_cb -= h->uvlinesize * (block_h - 1);
4398 dest_cr -= h->uvlinesize * (block_h - 1);
4401 linesize = h->mb_linesize = h->linesize;
4402 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4404 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4406 if (fill_filter_caches(h, mb_type))
4408 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4409 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4411 if (FRAME_MBAFF(h)) {
4412 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4413 linesize, uvlinesize);
4415 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4416 dest_cr, linesize, uvlinesize);
4420 h->slice_type = old_slice_type;
4422 h->mb_y = end_mb_y - FRAME_MBAFF(h);
4423 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4424 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4427 static void predict_field_decoding_flag(H264Context *h)
4429 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4430 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4431 h->cur_pic.mb_type[mb_xy - 1] :
4432 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4433 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4434 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4438 * Draw edges and report progress for the last MB row.
4440 static void decode_finish_row(H264Context *h)
4442 int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4443 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4444 int height = 16 << FRAME_MBAFF(h);
4445 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4447 if (h->deblocking_filter) {
4448 if ((top + height) >= pic_height)
4449 height += deblock_border;
4450 top -= deblock_border;
4453 if (top >= pic_height || (top + height) < 0)
4456 height = FFMIN(height, pic_height - top);
4458 height = top + height;
4462 ff_h264_draw_horiz_band(h, top, height);
4464 if (h->droppable || h->er.error_occurred)
4467 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4468 h->picture_structure == PICT_BOTTOM_FIELD);
4471 static void er_add_slice(H264Context *h, int startx, int starty,
4472 int endx, int endy, int status)
4474 if (CONFIG_ERROR_RESILIENCE) {
4475 ERContext *er = &h->er;
4477 ff_er_add_slice(er, startx, starty, endx, endy, status);
4481 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4483 H264Context *h = *(void **)arg;
4484 int lf_x_start = h->mb_x;
4486 h->mb_skip_run = -1;
4488 av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4490 h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4491 avctx->codec_id != AV_CODEC_ID_H264 ||
4492 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4494 if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
4495 const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
4497 int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
4498 prev_status &= ~ VP_START;
4499 if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
4500 h->er.error_occurred = 1;
4506 align_get_bits(&h->gb);
4509 ff_init_cabac_decoder(&h->cabac,
4510 h->gb.buffer + get_bits_count(&h->gb) / 8,
4511 (get_bits_left(&h->gb) + 7) / 8);
4513 ff_h264_init_cabac_states(h);
4517 int ret = ff_h264_decode_mb_cabac(h);
4519 // STOP_TIMER("decode_mb_cabac")
4522 ff_h264_hl_decode_mb(h);
4524 // FIXME optimal? or let mb_decode decode 16x32 ?
4525 if (ret >= 0 && FRAME_MBAFF(h)) {
4528 ret = ff_h264_decode_mb_cabac(h);
4531 ff_h264_hl_decode_mb(h);
4534 eos = get_cabac_terminate(&h->cabac);
4536 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4537 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4538 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4539 h->mb_y, ER_MB_END);
4540 if (h->mb_x >= lf_x_start)
4541 loop_filter(h, lf_x_start, h->mb_x + 1);
4544 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4545 av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4546 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4547 av_log(h->avctx, AV_LOG_ERROR,
4548 "error while decoding MB %d %d, bytestream (%td)\n",
4550 h->cabac.bytestream_end - h->cabac.bytestream);
4551 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4552 h->mb_y, ER_MB_ERROR);
4553 return AVERROR_INVALIDDATA;
4556 if (++h->mb_x >= h->mb_width) {
4557 loop_filter(h, lf_x_start, h->mb_x);
4558 h->mb_x = lf_x_start = 0;
4559 decode_finish_row(h);
4561 if (FIELD_OR_MBAFF_PICTURE(h)) {
4563 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4564 predict_field_decoding_flag(h);
4568 if (eos || h->mb_y >= h->mb_height) {
4569 tprintf(h->avctx, "slice end %d %d\n",
4570 get_bits_count(&h->gb), h->gb.size_in_bits);
4571 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4572 h->mb_y, ER_MB_END);
4573 if (h->mb_x > lf_x_start)
4574 loop_filter(h, lf_x_start, h->mb_x);
4580 int ret = ff_h264_decode_mb_cavlc(h);
4583 ff_h264_hl_decode_mb(h);
4585 // FIXME optimal? or let mb_decode decode 16x32 ?
4586 if (ret >= 0 && FRAME_MBAFF(h)) {
4588 ret = ff_h264_decode_mb_cavlc(h);
4591 ff_h264_hl_decode_mb(h);
4596 av_log(h->avctx, AV_LOG_ERROR,
4597 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4598 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4599 h->mb_y, ER_MB_ERROR);
4603 if (++h->mb_x >= h->mb_width) {
4604 loop_filter(h, lf_x_start, h->mb_x);
4605 h->mb_x = lf_x_start = 0;
4606 decode_finish_row(h);
4608 if (FIELD_OR_MBAFF_PICTURE(h)) {
4610 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4611 predict_field_decoding_flag(h);
4613 if (h->mb_y >= h->mb_height) {
4614 tprintf(h->avctx, "slice end %d %d\n",
4615 get_bits_count(&h->gb), h->gb.size_in_bits);
4617 if ( get_bits_left(&h->gb) == 0
4618 || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4619 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4620 h->mb_x - 1, h->mb_y,
4625 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4629 return AVERROR_INVALIDDATA;
4634 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4635 tprintf(h->avctx, "slice end %d %d\n",
4636 get_bits_count(&h->gb), h->gb.size_in_bits);
4638 if (get_bits_left(&h->gb) == 0) {
4639 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4640 h->mb_x - 1, h->mb_y,
4642 if (h->mb_x > lf_x_start)
4643 loop_filter(h, lf_x_start, h->mb_x);
4647 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4648 h->mb_y, ER_MB_ERROR);
4650 return AVERROR_INVALIDDATA;
4658 * Call decode_slice() for each context.
4660 * @param h h264 master context
4661 * @param context_count number of contexts to execute
4663 static int execute_decode_slices(H264Context *h, int context_count)
4665 AVCodecContext *const avctx = h->avctx;
4669 if (h->avctx->hwaccel ||
4670 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4672 if (context_count == 1) {
4673 return decode_slice(avctx, &h);
4675 av_assert0(context_count > 0);
4676 for (i = 1; i < context_count; i++) {
4677 hx = h->thread_context[i];
4678 if (CONFIG_ERROR_RESILIENCE) {
4679 hx->er.error_count = 0;
4681 hx->x264_build = h->x264_build;
4684 avctx->execute(avctx, decode_slice, h->thread_context,
4685 NULL, context_count, sizeof(void *));
4687 /* pull back stuff from slices to master context */
4688 hx = h->thread_context[context_count - 1];
4691 h->droppable = hx->droppable;
4692 h->picture_structure = hx->picture_structure;
4693 if (CONFIG_ERROR_RESILIENCE) {
4694 for (i = 1; i < context_count; i++)
4695 h->er.error_count += h->thread_context[i]->er.error_count;
4702 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
4704 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4705 int parse_extradata)
4707 AVCodecContext *const avctx = h->avctx;
4708 H264Context *hx; ///< thread context
4712 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4713 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4716 int first_slice = 0;
4719 h->nal_unit_type= 0;
4721 if(!h->slice_context_count)
4722 h->slice_context_count= 1;
4723 h->max_contexts = h->slice_context_count;
4724 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4725 h->current_slice = 0;
4726 if (!h->first_field)
4727 h->cur_pic_ptr = NULL;
4728 ff_h264_reset_sei(h);
4731 if (h->nal_length_size == 4) {
4732 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4734 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4738 for (; pass <= 1; pass++) {
4741 next_avc = h->is_avc ? 0 : buf_size;
4751 if (buf_index >= next_avc) {
4752 if (buf_index >= buf_size - h->nal_length_size)
4755 for (i = 0; i < h->nal_length_size; i++)
4756 nalsize = (nalsize << 8) | buf[buf_index++];
4757 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4758 av_log(h->avctx, AV_LOG_ERROR,
4759 "AVC: nal size %d\n", nalsize);
4762 next_avc = buf_index + nalsize;
4764 // start code prefix search
4765 for (; buf_index + 3 < next_avc; buf_index++)
4766 // This should always succeed in the first iteration.
4767 if (buf[buf_index] == 0 &&
4768 buf[buf_index + 1] == 0 &&
4769 buf[buf_index + 2] == 1)
4772 if (buf_index + 3 >= buf_size) {
4773 buf_index = buf_size;
4778 if (buf_index >= next_avc)
4782 hx = h->thread_context[context_count];
4784 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4785 &consumed, next_avc - buf_index);
4786 if (ptr == NULL || dst_length < 0) {
4790 i = buf_index + consumed;
4791 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4792 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4793 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4794 h->workaround_bugs |= FF_BUG_TRUNCATED;
4796 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4797 while (dst_length > 0 && ptr[dst_length - 1] == 0)
4799 bit_length = !dst_length ? 0
4801 decode_rbsp_trailing(h, ptr + dst_length - 1));
4803 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4804 av_log(h->avctx, AV_LOG_DEBUG,
4805 "NAL %d/%d at %d/%d length %d pass %d\n",
4806 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
4808 if (h->is_avc && (nalsize != consumed) && nalsize)
4809 av_log(h->avctx, AV_LOG_DEBUG,
4810 "AVC: Consumed only %d bytes instead of %d\n",
4813 buf_index += consumed;
4817 /* packets can sometimes contain multiple PPS/SPS,
4818 * e.g. two PAFF field pictures in one packet, or a demuxer
4819 * which splits NALs strangely if so, when frame threading we
4820 * can't start the next thread until we've read all of them */
4821 switch (hx->nal_unit_type) {
4824 nals_needed = nal_index;
4829 init_get_bits(&hx->gb, ptr, bit_length);
4830 if (!get_ue_golomb(&hx->gb) || !first_slice)
4831 nals_needed = nal_index;
4833 first_slice = hx->nal_unit_type;
4839 switch (hx->nal_unit_type) {
4843 first_slice = hx->nal_unit_type;
4846 if (avctx->skip_frame >= AVDISCARD_NONREF &&
4847 h->nal_ref_idc == 0 &&
4848 h->nal_unit_type != NAL_SEI)
4852 /* Ignore per frame NAL unit type during extradata
4853 * parsing. Decoding slices is not possible in codec init
4855 if (parse_extradata) {
4856 switch (hx->nal_unit_type) {
4862 av_log(h->avctx, AV_LOG_WARNING,
4863 "Ignoring NAL %d in global header/extradata\n",
4865 // fall through to next case
4866 case NAL_AUXILIARY_SLICE:
4867 hx->nal_unit_type = NAL_FF_IGNORE;
4873 switch (hx->nal_unit_type) {
4875 if (first_slice != NAL_IDR_SLICE) {
4876 av_log(h->avctx, AV_LOG_ERROR,
4877 "Invalid mix of idr and non-idr slices\n");
4882 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4885 init_get_bits(&hx->gb, ptr, bit_length);
4887 hx->inter_gb_ptr = &hx->gb;
4888 hx->data_partitioning = 0;
4890 if ((err = decode_slice_header(hx, h)))
4893 if (h->sei_recovery_frame_cnt >= 0) {
4894 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
4895 h->valid_recovery_point = 1;
4897 if ( h->recovery_frame < 0
4898 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
4899 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4900 ((1 << h->sps.log2_max_frame_num) - 1);
4902 if (!h->valid_recovery_point)
4903 h->recovery_frame = h->frame_num;
4907 h->cur_pic_ptr->f.key_frame |=
4908 (hx->nal_unit_type == NAL_IDR_SLICE);
4910 if (hx->nal_unit_type == NAL_IDR_SLICE ||
4911 h->recovery_frame == h->frame_num) {
4912 h->recovery_frame = -1;
4913 h->cur_pic_ptr->recovered = 1;
4915 // If we have an IDR, all frames after it in decoded order are
4917 if (hx->nal_unit_type == NAL_IDR_SLICE)
4918 h->frame_recovered |= FRAME_RECOVERED_IDR;
4919 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
4920 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
4922 h->cur_pic_ptr->recovered |= h->frame_recovered;
4924 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
4927 if (h->current_slice == 1) {
4928 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4929 decode_postinit(h, nal_index >= nals_needed);
4931 if (h->avctx->hwaccel &&
4932 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4934 if (CONFIG_H264_VDPAU_DECODER &&
4935 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4936 ff_vdpau_h264_picture_start(h);
4939 if (hx->redundant_pic_count == 0 &&
4940 (avctx->skip_frame < AVDISCARD_NONREF ||
4942 (avctx->skip_frame < AVDISCARD_BIDIR ||
4943 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4944 (avctx->skip_frame < AVDISCARD_NONKEY ||
4945 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4946 avctx->skip_frame < AVDISCARD_ALL) {
4947 if (avctx->hwaccel) {
4948 ret = avctx->hwaccel->decode_slice(avctx,
4949 &buf[buf_index - consumed],
4953 } else if (CONFIG_H264_VDPAU_DECODER &&
4954 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4955 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4957 sizeof(start_code));
4958 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4959 &buf[buf_index - consumed],
4966 init_get_bits(&hx->gb, ptr, bit_length);
4968 hx->inter_gb_ptr = NULL;
4970 if ((err = decode_slice_header(hx, h)) < 0)
4973 hx->data_partitioning = 1;
4976 init_get_bits(&hx->intra_gb, ptr, bit_length);
4977 hx->intra_gb_ptr = &hx->intra_gb;
4980 init_get_bits(&hx->inter_gb, ptr, bit_length);
4981 hx->inter_gb_ptr = &hx->inter_gb;
4983 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
4986 if (hx->redundant_pic_count == 0 &&
4988 hx->data_partitioning &&
4989 h->cur_pic_ptr && h->context_initialized &&
4990 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
4991 (avctx->skip_frame < AVDISCARD_BIDIR ||
4992 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4993 (avctx->skip_frame < AVDISCARD_NONKEY ||
4994 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4995 avctx->skip_frame < AVDISCARD_ALL)
4999 init_get_bits(&h->gb, ptr, bit_length);
5000 ff_h264_decode_sei(h);
5003 init_get_bits(&h->gb, ptr, bit_length);
5004 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
5005 av_log(h->avctx, AV_LOG_DEBUG,
5006 "SPS decoding failure, trying again with the complete NAL\n");
5008 av_assert0(next_avc - buf_index + consumed == nalsize);
5009 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
5011 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
5012 8*(next_avc - buf_index + consumed - 1));
5013 ff_h264_decode_seq_parameter_set(h);
5018 init_get_bits(&h->gb, ptr, bit_length);
5019 ff_h264_decode_picture_parameter_set(h, bit_length);
5022 case NAL_END_SEQUENCE:
5023 case NAL_END_STREAM:
5024 case NAL_FILLER_DATA:
5026 case NAL_AUXILIARY_SLICE:
5031 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
5032 hx->nal_unit_type, bit_length);
5035 if (context_count == h->max_contexts) {
5036 execute_decode_slices(h, context_count);
5041 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
5042 else if (err == 1) {
5043 /* Slice could not be decoded in parallel mode, copy down
5044 * NAL unit stuff to context 0 and restart. Note that
5045 * rbsp_buffer is not transferred, but since we no longer
5046 * run in parallel mode this should not be an issue. */
5047 h->nal_unit_type = hx->nal_unit_type;
5048 h->nal_ref_idc = hx->nal_ref_idc;
5055 execute_decode_slices(h, context_count);
5059 if (h->cur_pic_ptr && !h->droppable) {
5060 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
5061 h->picture_structure == PICT_BOTTOM_FIELD);
5064 return (ret < 0) ? ret : buf_index;
5068 * Return the number of bytes consumed for building the current frame.
5070 static int get_consumed_bytes(int pos, int buf_size)
5073 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
5074 if (pos + 10 > buf_size)
5075 pos = buf_size; // oops ;)
5080 static int output_frame(H264Context *h, AVFrame *dst, Picture *srcp)
5082 AVFrame *src = &srcp->f;
5084 int ret = av_frame_ref(dst, src);
5088 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
5093 for (i = 0; i < 3; i++) {
5094 int hshift = (i > 0) ? h->chroma_x_shift : 0;
5095 int vshift = (i > 0) ? h->chroma_y_shift : 0;
5096 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
5097 (srcp->crop_top >> vshift) * dst->linesize[i];
5098 dst->data[i] += off;
5103 static int h264_decode_frame(AVCodecContext *avctx, void *data,
5104 int *got_frame, AVPacket *avpkt)
5106 const uint8_t *buf = avpkt->data;
5107 int buf_size = avpkt->size;
5108 H264Context *h = avctx->priv_data;
5109 AVFrame *pict = data;
5115 h->flags = avctx->flags;
5117 /* end of stream, output what is still in the buffers */
5118 if (buf_size == 0) {
5121 h->cur_pic_ptr = NULL;
5124 // FIXME factorize this with the output code below
5125 out = h->delayed_pic[0];
5128 h->delayed_pic[i] &&
5129 !h->delayed_pic[i]->f.key_frame &&
5130 !h->delayed_pic[i]->mmco_reset;
5132 if (h->delayed_pic[i]->poc < out->poc) {
5133 out = h->delayed_pic[i];
5137 for (i = out_idx; h->delayed_pic[i]; i++)
5138 h->delayed_pic[i] = h->delayed_pic[i + 1];
5141 out->reference &= ~DELAYED_PIC_REF;
5142 ret = output_frame(h, pict, out);
5150 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
5151 int cnt= buf[5]&0x1f;
5152 const uint8_t *p= buf+6;
5154 int nalsize= AV_RB16(p) + 2;
5155 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
5163 int nalsize= AV_RB16(p) + 2;
5164 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
5169 return ff_h264_decode_extradata(h, buf, buf_size);
5173 buf_index = decode_nal_units(h, buf, buf_size, 0);
5175 return AVERROR_INVALIDDATA;
5177 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
5178 av_assert0(buf_index <= buf_size);
5182 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
5183 if (avctx->skip_frame >= AVDISCARD_NONREF ||
5184 buf_size >= 4 && !memcmp("Q264", buf, 4))
5186 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
5187 return AVERROR_INVALIDDATA;
5190 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
5191 (h->mb_y >= h->mb_height && h->mb_height)) {
5192 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
5193 decode_postinit(h, 1);
5197 /* Wait for second field. */
5199 if (h->next_output_pic && (
5200 h->next_output_pic->recovered)) {
5201 if (!h->next_output_pic->recovered)
5202 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
5204 ret = output_frame(h, pict, h->next_output_pic);
5208 if (CONFIG_MPEGVIDEO) {
5209 ff_print_debug_info2(h->avctx, h->next_output_pic, pict, h->er.mbskip_table,
5211 h->mb_width, h->mb_height, h->mb_stride, 1);
5216 assert(pict->buf[0] || !*got_frame);
5218 return get_consumed_bytes(buf_index, buf_size);
5221 av_cold void ff_h264_free_context(H264Context *h)
5225 free_tables(h, 1); // FIXME cleanup init stuff perhaps
5227 for (i = 0; i < MAX_SPS_COUNT; i++)
5228 av_freep(h->sps_buffers + i);
5230 for (i = 0; i < MAX_PPS_COUNT; i++)
5231 av_freep(h->pps_buffers + i);
5234 static av_cold int h264_decode_end(AVCodecContext *avctx)
5236 H264Context *h = avctx->priv_data;
5238 ff_h264_remove_all_refs(h);
5239 ff_h264_free_context(h);
5241 unref_picture(h, &h->cur_pic);
5246 static const AVProfile profiles[] = {
5247 { FF_PROFILE_H264_BASELINE, "Baseline" },
5248 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
5249 { FF_PROFILE_H264_MAIN, "Main" },
5250 { FF_PROFILE_H264_EXTENDED, "Extended" },
5251 { FF_PROFILE_H264_HIGH, "High" },
5252 { FF_PROFILE_H264_HIGH_10, "High 10" },
5253 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
5254 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
5255 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
5256 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
5257 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
5258 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
5259 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
5260 { FF_PROFILE_UNKNOWN },
5263 static const AVOption h264_options[] = {
5264 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
5265 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
5269 static const AVClass h264_class = {
5270 .class_name = "H264 Decoder",
5271 .item_name = av_default_item_name,
5272 .option = h264_options,
5273 .version = LIBAVUTIL_VERSION_INT,
5276 static const AVClass h264_vdpau_class = {
5277 .class_name = "H264 VDPAU Decoder",
5278 .item_name = av_default_item_name,
5279 .option = h264_options,
5280 .version = LIBAVUTIL_VERSION_INT,
5283 AVCodec ff_h264_decoder = {
5285 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5286 .type = AVMEDIA_TYPE_VIDEO,
5287 .id = AV_CODEC_ID_H264,
5288 .priv_data_size = sizeof(H264Context),
5289 .init = ff_h264_decode_init,
5290 .close = h264_decode_end,
5291 .decode = h264_decode_frame,
5292 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5293 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
5294 CODEC_CAP_FRAME_THREADS,
5296 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
5297 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5298 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5299 .priv_class = &h264_class,
5302 #if CONFIG_H264_VDPAU_DECODER
5303 AVCodec ff_h264_vdpau_decoder = {
5304 .name = "h264_vdpau",
5305 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
5306 .type = AVMEDIA_TYPE_VIDEO,
5307 .id = AV_CODEC_ID_H264,
5308 .priv_data_size = sizeof(H264Context),
5309 .init = ff_h264_decode_init,
5310 .close = h264_decode_end,
5311 .decode = h264_decode_frame,
5312 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5314 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
5316 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5317 .priv_class = &h264_vdpau_class,