2 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * H.264 / AVC / MPEG4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #define UNCHECKED_BITSTREAM_READER 1
30 #include "libavutil/avassert.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/stereo3d.h"
34 #include "libavutil/timer.h"
37 #include "cabac_functions.h"
39 #include "error_resilience.h"
41 #include "mpegvideo.h"
44 #include "h264chroma.h"
45 #include "h264_mvpred.h"
48 #include "rectangle.h"
51 #include "vdpau_internal.h"
55 static void flush_change(H264Context *h);
57 const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
59 static const uint8_t rem6[QP_MAX_NUM + 1] = {
60 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
61 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
62 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
63 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
67 static const uint8_t div6[QP_MAX_NUM + 1] = {
68 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
69 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
70 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
71 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
75 static const uint8_t field_scan[16+1] = {
76 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
77 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
78 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
79 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
82 static const uint8_t field_scan8x8[64+1] = {
83 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
84 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
85 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
86 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
87 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
88 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
89 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
90 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
91 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
92 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
93 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
94 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
95 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
96 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
97 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
98 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
101 static const uint8_t field_scan8x8_cavlc[64+1] = {
102 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
103 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
104 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
105 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
106 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
107 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
108 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
109 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
110 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
111 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
112 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
113 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
114 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
115 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
116 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
117 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
120 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
121 static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
122 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
123 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
124 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
125 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
126 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
127 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
128 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
129 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
130 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
131 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
132 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
133 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
134 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
135 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
136 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
137 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
140 static const uint8_t dequant4_coeff_init[6][3] = {
149 static const uint8_t dequant8_coeff_init_scan[16] = {
150 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
153 static const uint8_t dequant8_coeff_init[6][6] = {
154 { 20, 18, 32, 19, 25, 24 },
155 { 22, 19, 35, 21, 28, 26 },
156 { 26, 23, 42, 24, 33, 31 },
157 { 28, 25, 45, 26, 35, 33 },
158 { 32, 28, 51, 30, 40, 38 },
159 { 36, 32, 58, 34, 46, 43 },
162 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
163 #if CONFIG_H264_DXVA2_HWACCEL
164 AV_PIX_FMT_DXVA2_VLD,
166 #if CONFIG_H264_VAAPI_HWACCEL
167 AV_PIX_FMT_VAAPI_VLD,
169 #if CONFIG_H264_VDA_HWACCEL
172 #if CONFIG_H264_VDPAU_HWACCEL
179 static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
180 #if CONFIG_H264_DXVA2_HWACCEL
181 AV_PIX_FMT_DXVA2_VLD,
183 #if CONFIG_H264_VAAPI_HWACCEL
184 AV_PIX_FMT_VAAPI_VLD,
186 #if CONFIG_H264_VDA_HWACCEL
189 #if CONFIG_H264_VDPAU_HWACCEL
196 int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
198 H264Context *h = avctx->priv_data;
199 return h ? h->sps.num_reorder_frames : 0;
202 static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
204 int mb_x, int mb_y, int mb_intra, int mb_skipped)
206 H264Context *h = opaque;
210 h->mb_xy = mb_x + mb_y * h->mb_stride;
211 memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
212 av_assert1(ref >= 0);
213 /* FIXME: It is possible albeit uncommon that slice references
214 * differ between slices. We take the easy approach and ignore
215 * it for now. If this turns out to have any relevance in
216 * practice then correct remapping should be added. */
217 if (ref >= h->ref_count[0])
219 if (!h->ref_list[0][ref].f.data[0]) {
220 av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
223 if ((h->ref_list[0][ref].reference&3) != 3) {
224 av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
227 fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
229 fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
230 fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
231 pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
233 h->mb_field_decoding_flag = 0;
234 ff_h264_hl_decode_mb(h);
237 void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
239 AVCodecContext *avctx = h->avctx;
240 Picture *cur = &h->cur_pic;
241 Picture *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0] : NULL;
242 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
243 int vshift = desc->log2_chroma_h;
244 const int field_pic = h->picture_structure != PICT_FRAME;
250 height = FFMIN(height, avctx->height - y);
252 if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
255 if (avctx->draw_horiz_band) {
257 int offset[AV_NUM_DATA_POINTERS];
260 if (cur->f.pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
261 (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
268 offset[0] = y * src->linesize[0];
270 offset[2] = (y >> vshift) * src->linesize[1];
271 for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
276 avctx->draw_horiz_band(avctx, src, offset,
277 y, h->picture_structure, height);
281 static void unref_picture(H264Context *h, Picture *pic)
283 int off = offsetof(Picture, tf) + sizeof(pic->tf);
289 ff_thread_release_buffer(h->avctx, &pic->tf);
290 av_buffer_unref(&pic->hwaccel_priv_buf);
292 av_buffer_unref(&pic->qscale_table_buf);
293 av_buffer_unref(&pic->mb_type_buf);
294 for (i = 0; i < 2; i++) {
295 av_buffer_unref(&pic->motion_val_buf[i]);
296 av_buffer_unref(&pic->ref_index_buf[i]);
299 memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
302 static void release_unused_pictures(H264Context *h, int remove_current)
306 /* release non reference frames */
307 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
308 if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
309 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
310 unref_picture(h, &h->DPB[i]);
315 static int ref_picture(H264Context *h, Picture *dst, Picture *src)
319 av_assert0(!dst->f.buf[0]);
320 av_assert0(src->f.buf[0]);
324 ret = ff_thread_ref_frame(&dst->tf, &src->tf);
328 dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
329 dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
330 if (!dst->qscale_table_buf || !dst->mb_type_buf)
332 dst->qscale_table = src->qscale_table;
333 dst->mb_type = src->mb_type;
335 for (i = 0; i < 2; i++) {
336 dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
337 dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
338 if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
340 dst->motion_val[i] = src->motion_val[i];
341 dst->ref_index[i] = src->ref_index[i];
344 if (src->hwaccel_picture_private) {
345 dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
346 if (!dst->hwaccel_priv_buf)
348 dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
351 for (i = 0; i < 2; i++)
352 dst->field_poc[i] = src->field_poc[i];
354 memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
355 memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
358 dst->frame_num = src->frame_num;
359 dst->mmco_reset = src->mmco_reset;
360 dst->pic_id = src->pic_id;
361 dst->long_ref = src->long_ref;
362 dst->mbaff = src->mbaff;
363 dst->field_picture = src->field_picture;
364 dst->needs_realloc = src->needs_realloc;
365 dst->reference = src->reference;
366 dst->crop = src->crop;
367 dst->crop_left = src->crop_left;
368 dst->crop_top = src->crop_top;
369 dst->recovered = src->recovered;
373 unref_picture(h, dst);
377 static int alloc_scratch_buffers(H264Context *h, int linesize)
379 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
381 if (h->bipred_scratchpad)
384 h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
385 // edge emu needs blocksize + filter length - 1
386 // (= 21x21 for h264)
387 h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
388 h->me.scratchpad = av_mallocz(alloc_size * 2 * 16 * 2);
390 if (!h->bipred_scratchpad || !h->edge_emu_buffer || !h->me.scratchpad) {
391 av_freep(&h->bipred_scratchpad);
392 av_freep(&h->edge_emu_buffer);
393 av_freep(&h->me.scratchpad);
394 return AVERROR(ENOMEM);
397 h->me.temp = h->me.scratchpad;
402 static int init_table_pools(H264Context *h)
404 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
405 const int mb_array_size = h->mb_stride * h->mb_height;
406 const int b4_stride = h->mb_width * 4 + 1;
407 const int b4_array_size = b4_stride * h->mb_height * 4;
409 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
411 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
412 sizeof(uint32_t), av_buffer_allocz);
413 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
414 sizeof(int16_t), av_buffer_allocz);
415 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
417 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
418 !h->ref_index_pool) {
419 av_buffer_pool_uninit(&h->qscale_table_pool);
420 av_buffer_pool_uninit(&h->mb_type_pool);
421 av_buffer_pool_uninit(&h->motion_val_pool);
422 av_buffer_pool_uninit(&h->ref_index_pool);
423 return AVERROR(ENOMEM);
429 static int alloc_picture(H264Context *h, Picture *pic)
433 av_assert0(!pic->f.data[0]);
436 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
437 AV_GET_BUFFER_FLAG_REF : 0);
441 h->linesize = pic->f.linesize[0];
442 h->uvlinesize = pic->f.linesize[1];
443 pic->crop = h->sps.crop;
444 pic->crop_top = h->sps.crop_top;
445 pic->crop_left= h->sps.crop_left;
447 if (h->avctx->hwaccel) {
448 const AVHWAccel *hwaccel = h->avctx->hwaccel;
449 av_assert0(!pic->hwaccel_picture_private);
450 if (hwaccel->priv_data_size) {
451 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
452 if (!pic->hwaccel_priv_buf)
453 return AVERROR(ENOMEM);
454 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
458 if (!h->qscale_table_pool) {
459 ret = init_table_pools(h);
464 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
465 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
466 if (!pic->qscale_table_buf || !pic->mb_type_buf)
469 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
470 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
472 for (i = 0; i < 2; i++) {
473 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
474 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
475 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
478 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
479 pic->ref_index[i] = pic->ref_index_buf[i]->data;
484 unref_picture(h, pic);
485 return (ret < 0) ? ret : AVERROR(ENOMEM);
488 static inline int pic_is_unused(H264Context *h, Picture *pic)
492 if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
497 static int find_unused_picture(H264Context *h)
501 for (i = 0; i < MAX_PICTURE_COUNT; i++) {
502 if (pic_is_unused(h, &h->DPB[i]))
505 if (i == MAX_PICTURE_COUNT)
506 return AVERROR_INVALIDDATA;
508 if (h->DPB[i].needs_realloc) {
509 h->DPB[i].needs_realloc = 0;
510 unref_picture(h, &h->DPB[i]);
517 * Check if the top & left blocks are available if needed and
518 * change the dc mode so it only uses the available blocks.
520 int ff_h264_check_intra4x4_pred_mode(H264Context *h)
522 static const int8_t top[12] = {
523 -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
525 static const int8_t left[12] = {
526 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
530 if (!(h->top_samples_available & 0x8000)) {
531 for (i = 0; i < 4; i++) {
532 int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
534 av_log(h->avctx, AV_LOG_ERROR,
535 "top block unavailable for requested intra4x4 mode %d at %d %d\n",
536 status, h->mb_x, h->mb_y);
537 return AVERROR_INVALIDDATA;
539 h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
544 if ((h->left_samples_available & 0x8888) != 0x8888) {
545 static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
546 for (i = 0; i < 4; i++)
547 if (!(h->left_samples_available & mask[i])) {
548 int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
550 av_log(h->avctx, AV_LOG_ERROR,
551 "left block unavailable for requested intra4x4 mode %d at %d %d\n",
552 status, h->mb_x, h->mb_y);
553 return AVERROR_INVALIDDATA;
555 h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
561 } // FIXME cleanup like ff_h264_check_intra_pred_mode
564 * Check if the top & left blocks are available if needed and
565 * change the dc mode so it only uses the available blocks.
567 int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
569 static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
570 static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
573 av_log(h->avctx, AV_LOG_ERROR,
574 "out of range intra chroma pred mode at %d %d\n",
576 return AVERROR_INVALIDDATA;
579 if (!(h->top_samples_available & 0x8000)) {
582 av_log(h->avctx, AV_LOG_ERROR,
583 "top block unavailable for requested intra mode at %d %d\n",
585 return AVERROR_INVALIDDATA;
589 if ((h->left_samples_available & 0x8080) != 0x8080) {
591 if (is_chroma && (h->left_samples_available & 0x8080)) {
592 // mad cow disease mode, aka MBAFF + constrained_intra_pred
593 mode = ALZHEIMER_DC_L0T_PRED8x8 +
594 (!(h->left_samples_available & 0x8000)) +
595 2 * (mode == DC_128_PRED8x8);
598 av_log(h->avctx, AV_LOG_ERROR,
599 "left block unavailable for requested intra mode at %d %d\n",
601 return AVERROR_INVALIDDATA;
608 const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
609 int *dst_length, int *consumed, int length)
615 // src[0]&0x80; // forbidden bit
616 h->nal_ref_idc = src[0] >> 5;
617 h->nal_unit_type = src[0] & 0x1F;
622 #define STARTCODE_TEST \
623 if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
624 if (src[i + 2] != 3) { \
625 /* startcode, so we must be past the end */ \
631 #if HAVE_FAST_UNALIGNED
632 #define FIND_FIRST_ZERO \
633 if (i > 0 && !src[i]) \
639 for (i = 0; i + 1 < length; i += 9) {
640 if (!((~AV_RN64A(src + i) &
641 (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
642 0x8000800080008080ULL))
649 for (i = 0; i + 1 < length; i += 5) {
650 if (!((~AV_RN32A(src + i) &
651 (AV_RN32A(src + i) - 0x01000101U)) &
660 for (i = 0; i + 1 < length; i += 2) {
663 if (i > 0 && src[i - 1] == 0)
669 // use second escape buffer for inter data
670 bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
672 si = h->rbsp_buffer_size[bufidx];
673 av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
674 dst = h->rbsp_buffer[bufidx];
679 if(i>=length-1){ //no escaped 0
681 *consumed= length+1; //+1 for the header
682 if(h->avctx->flags2 & CODEC_FLAG2_FAST){
685 memcpy(dst, src, length);
692 while (si + 2 < length) {
693 // remove escapes (very rare 1:2^22)
694 if (src[si + 2] > 3) {
695 dst[di++] = src[si++];
696 dst[di++] = src[si++];
697 } else if (src[si] == 0 && src[si + 1] == 0) {
698 if (src[si + 2] == 3) { // escape
703 } else // next start code
707 dst[di++] = src[si++];
710 dst[di++] = src[si++];
713 memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
716 *consumed = si + 1; // +1 for the header
717 /* FIXME store exact number of bits in the getbitcontext
718 * (it is needed for decoding) */
723 * Identify the exact end of the bitstream
724 * @return the length of the trailing, or 0 if damaged
726 static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
731 tprintf(h->avctx, "rbsp trailing %X\n", v);
733 for (r = 1; r < 9; r++) {
741 static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
742 int height, int y_offset, int list)
744 int raw_my = h->mv_cache[list][scan8[n]][1];
745 int filter_height_down = (raw_my & 3) ? 3 : 0;
746 int full_my = (raw_my >> 2) + y_offset;
747 int bottom = full_my + filter_height_down + height;
749 av_assert2(height >= 0);
751 return FFMAX(0, bottom);
754 static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
755 int height, int y_offset, int list0,
756 int list1, int *nrefs)
760 y_offset += 16 * (h->mb_y >> MB_FIELD(h));
763 int ref_n = h->ref_cache[0][scan8[n]];
764 Picture *ref = &h->ref_list[0][ref_n];
766 // Error resilience puts the current picture in the ref list.
767 // Don't try to wait on these as it will cause a deadlock.
768 // Fields can wait on each other, though.
769 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
770 (ref->reference & 3) != h->picture_structure) {
771 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
772 if (refs[0][ref_n] < 0)
774 refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
779 int ref_n = h->ref_cache[1][scan8[n]];
780 Picture *ref = &h->ref_list[1][ref_n];
782 if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
783 (ref->reference & 3) != h->picture_structure) {
784 my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
785 if (refs[1][ref_n] < 0)
787 refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
793 * Wait until all reference frames are available for MC operations.
795 * @param h the H264 context
797 static void await_references(H264Context *h)
799 const int mb_xy = h->mb_xy;
800 const int mb_type = h->cur_pic.mb_type[mb_xy];
802 int nrefs[2] = { 0 };
805 memset(refs, -1, sizeof(refs));
807 if (IS_16X16(mb_type)) {
808 get_lowest_part_y(h, refs, 0, 16, 0,
809 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
810 } else if (IS_16X8(mb_type)) {
811 get_lowest_part_y(h, refs, 0, 8, 0,
812 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
813 get_lowest_part_y(h, refs, 8, 8, 8,
814 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
815 } else if (IS_8X16(mb_type)) {
816 get_lowest_part_y(h, refs, 0, 16, 0,
817 IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
818 get_lowest_part_y(h, refs, 4, 16, 0,
819 IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
823 av_assert2(IS_8X8(mb_type));
825 for (i = 0; i < 4; i++) {
826 const int sub_mb_type = h->sub_mb_type[i];
828 int y_offset = (i & 2) << 2;
830 if (IS_SUB_8X8(sub_mb_type)) {
831 get_lowest_part_y(h, refs, n, 8, y_offset,
832 IS_DIR(sub_mb_type, 0, 0),
833 IS_DIR(sub_mb_type, 0, 1),
835 } else if (IS_SUB_8X4(sub_mb_type)) {
836 get_lowest_part_y(h, refs, n, 4, y_offset,
837 IS_DIR(sub_mb_type, 0, 0),
838 IS_DIR(sub_mb_type, 0, 1),
840 get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
841 IS_DIR(sub_mb_type, 0, 0),
842 IS_DIR(sub_mb_type, 0, 1),
844 } else if (IS_SUB_4X8(sub_mb_type)) {
845 get_lowest_part_y(h, refs, n, 8, y_offset,
846 IS_DIR(sub_mb_type, 0, 0),
847 IS_DIR(sub_mb_type, 0, 1),
849 get_lowest_part_y(h, refs, n + 1, 8, y_offset,
850 IS_DIR(sub_mb_type, 0, 0),
851 IS_DIR(sub_mb_type, 0, 1),
855 av_assert2(IS_SUB_4X4(sub_mb_type));
856 for (j = 0; j < 4; j++) {
857 int sub_y_offset = y_offset + 2 * (j & 2);
858 get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
859 IS_DIR(sub_mb_type, 0, 0),
860 IS_DIR(sub_mb_type, 0, 1),
867 for (list = h->list_count - 1; list >= 0; list--)
868 for (ref = 0; ref < 48 && nrefs[list]; ref++) {
869 int row = refs[list][ref];
871 Picture *ref_pic = &h->ref_list[list][ref];
872 int ref_field = ref_pic->reference - 1;
873 int ref_field_picture = ref_pic->field_picture;
874 int pic_height = 16 * h->mb_height >> ref_field_picture;
879 if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
880 ff_thread_await_progress(&ref_pic->tf,
881 FFMIN((row >> 1) - !(row & 1),
884 ff_thread_await_progress(&ref_pic->tf,
885 FFMIN((row >> 1), pic_height - 1),
887 } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
888 ff_thread_await_progress(&ref_pic->tf,
889 FFMIN(row * 2 + ref_field,
892 } else if (FIELD_PICTURE(h)) {
893 ff_thread_await_progress(&ref_pic->tf,
894 FFMIN(row, pic_height - 1),
897 ff_thread_await_progress(&ref_pic->tf,
898 FFMIN(row, pic_height - 1),
905 static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
906 int n, int square, int height,
908 uint8_t *dest_y, uint8_t *dest_cb,
910 int src_x_offset, int src_y_offset,
911 qpel_mc_func *qpix_op,
912 h264_chroma_mc_func chroma_op,
913 int pixel_shift, int chroma_idc)
915 const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
916 int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
917 const int luma_xy = (mx & 3) + ((my & 3) << 2);
918 ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
919 uint8_t *src_y = pic->f.data[0] + offset;
920 uint8_t *src_cb, *src_cr;
922 int extra_height = 0;
924 const int full_mx = mx >> 2;
925 const int full_my = my >> 2;
926 const int pic_width = 16 * h->mb_width;
927 const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
935 if (full_mx < 0 - extra_width ||
936 full_my < 0 - extra_height ||
937 full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
938 full_my + 16 /*FIXME*/ > pic_height + extra_height) {
939 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
940 src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
941 h->mb_linesize, h->mb_linesize,
942 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
943 full_my - 2, pic_width, pic_height);
944 src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
948 qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
950 qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
952 if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
955 if (chroma_idc == 3 /* yuv444 */) {
956 src_cb = pic->f.data[1] + offset;
958 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
959 src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
960 h->mb_linesize, h->mb_linesize,
961 16 + 5, 16 + 5 /*FIXME*/,
962 full_mx - 2, full_my - 2,
963 pic_width, pic_height);
964 src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
966 qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
968 qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
970 src_cr = pic->f.data[2] + offset;
972 h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
973 src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
974 h->mb_linesize, h->mb_linesize,
975 16 + 5, 16 + 5 /*FIXME*/,
976 full_mx - 2, full_my - 2,
977 pic_width, pic_height);
978 src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
980 qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
982 qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
986 ysh = 3 - (chroma_idc == 2 /* yuv422 */);
987 if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
988 // chroma offset when predicting from a field of opposite parity
989 my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
990 emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
993 src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
994 (my >> ysh) * h->mb_uvlinesize;
995 src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
996 (my >> ysh) * h->mb_uvlinesize;
999 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
1000 h->mb_uvlinesize, h->mb_uvlinesize,
1001 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1002 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1003 src_cb = h->edge_emu_buffer;
1005 chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
1006 height >> (chroma_idc == 1 /* yuv420 */),
1007 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1010 h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
1011 h->mb_uvlinesize, h->mb_uvlinesize,
1012 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
1013 pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
1014 src_cr = h->edge_emu_buffer;
1016 chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
1017 mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
1020 static av_always_inline void mc_part_std(H264Context *h, int n, int square,
1021 int height, int delta,
1022 uint8_t *dest_y, uint8_t *dest_cb,
1024 int x_offset, int y_offset,
1025 qpel_mc_func *qpix_put,
1026 h264_chroma_mc_func chroma_put,
1027 qpel_mc_func *qpix_avg,
1028 h264_chroma_mc_func chroma_avg,
1029 int list0, int list1,
1030 int pixel_shift, int chroma_idc)
1032 qpel_mc_func *qpix_op = qpix_put;
1033 h264_chroma_mc_func chroma_op = chroma_put;
1035 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1036 if (chroma_idc == 3 /* yuv444 */) {
1037 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1038 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1039 } else if (chroma_idc == 2 /* yuv422 */) {
1040 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1041 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1042 } else { /* yuv420 */
1043 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1044 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1046 x_offset += 8 * h->mb_x;
1047 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1050 Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
1051 mc_dir_part(h, ref, n, square, height, delta, 0,
1052 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1053 qpix_op, chroma_op, pixel_shift, chroma_idc);
1056 chroma_op = chroma_avg;
1060 Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
1061 mc_dir_part(h, ref, n, square, height, delta, 1,
1062 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1063 qpix_op, chroma_op, pixel_shift, chroma_idc);
1067 static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
1068 int height, int delta,
1069 uint8_t *dest_y, uint8_t *dest_cb,
1071 int x_offset, int y_offset,
1072 qpel_mc_func *qpix_put,
1073 h264_chroma_mc_func chroma_put,
1074 h264_weight_func luma_weight_op,
1075 h264_weight_func chroma_weight_op,
1076 h264_biweight_func luma_weight_avg,
1077 h264_biweight_func chroma_weight_avg,
1078 int list0, int list1,
1079 int pixel_shift, int chroma_idc)
1083 dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1084 if (chroma_idc == 3 /* yuv444 */) {
1085 chroma_height = height;
1086 chroma_weight_avg = luma_weight_avg;
1087 chroma_weight_op = luma_weight_op;
1088 dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1089 dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
1090 } else if (chroma_idc == 2 /* yuv422 */) {
1091 chroma_height = height;
1092 dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1093 dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
1094 } else { /* yuv420 */
1095 chroma_height = height >> 1;
1096 dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1097 dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
1099 x_offset += 8 * h->mb_x;
1100 y_offset += 8 * (h->mb_y >> MB_FIELD(h));
1102 if (list0 && list1) {
1103 /* don't optimize for luma-only case, since B-frames usually
1104 * use implicit weights => chroma too. */
1105 uint8_t *tmp_cb = h->bipred_scratchpad;
1106 uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
1107 uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
1108 int refn0 = h->ref_cache[0][scan8[n]];
1109 int refn1 = h->ref_cache[1][scan8[n]];
1111 mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
1112 dest_y, dest_cb, dest_cr,
1113 x_offset, y_offset, qpix_put, chroma_put,
1114 pixel_shift, chroma_idc);
1115 mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
1116 tmp_y, tmp_cb, tmp_cr,
1117 x_offset, y_offset, qpix_put, chroma_put,
1118 pixel_shift, chroma_idc);
1120 if (h->use_weight == 2) {
1121 int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
1122 int weight1 = 64 - weight0;
1123 luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
1124 height, 5, weight0, weight1, 0);
1125 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
1126 chroma_height, 5, weight0, weight1, 0);
1127 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
1128 chroma_height, 5, weight0, weight1, 0);
1130 luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
1131 h->luma_log2_weight_denom,
1132 h->luma_weight[refn0][0][0],
1133 h->luma_weight[refn1][1][0],
1134 h->luma_weight[refn0][0][1] +
1135 h->luma_weight[refn1][1][1]);
1136 chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
1137 h->chroma_log2_weight_denom,
1138 h->chroma_weight[refn0][0][0][0],
1139 h->chroma_weight[refn1][1][0][0],
1140 h->chroma_weight[refn0][0][0][1] +
1141 h->chroma_weight[refn1][1][0][1]);
1142 chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
1143 h->chroma_log2_weight_denom,
1144 h->chroma_weight[refn0][0][1][0],
1145 h->chroma_weight[refn1][1][1][0],
1146 h->chroma_weight[refn0][0][1][1] +
1147 h->chroma_weight[refn1][1][1][1]);
1150 int list = list1 ? 1 : 0;
1151 int refn = h->ref_cache[list][scan8[n]];
1152 Picture *ref = &h->ref_list[list][refn];
1153 mc_dir_part(h, ref, n, square, height, delta, list,
1154 dest_y, dest_cb, dest_cr, x_offset, y_offset,
1155 qpix_put, chroma_put, pixel_shift, chroma_idc);
1157 luma_weight_op(dest_y, h->mb_linesize, height,
1158 h->luma_log2_weight_denom,
1159 h->luma_weight[refn][list][0],
1160 h->luma_weight[refn][list][1]);
1161 if (h->use_weight_chroma) {
1162 chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
1163 h->chroma_log2_weight_denom,
1164 h->chroma_weight[refn][list][0][0],
1165 h->chroma_weight[refn][list][0][1]);
1166 chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
1167 h->chroma_log2_weight_denom,
1168 h->chroma_weight[refn][list][1][0],
1169 h->chroma_weight[refn][list][1][1]);
1174 static av_always_inline void prefetch_motion(H264Context *h, int list,
1175 int pixel_shift, int chroma_idc)
1177 /* fetch pixels for estimated mv 4 macroblocks ahead
1178 * optimized for 64byte cache lines */
1179 const int refn = h->ref_cache[list][scan8[0]];
1181 const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
1182 const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
1183 uint8_t **src = h->ref_list[list][refn].f.data;
1184 int off = (mx << pixel_shift) +
1185 (my + (h->mb_x & 3) * 4) * h->mb_linesize +
1186 (64 << pixel_shift);
1187 h->vdsp.prefetch(src[0] + off, h->linesize, 4);
1188 if (chroma_idc == 3 /* yuv444 */) {
1189 h->vdsp.prefetch(src[1] + off, h->linesize, 4);
1190 h->vdsp.prefetch(src[2] + off, h->linesize, 4);
1192 off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
1193 h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
1198 static void free_tables(H264Context *h, int free_rbsp)
1203 av_freep(&h->intra4x4_pred_mode);
1204 av_freep(&h->chroma_pred_mode_table);
1205 av_freep(&h->cbp_table);
1206 av_freep(&h->mvd_table[0]);
1207 av_freep(&h->mvd_table[1]);
1208 av_freep(&h->direct_table);
1209 av_freep(&h->non_zero_count);
1210 av_freep(&h->slice_table_base);
1211 h->slice_table = NULL;
1212 av_freep(&h->list_counts);
1214 av_freep(&h->mb2b_xy);
1215 av_freep(&h->mb2br_xy);
1217 av_buffer_pool_uninit(&h->qscale_table_pool);
1218 av_buffer_pool_uninit(&h->mb_type_pool);
1219 av_buffer_pool_uninit(&h->motion_val_pool);
1220 av_buffer_pool_uninit(&h->ref_index_pool);
1222 if (free_rbsp && h->DPB) {
1223 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1224 unref_picture(h, &h->DPB[i]);
1226 } else if (h->DPB) {
1227 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1228 h->DPB[i].needs_realloc = 1;
1231 h->cur_pic_ptr = NULL;
1233 for (i = 0; i < MAX_THREADS; i++) {
1234 hx = h->thread_context[i];
1237 av_freep(&hx->top_borders[1]);
1238 av_freep(&hx->top_borders[0]);
1239 av_freep(&hx->bipred_scratchpad);
1240 av_freep(&hx->edge_emu_buffer);
1241 av_freep(&hx->dc_val_base);
1242 av_freep(&hx->me.scratchpad);
1243 av_freep(&hx->er.mb_index2xy);
1244 av_freep(&hx->er.error_status_table);
1245 av_freep(&hx->er.er_temp_buffer);
1246 av_freep(&hx->er.mbintra_table);
1247 av_freep(&hx->er.mbskip_table);
1250 av_freep(&hx->rbsp_buffer[1]);
1251 av_freep(&hx->rbsp_buffer[0]);
1252 hx->rbsp_buffer_size[0] = 0;
1253 hx->rbsp_buffer_size[1] = 0;
1256 av_freep(&h->thread_context[i]);
1260 static void init_dequant8_coeff_table(H264Context *h)
1263 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1265 for (i = 0; i < 6; i++) {
1266 h->dequant8_coeff[i] = h->dequant8_buffer[i];
1267 for (j = 0; j < i; j++)
1268 if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
1269 64 * sizeof(uint8_t))) {
1270 h->dequant8_coeff[i] = h->dequant8_buffer[j];
1276 for (q = 0; q < max_qp + 1; q++) {
1277 int shift = div6[q];
1279 for (x = 0; x < 64; x++)
1280 h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
1281 ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
1282 h->pps.scaling_matrix8[i][x]) << shift;
1287 static void init_dequant4_coeff_table(H264Context *h)
1290 const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
1291 for (i = 0; i < 6; i++) {
1292 h->dequant4_coeff[i] = h->dequant4_buffer[i];
1293 for (j = 0; j < i; j++)
1294 if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
1295 16 * sizeof(uint8_t))) {
1296 h->dequant4_coeff[i] = h->dequant4_buffer[j];
1302 for (q = 0; q < max_qp + 1; q++) {
1303 int shift = div6[q] + 2;
1305 for (x = 0; x < 16; x++)
1306 h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
1307 ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
1308 h->pps.scaling_matrix4[i][x]) << shift;
1313 static void init_dequant_tables(H264Context *h)
1316 init_dequant4_coeff_table(h);
1317 memset(h->dequant8_coeff, 0, sizeof(h->dequant8_coeff));
1319 if (h->pps.transform_8x8_mode)
1320 init_dequant8_coeff_table(h);
1321 if (h->sps.transform_bypass) {
1322 for (i = 0; i < 6; i++)
1323 for (x = 0; x < 16; x++)
1324 h->dequant4_coeff[i][0][x] = 1 << 6;
1325 if (h->pps.transform_8x8_mode)
1326 for (i = 0; i < 6; i++)
1327 for (x = 0; x < 64; x++)
1328 h->dequant8_coeff[i][0][x] = 1 << 6;
1332 int ff_h264_alloc_tables(H264Context *h)
1334 const int big_mb_num = h->mb_stride * (h->mb_height + 1);
1335 const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
1338 FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
1339 row_mb_num * 8 * sizeof(uint8_t), fail)
1340 FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
1341 big_mb_num * 48 * sizeof(uint8_t), fail)
1342 FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
1343 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
1344 FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
1345 big_mb_num * sizeof(uint16_t), fail)
1346 FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
1347 big_mb_num * sizeof(uint8_t), fail)
1348 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
1349 16 * row_mb_num * sizeof(uint8_t), fail);
1350 FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
1351 16 * row_mb_num * sizeof(uint8_t), fail);
1352 FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
1353 4 * big_mb_num * sizeof(uint8_t), fail);
1354 FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
1355 big_mb_num * sizeof(uint8_t), fail)
1357 memset(h->slice_table_base, -1,
1358 (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
1359 h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
1361 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
1362 big_mb_num * sizeof(uint32_t), fail);
1363 FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
1364 big_mb_num * sizeof(uint32_t), fail);
1365 for (y = 0; y < h->mb_height; y++)
1366 for (x = 0; x < h->mb_width; x++) {
1367 const int mb_xy = x + y * h->mb_stride;
1368 const int b_xy = 4 * x + 4 * y * h->b_stride;
1370 h->mb2b_xy[mb_xy] = b_xy;
1371 h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
1374 if (!h->dequant4_coeff[0])
1375 init_dequant_tables(h);
1378 h->DPB = av_mallocz_array(MAX_PICTURE_COUNT, sizeof(*h->DPB));
1380 return AVERROR(ENOMEM);
1381 for (i = 0; i < MAX_PICTURE_COUNT; i++)
1382 av_frame_unref(&h->DPB[i].f);
1383 av_frame_unref(&h->cur_pic.f);
1390 return AVERROR(ENOMEM);
1394 * Mimic alloc_tables(), but for every context thread.
1396 static void clone_tables(H264Context *dst, H264Context *src, int i)
1398 dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
1399 dst->non_zero_count = src->non_zero_count;
1400 dst->slice_table = src->slice_table;
1401 dst->cbp_table = src->cbp_table;
1402 dst->mb2b_xy = src->mb2b_xy;
1403 dst->mb2br_xy = src->mb2br_xy;
1404 dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
1405 dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
1406 dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
1407 dst->direct_table = src->direct_table;
1408 dst->list_counts = src->list_counts;
1409 dst->DPB = src->DPB;
1410 dst->cur_pic_ptr = src->cur_pic_ptr;
1411 dst->cur_pic = src->cur_pic;
1412 dst->bipred_scratchpad = NULL;
1413 dst->edge_emu_buffer = NULL;
1414 dst->me.scratchpad = NULL;
1415 ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
1416 src->sps.chroma_format_idc);
1421 * Allocate buffers which are not shared amongst multiple threads.
1423 static int context_init(H264Context *h)
1425 ERContext *er = &h->er;
1426 int mb_array_size = h->mb_height * h->mb_stride;
1427 int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
1428 int c_size = h->mb_stride * (h->mb_height + 1);
1429 int yc_size = y_size + 2 * c_size;
1432 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
1433 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1434 FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
1435 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
1437 h->ref_cache[0][scan8[5] + 1] =
1438 h->ref_cache[0][scan8[7] + 1] =
1439 h->ref_cache[0][scan8[13] + 1] =
1440 h->ref_cache[1][scan8[5] + 1] =
1441 h->ref_cache[1][scan8[7] + 1] =
1442 h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
1444 if (CONFIG_ERROR_RESILIENCE) {
1446 er->avctx = h->avctx;
1448 er->decode_mb = h264_er_decode_mb;
1450 er->quarter_sample = 1;
1452 er->mb_num = h->mb_num;
1453 er->mb_width = h->mb_width;
1454 er->mb_height = h->mb_height;
1455 er->mb_stride = h->mb_stride;
1456 er->b8_stride = h->mb_width * 2 + 1;
1458 FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
1459 fail); // error ressilience code looks cleaner with this
1460 for (y = 0; y < h->mb_height; y++)
1461 for (x = 0; x < h->mb_width; x++)
1462 er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
1464 er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
1465 h->mb_stride + h->mb_width;
1467 FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
1468 mb_array_size * sizeof(uint8_t), fail);
1470 FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
1471 memset(er->mbintra_table, 1, mb_array_size);
1473 FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
1475 FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
1478 FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
1479 er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
1480 er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
1481 er->dc_val[2] = er->dc_val[1] + c_size;
1482 for (i = 0; i < yc_size; i++)
1483 h->dc_val_base[i] = 1024;
1489 return AVERROR(ENOMEM); // free_tables will clean up for us
1492 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
1493 int parse_extradata);
1495 int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
1497 AVCodecContext *avctx = h->avctx;
1500 if (!buf || size <= 0)
1504 int i, cnt, nalsize;
1505 const unsigned char *p = buf;
1510 av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
1511 return AVERROR_INVALIDDATA;
1513 /* sps and pps in the avcC always have length coded with 2 bytes,
1514 * so put a fake nal_length_size = 2 while parsing them */
1515 h->nal_length_size = 2;
1516 // Decode sps from avcC
1517 cnt = *(p + 5) & 0x1f; // Number of sps
1519 for (i = 0; i < cnt; i++) {
1520 nalsize = AV_RB16(p) + 2;
1521 if(nalsize > size - (p-buf))
1522 return AVERROR_INVALIDDATA;
1523 ret = decode_nal_units(h, p, nalsize, 1);
1525 av_log(avctx, AV_LOG_ERROR,
1526 "Decoding sps %d from avcC failed\n", i);
1531 // Decode pps from avcC
1532 cnt = *(p++); // Number of pps
1533 for (i = 0; i < cnt; i++) {
1534 nalsize = AV_RB16(p) + 2;
1535 if(nalsize > size - (p-buf))
1536 return AVERROR_INVALIDDATA;
1537 ret = decode_nal_units(h, p, nalsize, 1);
1539 av_log(avctx, AV_LOG_ERROR,
1540 "Decoding pps %d from avcC failed\n", i);
1545 // Now store right nal length size, that will be used to parse all other nals
1546 h->nal_length_size = (buf[4] & 0x03) + 1;
1549 ret = decode_nal_units(h, buf, size, 1);
1556 av_cold int ff_h264_decode_init(AVCodecContext *avctx)
1558 H264Context *h = avctx->priv_data;
1564 h->bit_depth_luma = 8;
1565 h->chroma_format_idc = 1;
1567 h->avctx->bits_per_raw_sample = 8;
1568 h->cur_chroma_format_idc = 1;
1570 ff_h264dsp_init(&h->h264dsp, 8, 1);
1571 av_assert0(h->sps.bit_depth_chroma == 0);
1572 ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
1573 ff_h264qpel_init(&h->h264qpel, 8);
1574 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
1576 h->dequant_coeff_pps = -1;
1577 h->current_sps_id = -1;
1579 /* needed so that IDCT permutation is known early */
1580 if (CONFIG_ERROR_RESILIENCE)
1581 ff_dsputil_init(&h->dsp, h->avctx);
1582 ff_videodsp_init(&h->vdsp, 8);
1584 memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
1585 memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
1587 h->picture_structure = PICT_FRAME;
1588 h->slice_context_count = 1;
1589 h->workaround_bugs = avctx->workaround_bugs;
1590 h->flags = avctx->flags;
1593 // s->decode_mb = ff_h263_decode_mb;
1594 if (!avctx->has_b_frames)
1597 avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
1599 ff_h264_decode_init_vlc();
1601 ff_init_cabac_states();
1604 h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
1606 h->thread_context[0] = h;
1607 h->outputed_poc = h->next_outputed_poc = INT_MIN;
1608 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1609 h->last_pocs[i] = INT_MIN;
1610 h->prev_poc_msb = 1 << 16;
1611 h->prev_frame_num = -1;
1613 h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
1614 ff_h264_reset_sei(h);
1615 if (avctx->codec_id == AV_CODEC_ID_H264) {
1616 if (avctx->ticks_per_frame == 1) {
1617 if(h->avctx->time_base.den < INT_MAX/2) {
1618 h->avctx->time_base.den *= 2;
1620 h->avctx->time_base.num /= 2;
1622 avctx->ticks_per_frame = 2;
1625 if (avctx->extradata_size > 0 && avctx->extradata) {
1626 ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
1628 ff_h264_free_context(h);
1633 if (h->sps.bitstream_restriction_flag &&
1634 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
1635 h->avctx->has_b_frames = h->sps.num_reorder_frames;
1639 avctx->internal->allocate_progress = 1;
1646 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
1647 #undef REBASE_PICTURE
1648 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
1649 ((pic && pic >= old_ctx->DPB && \
1650 pic < old_ctx->DPB + MAX_PICTURE_COUNT) ? \
1651 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
1653 static void copy_picture_range(Picture **to, Picture **from, int count,
1654 H264Context *new_base,
1655 H264Context *old_base)
1659 for (i = 0; i < count; i++) {
1660 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
1661 IN_RANGE(from[i], old_base->DPB,
1662 sizeof(Picture) * MAX_PICTURE_COUNT) ||
1664 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
1668 static int copy_parameter_set(void **to, void **from, int count, int size)
1672 for (i = 0; i < count; i++) {
1673 if (to[i] && !from[i]) {
1675 } else if (from[i] && !to[i]) {
1676 to[i] = av_malloc(size);
1678 return AVERROR(ENOMEM);
1682 memcpy(to[i], from[i], size);
1688 static int decode_init_thread_copy(AVCodecContext *avctx)
1690 H264Context *h = avctx->priv_data;
1692 if (!avctx->internal->is_copy)
1694 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1695 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1697 h->rbsp_buffer[0] = NULL;
1698 h->rbsp_buffer[1] = NULL;
1699 h->rbsp_buffer_size[0] = 0;
1700 h->rbsp_buffer_size[1] = 0;
1701 h->context_initialized = 0;
1706 #define copy_fields(to, from, start_field, end_field) \
1707 memcpy(&to->start_field, &from->start_field, \
1708 (char *)&to->end_field - (char *)&to->start_field)
1710 static int h264_slice_header_init(H264Context *, int);
1712 static int h264_set_parameter_from_sps(H264Context *h);
1714 static int decode_update_thread_context(AVCodecContext *dst,
1715 const AVCodecContext *src)
1717 H264Context *h = dst->priv_data, *h1 = src->priv_data;
1718 int inited = h->context_initialized, err = 0;
1719 int context_reinitialized = 0;
1726 (h->width != h1->width ||
1727 h->height != h1->height ||
1728 h->mb_width != h1->mb_width ||
1729 h->mb_height != h1->mb_height ||
1730 h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
1731 h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
1732 h->sps.colorspace != h1->sps.colorspace)) {
1734 /* set bits_per_raw_sample to the previous value. the check for changed
1735 * bit depth in h264_set_parameter_from_sps() uses it and sets it to
1736 * the current value */
1737 h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
1739 av_freep(&h->bipred_scratchpad);
1741 h->width = h1->width;
1742 h->height = h1->height;
1743 h->mb_height = h1->mb_height;
1744 h->mb_width = h1->mb_width;
1745 h->mb_num = h1->mb_num;
1746 h->mb_stride = h1->mb_stride;
1747 h->b_stride = h1->b_stride;
1749 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1750 (void **)h1->sps_buffers,
1751 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1754 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1755 (void **)h1->pps_buffers,
1756 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1760 if ((err = h264_slice_header_init(h, 1)) < 0) {
1761 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
1764 context_reinitialized = 1;
1767 h264_set_parameter_from_sps(h);
1768 //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
1769 h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
1772 /* update linesize on resize for h264. The h264 decoder doesn't
1773 * necessarily call ff_MPV_frame_start in the new thread */
1774 h->linesize = h1->linesize;
1775 h->uvlinesize = h1->uvlinesize;
1777 /* copy block_offset since frame_start may not be called */
1778 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
1781 for (i = 0; i < MAX_SPS_COUNT; i++)
1782 av_freep(h->sps_buffers + i);
1784 for (i = 0; i < MAX_PPS_COUNT; i++)
1785 av_freep(h->pps_buffers + i);
1787 av_freep(&h->rbsp_buffer[0]);
1788 av_freep(&h->rbsp_buffer[1]);
1789 memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
1790 memcpy(&h->cabac, &h1->cabac,
1791 sizeof(H264Context) - offsetof(H264Context, cabac));
1792 av_assert0((void*)&h->cabac == &h->mb_padding + 1);
1794 memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
1795 memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
1797 memset(&h->er, 0, sizeof(h->er));
1798 memset(&h->me, 0, sizeof(h->me));
1799 memset(&h->mb, 0, sizeof(h->mb));
1800 memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
1801 memset(&h->mb_padding, 0, sizeof(h->mb_padding));
1805 h->qscale_table_pool = NULL;
1806 h->mb_type_pool = NULL;
1807 h->ref_index_pool = NULL;
1808 h->motion_val_pool = NULL;
1809 for (i = 0; i < 2; i++) {
1810 h->rbsp_buffer[i] = NULL;
1811 h->rbsp_buffer_size[i] = 0;
1814 if (h1->context_initialized) {
1815 h->context_initialized = 0;
1817 memset(&h->cur_pic, 0, sizeof(h->cur_pic));
1818 av_frame_unref(&h->cur_pic.f);
1819 h->cur_pic.tf.f = &h->cur_pic.f;
1821 ret = ff_h264_alloc_tables(h);
1823 av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
1826 ret = context_init(h);
1828 av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
1833 h->bipred_scratchpad = NULL;
1834 h->edge_emu_buffer = NULL;
1836 h->thread_context[0] = h;
1837 h->context_initialized = h1->context_initialized;
1840 h->avctx->coded_height = h1->avctx->coded_height;
1841 h->avctx->coded_width = h1->avctx->coded_width;
1842 h->avctx->width = h1->avctx->width;
1843 h->avctx->height = h1->avctx->height;
1844 h->coded_picture_number = h1->coded_picture_number;
1845 h->first_field = h1->first_field;
1846 h->picture_structure = h1->picture_structure;
1847 h->qscale = h1->qscale;
1848 h->droppable = h1->droppable;
1849 h->low_delay = h1->low_delay;
1851 for (i = 0; h->DPB && i < MAX_PICTURE_COUNT; i++) {
1852 unref_picture(h, &h->DPB[i]);
1853 if (h1->DPB && h1->DPB[i].f.buf[0] &&
1854 (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
1858 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
1859 unref_picture(h, &h->cur_pic);
1860 if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
1863 h->workaround_bugs = h1->workaround_bugs;
1864 h->low_delay = h1->low_delay;
1865 h->droppable = h1->droppable;
1867 // extradata/NAL handling
1868 h->is_avc = h1->is_avc;
1871 if ((ret = copy_parameter_set((void **)h->sps_buffers,
1872 (void **)h1->sps_buffers,
1873 MAX_SPS_COUNT, sizeof(SPS))) < 0)
1876 if ((ret = copy_parameter_set((void **)h->pps_buffers,
1877 (void **)h1->pps_buffers,
1878 MAX_PPS_COUNT, sizeof(PPS))) < 0)
1882 // Dequantization matrices
1883 // FIXME these are big - can they be only copied when PPS changes?
1884 copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
1886 for (i = 0; i < 6; i++)
1887 h->dequant4_coeff[i] = h->dequant4_buffer[0] +
1888 (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
1890 for (i = 0; i < 6; i++)
1891 h->dequant8_coeff[i] = h->dequant8_buffer[0] +
1892 (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
1894 h->dequant_coeff_pps = h1->dequant_coeff_pps;
1897 copy_fields(h, h1, poc_lsb, redundant_pic_count);
1900 copy_fields(h, h1, short_ref, cabac_init_idc);
1902 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
1903 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
1904 copy_picture_range(h->delayed_pic, h1->delayed_pic,
1905 MAX_DELAYED_PIC_COUNT + 2, h, h1);
1907 h->frame_recovered = h1->frame_recovered;
1909 if (context_reinitialized)
1910 h264_set_parameter_from_sps(h);
1912 if (!h->cur_pic_ptr)
1915 if (!h->droppable) {
1916 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1917 h->prev_poc_msb = h->poc_msb;
1918 h->prev_poc_lsb = h->poc_lsb;
1920 h->prev_frame_num_offset = h->frame_num_offset;
1921 h->prev_frame_num = h->frame_num;
1922 h->outputed_poc = h->next_outputed_poc;
1924 h->recovery_frame = h1->recovery_frame;
1929 static int h264_frame_start(H264Context *h)
1933 const int pixel_shift = h->pixel_shift;
1935 1<<(h->sps.bit_depth_luma-1),
1936 1<<(h->sps.bit_depth_chroma-1),
1937 1<<(h->sps.bit_depth_chroma-1),
1941 if (!ff_thread_can_start_frame(h->avctx)) {
1942 av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
1946 release_unused_pictures(h, 1);
1947 h->cur_pic_ptr = NULL;
1949 i = find_unused_picture(h);
1951 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
1956 pic->reference = h->droppable ? 0 : h->picture_structure;
1957 pic->f.coded_picture_number = h->coded_picture_number++;
1958 pic->field_picture = h->picture_structure != PICT_FRAME;
1961 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
1963 * See decode_nal_units().
1965 pic->f.key_frame = 0;
1966 pic->mmco_reset = 0;
1969 if ((ret = alloc_picture(h, pic)) < 0)
1971 if(!h->frame_recovered && !h->avctx->hwaccel &&
1972 !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
1973 avpriv_color_frame(&pic->f, c);
1975 h->cur_pic_ptr = pic;
1976 unref_picture(h, &h->cur_pic);
1977 if (CONFIG_ERROR_RESILIENCE) {
1978 h->er.cur_pic = NULL;
1981 if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
1984 if (CONFIG_ERROR_RESILIENCE) {
1985 ff_er_frame_start(&h->er);
1987 h->er.next_pic = NULL;
1990 assert(h->linesize && h->uvlinesize);
1992 for (i = 0; i < 16; i++) {
1993 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1994 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
1996 for (i = 0; i < 16; i++) {
1997 h->block_offset[16 + i] =
1998 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
1999 h->block_offset[48 + 16 + i] =
2000 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
2003 // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
2004 // h->cur_pic.reference /* || h->contains_intra */ || 1;
2006 /* We mark the current picture as non-reference after allocating it, so
2007 * that if we break out due to an error it can be released automatically
2008 * in the next ff_MPV_frame_start().
2010 h->cur_pic_ptr->reference = 0;
2012 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
2014 h->next_output_pic = NULL;
2016 assert(h->cur_pic_ptr->long_ref == 0);
2022 * Run setup operations that must be run after slice header decoding.
2023 * This includes finding the next displayed frame.
2025 * @param h h264 master context
2026 * @param setup_finished enough NALs have been read that we can call
2027 * ff_thread_finish_setup()
2029 static void decode_postinit(H264Context *h, int setup_finished)
2031 Picture *out = h->cur_pic_ptr;
2032 Picture *cur = h->cur_pic_ptr;
2033 int i, pics, out_of_order, out_idx;
2035 h->cur_pic_ptr->f.pict_type = h->pict_type;
2037 if (h->next_output_pic)
2040 if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
2041 /* FIXME: if we have two PAFF fields in one packet, we can't start
2042 * the next thread here. If we have one field per packet, we can.
2043 * The check in decode_nal_units() is not good enough to find this
2044 * yet, so we assume the worst for now. */
2045 // if (setup_finished)
2046 // ff_thread_finish_setup(h->avctx);
2050 cur->f.interlaced_frame = 0;
2051 cur->f.repeat_pict = 0;
2053 /* Signal interlacing information externally. */
2054 /* Prioritize picture timing SEI information over used
2055 * decoding process if it exists. */
2057 if (h->sps.pic_struct_present_flag) {
2058 switch (h->sei_pic_struct) {
2059 case SEI_PIC_STRUCT_FRAME:
2061 case SEI_PIC_STRUCT_TOP_FIELD:
2062 case SEI_PIC_STRUCT_BOTTOM_FIELD:
2063 cur->f.interlaced_frame = 1;
2065 case SEI_PIC_STRUCT_TOP_BOTTOM:
2066 case SEI_PIC_STRUCT_BOTTOM_TOP:
2067 if (FIELD_OR_MBAFF_PICTURE(h))
2068 cur->f.interlaced_frame = 1;
2070 // try to flag soft telecine progressive
2071 cur->f.interlaced_frame = h->prev_interlaced_frame;
2073 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
2074 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
2075 /* Signal the possibility of telecined film externally
2076 * (pic_struct 5,6). From these hints, let the applications
2077 * decide if they apply deinterlacing. */
2078 cur->f.repeat_pict = 1;
2080 case SEI_PIC_STRUCT_FRAME_DOUBLING:
2081 cur->f.repeat_pict = 2;
2083 case SEI_PIC_STRUCT_FRAME_TRIPLING:
2084 cur->f.repeat_pict = 4;
2088 if ((h->sei_ct_type & 3) &&
2089 h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
2090 cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
2092 /* Derive interlacing flag from used decoding process. */
2093 cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
2095 h->prev_interlaced_frame = cur->f.interlaced_frame;
2097 if (cur->field_poc[0] != cur->field_poc[1]) {
2098 /* Derive top_field_first from field pocs. */
2099 cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
2101 if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
2102 /* Use picture timing SEI information. Even if it is a
2103 * information of a past frame, better than nothing. */
2104 if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
2105 h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
2106 cur->f.top_field_first = 1;
2108 cur->f.top_field_first = 0;
2110 /* Most likely progressive */
2111 cur->f.top_field_first = 0;
2115 if (h->sei_frame_packing_present &&
2116 h->frame_packing_arrangement_type >= 0 &&
2117 h->frame_packing_arrangement_type <= 6 &&
2118 h->content_interpretation_type > 0 &&
2119 h->content_interpretation_type < 3) {
2120 AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
2124 switch (h->frame_packing_arrangement_type) {
2126 stereo->type = AV_STEREO3D_CHECKERBOARD;
2129 stereo->type = AV_STEREO3D_LINES;
2132 stereo->type = AV_STEREO3D_COLUMNS;
2135 if (h->quincunx_subsampling)
2136 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
2138 stereo->type = AV_STEREO3D_SIDEBYSIDE;
2141 stereo->type = AV_STEREO3D_TOPBOTTOM;
2144 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
2147 stereo->type = AV_STEREO3D_2D;
2151 if (h->content_interpretation_type == 2)
2152 stereo->flags = AV_STEREO3D_FLAG_INVERT;
2155 cur->mmco_reset = h->mmco_reset;
2158 // FIXME do something with unavailable reference frames
2160 /* Sort B-frames into display order */
2162 if (h->sps.bitstream_restriction_flag &&
2163 h->avctx->has_b_frames < h->sps.num_reorder_frames) {
2164 h->avctx->has_b_frames = h->sps.num_reorder_frames;
2168 if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
2169 !h->sps.bitstream_restriction_flag) {
2170 h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
2174 for (i = 0; 1; i++) {
2175 if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
2177 h->last_pocs[i-1] = cur->poc;
2180 h->last_pocs[i-1]= h->last_pocs[i];
2183 out_of_order = MAX_DELAYED_PIC_COUNT - i;
2184 if( cur->f.pict_type == AV_PICTURE_TYPE_B
2185 || (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))
2186 out_of_order = FFMAX(out_of_order, 1);
2187 if (out_of_order == MAX_DELAYED_PIC_COUNT) {
2188 av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
2189 for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
2190 h->last_pocs[i] = INT_MIN;
2191 h->last_pocs[0] = cur->poc;
2192 cur->mmco_reset = 1;
2193 } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
2194 av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
2195 h->avctx->has_b_frames = out_of_order;
2200 while (h->delayed_pic[pics])
2203 av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
2205 h->delayed_pic[pics++] = cur;
2206 if (cur->reference == 0)
2207 cur->reference = DELAYED_PIC_REF;
2209 out = h->delayed_pic[0];
2211 for (i = 1; h->delayed_pic[i] &&
2212 !h->delayed_pic[i]->f.key_frame &&
2213 !h->delayed_pic[i]->mmco_reset;
2215 if (h->delayed_pic[i]->poc < out->poc) {
2216 out = h->delayed_pic[i];
2219 if (h->avctx->has_b_frames == 0 &&
2220 (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
2221 h->next_outputed_poc = INT_MIN;
2222 out_of_order = out->poc < h->next_outputed_poc;
2224 if (out_of_order || pics > h->avctx->has_b_frames) {
2225 out->reference &= ~DELAYED_PIC_REF;
2226 // for frame threading, the owner must be the second field's thread or
2227 // else the first thread can release the picture and reuse it unsafely
2228 for (i = out_idx; h->delayed_pic[i]; i++)
2229 h->delayed_pic[i] = h->delayed_pic[i + 1];
2231 if (!out_of_order && pics > h->avctx->has_b_frames) {
2232 h->next_output_pic = out;
2233 if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
2234 h->next_outputed_poc = INT_MIN;
2236 h->next_outputed_poc = out->poc;
2238 av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
2241 if (h->next_output_pic) {
2242 if (h->next_output_pic->recovered) {
2243 // We have reached an recovery point and all frames after it in
2244 // display order are "recovered".
2245 h->frame_recovered |= FRAME_RECOVERED_SEI;
2247 h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
2250 if (setup_finished && !h->avctx->hwaccel)
2251 ff_thread_finish_setup(h->avctx);
2254 static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
2255 uint8_t *src_cb, uint8_t *src_cr,
2256 int linesize, int uvlinesize,
2259 uint8_t *top_border;
2261 const int pixel_shift = h->pixel_shift;
2262 int chroma444 = CHROMA444(h);
2263 int chroma422 = CHROMA422(h);
2266 src_cb -= uvlinesize;
2267 src_cr -= uvlinesize;
2269 if (!simple && FRAME_MBAFF(h)) {
2272 top_border = h->top_borders[0][h->mb_x];
2273 AV_COPY128(top_border, src_y + 15 * linesize);
2275 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
2276 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2279 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2280 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
2281 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
2282 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
2284 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
2285 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
2287 } else if (chroma422) {
2289 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
2290 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
2292 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
2293 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
2297 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
2298 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
2300 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
2301 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
2306 } else if (MB_MBAFF(h)) {
2312 top_border = h->top_borders[top_idx][h->mb_x];
2313 /* There are two lines saved, the line above the top macroblock
2314 * of a pair, and the line above the bottom macroblock. */
2315 AV_COPY128(top_border, src_y + 16 * linesize);
2317 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
2319 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2322 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
2323 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
2324 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
2325 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
2327 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
2328 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
2330 } else if (chroma422) {
2332 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
2333 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
2335 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
2336 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
2340 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
2341 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
2343 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
2344 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
2350 static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
2351 uint8_t *src_cb, uint8_t *src_cr,
2352 int linesize, int uvlinesize,
2353 int xchg, int chroma444,
2354 int simple, int pixel_shift)
2356 int deblock_topleft;
2359 uint8_t *top_border_m1;
2360 uint8_t *top_border;
2362 if (!simple && FRAME_MBAFF(h)) {
2367 top_idx = MB_MBAFF(h) ? 0 : 1;
2371 if (h->deblocking_filter == 2) {
2372 deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
2373 deblock_top = h->top_type;
2375 deblock_topleft = (h->mb_x > 0);
2376 deblock_top = (h->mb_y > !!MB_FIELD(h));
2379 src_y -= linesize + 1 + pixel_shift;
2380 src_cb -= uvlinesize + 1 + pixel_shift;
2381 src_cr -= uvlinesize + 1 + pixel_shift;
2383 top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
2384 top_border = h->top_borders[top_idx][h->mb_x];
2386 #define XCHG(a, b, xchg) \
2387 if (pixel_shift) { \
2389 AV_SWAP64(b + 0, a + 0); \
2390 AV_SWAP64(b + 8, a + 8); \
2400 if (deblock_topleft) {
2401 XCHG(top_border_m1 + (8 << pixel_shift),
2402 src_y - (7 << pixel_shift), 1);
2404 XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
2405 XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
2406 if (h->mb_x + 1 < h->mb_width) {
2407 XCHG(h->top_borders[top_idx][h->mb_x + 1],
2408 src_y + (17 << pixel_shift), 1);
2410 if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
2412 if (deblock_topleft) {
2413 XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2414 XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2416 XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
2417 XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
2418 XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
2419 XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
2420 if (h->mb_x + 1 < h->mb_width) {
2421 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
2422 XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
2425 if (deblock_topleft) {
2426 XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
2427 XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
2429 XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
2430 XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
2436 static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
2439 if (high_bit_depth) {
2440 return AV_RN32A(((int32_t *)mb) + index);
2442 return AV_RN16A(mb + index);
2445 static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
2446 int index, int value)
2448 if (high_bit_depth) {
2449 AV_WN32A(((int32_t *)mb) + index, value);
2451 AV_WN16A(mb + index, value);
2454 static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
2455 int mb_type, int is_h264,
2457 int transform_bypass,
2461 uint8_t *dest_y, int p)
2463 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2464 void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
2466 int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
2467 block_offset += 16 * p;
2468 if (IS_INTRA4x4(mb_type)) {
2469 if (IS_8x8DCT(mb_type)) {
2470 if (transform_bypass) {
2472 idct_add = h->h264dsp.h264_add_pixels8_clear;
2474 idct_dc_add = h->h264dsp.h264_idct8_dc_add;
2475 idct_add = h->h264dsp.h264_idct8_add;
2477 for (i = 0; i < 16; i += 4) {
2478 uint8_t *const ptr = dest_y + block_offset[i];
2479 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2480 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2481 h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2483 const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2484 h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
2485 (h->topright_samples_available << i) & 0x4000, linesize);
2487 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2488 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2490 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2495 if (transform_bypass) {
2497 idct_add = h->h264dsp.h264_add_pixels4_clear;
2499 idct_dc_add = h->h264dsp.h264_idct_dc_add;
2500 idct_add = h->h264dsp.h264_idct_add;
2502 for (i = 0; i < 16; i++) {
2503 uint8_t *const ptr = dest_y + block_offset[i];
2504 const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
2506 if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
2507 h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2512 if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
2513 const int topright_avail = (h->topright_samples_available << i) & 0x8000;
2514 av_assert2(h->mb_y || linesize <= block_offset[i]);
2515 if (!topright_avail) {
2517 tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
2518 topright = (uint8_t *)&tr_high;
2520 tr = ptr[3 - linesize] * 0x01010101u;
2521 topright = (uint8_t *)&tr;
2524 topright = ptr + (4 << pixel_shift) - linesize;
2528 h->hpc.pred4x4[dir](ptr, topright, linesize);
2529 nnz = h->non_zero_count_cache[scan8[i + p * 16]];
2532 if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2533 idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2535 idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
2536 } else if (CONFIG_SVQ3_DECODER)
2537 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
2543 h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
2545 if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
2546 if (!transform_bypass)
2547 h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
2549 h->dequant4_coeff[p][qscale][0]);
2551 static const uint8_t dc_mapping[16] = {
2552 0 * 16, 1 * 16, 4 * 16, 5 * 16,
2553 2 * 16, 3 * 16, 6 * 16, 7 * 16,
2554 8 * 16, 9 * 16, 12 * 16, 13 * 16,
2555 10 * 16, 11 * 16, 14 * 16, 15 * 16
2557 for (i = 0; i < 16; i++)
2558 dctcoef_set(h->mb + (p * 256 << pixel_shift),
2559 pixel_shift, dc_mapping[i],
2560 dctcoef_get(h->mb_luma_dc[p],
2564 } else if (CONFIG_SVQ3_DECODER)
2565 ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
2566 h->mb_luma_dc[p], qscale);
2570 static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
2571 int is_h264, int simple,
2572 int transform_bypass,
2576 uint8_t *dest_y, int p)
2578 void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
2580 block_offset += 16 * p;
2581 if (!IS_INTRA4x4(mb_type)) {
2583 if (IS_INTRA16x16(mb_type)) {
2584 if (transform_bypass) {
2585 if (h->sps.profile_idc == 244 &&
2586 (h->intra16x16_pred_mode == VERT_PRED8x8 ||
2587 h->intra16x16_pred_mode == HOR_PRED8x8)) {
2588 h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
2589 h->mb + (p * 256 << pixel_shift),
2592 for (i = 0; i < 16; i++)
2593 if (h->non_zero_count_cache[scan8[i + p * 16]] ||
2594 dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
2595 h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
2596 h->mb + (i * 16 + p * 256 << pixel_shift),
2600 h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
2601 h->mb + (p * 256 << pixel_shift),
2603 h->non_zero_count_cache + p * 5 * 8);
2605 } else if (h->cbp & 15) {
2606 if (transform_bypass) {
2607 const int di = IS_8x8DCT(mb_type) ? 4 : 1;
2608 idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
2609 : h->h264dsp.h264_add_pixels4_clear;
2610 for (i = 0; i < 16; i += di)
2611 if (h->non_zero_count_cache[scan8[i + p * 16]])
2612 idct_add(dest_y + block_offset[i],
2613 h->mb + (i * 16 + p * 256 << pixel_shift),
2616 if (IS_8x8DCT(mb_type))
2617 h->h264dsp.h264_idct8_add4(dest_y, block_offset,
2618 h->mb + (p * 256 << pixel_shift),
2620 h->non_zero_count_cache + p * 5 * 8);
2622 h->h264dsp.h264_idct_add16(dest_y, block_offset,
2623 h->mb + (p * 256 << pixel_shift),
2625 h->non_zero_count_cache + p * 5 * 8);
2628 } else if (CONFIG_SVQ3_DECODER) {
2629 for (i = 0; i < 16; i++)
2630 if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
2631 // FIXME benchmark weird rule, & below
2632 uint8_t *const ptr = dest_y + block_offset[i];
2633 ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
2634 h->qscale, IS_INTRA(mb_type) ? 1 : 0);
2642 #include "h264_mb_template.c"
2646 #include "h264_mb_template.c"
2650 #include "h264_mb_template.c"
2652 void ff_h264_hl_decode_mb(H264Context *h)
2654 const int mb_xy = h->mb_xy;
2655 const int mb_type = h->cur_pic.mb_type[mb_xy];
2656 int is_complex = CONFIG_SMALL || h->is_complex ||
2657 IS_INTRA_PCM(mb_type) || h->qscale == 0;
2660 if (is_complex || h->pixel_shift)
2661 hl_decode_mb_444_complex(h);
2663 hl_decode_mb_444_simple_8(h);
2664 } else if (is_complex) {
2665 hl_decode_mb_complex(h);
2666 } else if (h->pixel_shift) {
2667 hl_decode_mb_simple_16(h);
2669 hl_decode_mb_simple_8(h);
2672 int ff_pred_weight_table(H264Context *h)
2675 int luma_def, chroma_def;
2678 h->use_weight_chroma = 0;
2679 h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
2680 if (h->sps.chroma_format_idc)
2681 h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
2682 luma_def = 1 << h->luma_log2_weight_denom;
2683 chroma_def = 1 << h->chroma_log2_weight_denom;
2685 for (list = 0; list < 2; list++) {
2686 h->luma_weight_flag[list] = 0;
2687 h->chroma_weight_flag[list] = 0;
2688 for (i = 0; i < h->ref_count[list]; i++) {
2689 int luma_weight_flag, chroma_weight_flag;
2691 luma_weight_flag = get_bits1(&h->gb);
2692 if (luma_weight_flag) {
2693 h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
2694 h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
2695 if (h->luma_weight[i][list][0] != luma_def ||
2696 h->luma_weight[i][list][1] != 0) {
2698 h->luma_weight_flag[list] = 1;
2701 h->luma_weight[i][list][0] = luma_def;
2702 h->luma_weight[i][list][1] = 0;
2705 if (h->sps.chroma_format_idc) {
2706 chroma_weight_flag = get_bits1(&h->gb);
2707 if (chroma_weight_flag) {
2709 for (j = 0; j < 2; j++) {
2710 h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
2711 h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
2712 if (h->chroma_weight[i][list][j][0] != chroma_def ||
2713 h->chroma_weight[i][list][j][1] != 0) {
2714 h->use_weight_chroma = 1;
2715 h->chroma_weight_flag[list] = 1;
2720 for (j = 0; j < 2; j++) {
2721 h->chroma_weight[i][list][j][0] = chroma_def;
2722 h->chroma_weight[i][list][j][1] = 0;
2727 if (h->slice_type_nos != AV_PICTURE_TYPE_B)
2730 h->use_weight = h->use_weight || h->use_weight_chroma;
2735 * Initialize implicit_weight table.
2736 * @param field 0/1 initialize the weight for interlaced MBAFF
2737 * -1 initializes the rest
2739 static void implicit_weight_table(H264Context *h, int field)
2741 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
2743 for (i = 0; i < 2; i++) {
2744 h->luma_weight_flag[i] = 0;
2745 h->chroma_weight_flag[i] = 0;
2749 if (h->picture_structure == PICT_FRAME) {
2750 cur_poc = h->cur_pic_ptr->poc;
2752 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
2754 if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
2755 h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
2757 h->use_weight_chroma = 0;
2761 ref_count0 = h->ref_count[0];
2762 ref_count1 = h->ref_count[1];
2764 cur_poc = h->cur_pic_ptr->field_poc[field];
2766 ref_count0 = 16 + 2 * h->ref_count[0];
2767 ref_count1 = 16 + 2 * h->ref_count[1];
2771 h->use_weight_chroma = 2;
2772 h->luma_log2_weight_denom = 5;
2773 h->chroma_log2_weight_denom = 5;
2775 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
2776 int poc0 = h->ref_list[0][ref0].poc;
2777 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
2779 if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
2780 int poc1 = h->ref_list[1][ref1].poc;
2781 int td = av_clip(poc1 - poc0, -128, 127);
2783 int tb = av_clip(cur_poc - poc0, -128, 127);
2784 int tx = (16384 + (FFABS(td) >> 1)) / td;
2785 int dist_scale_factor = (tb * tx + 32) >> 8;
2786 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
2787 w = 64 - dist_scale_factor;
2791 h->implicit_weight[ref0][ref1][0] =
2792 h->implicit_weight[ref0][ref1][1] = w;
2794 h->implicit_weight[ref0][ref1][field] = w;
2801 * instantaneous decoder refresh.
2803 static void idr(H264Context *h)
2806 ff_h264_remove_all_refs(h);
2807 h->prev_frame_num = 0;
2808 h->prev_frame_num_offset = 0;
2809 h->prev_poc_msb = 1<<16;
2810 h->prev_poc_lsb = 0;
2811 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
2812 h->last_pocs[i] = INT_MIN;
2815 /* forget old pics after a seek */
2816 static void flush_change(H264Context *h)
2820 h->outputed_poc = h->next_outputed_poc = INT_MIN;
2821 h->prev_interlaced_frame = 1;
2824 h->prev_frame_num = -1;
2825 if (h->cur_pic_ptr) {
2826 h->cur_pic_ptr->reference = 0;
2827 for (j=i=0; h->delayed_pic[i]; i++)
2828 if (h->delayed_pic[i] != h->cur_pic_ptr)
2829 h->delayed_pic[j++] = h->delayed_pic[i];
2830 h->delayed_pic[j] = NULL;
2833 memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
2834 memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
2835 memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
2836 memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
2837 ff_h264_reset_sei(h);
2838 h->recovery_frame = -1;
2839 h->frame_recovered = 0;
2841 h->current_slice = 0;
2845 /* forget old pics after a seek */
2846 static void flush_dpb(AVCodecContext *avctx)
2848 H264Context *h = avctx->priv_data;
2851 for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
2852 if (h->delayed_pic[i])
2853 h->delayed_pic[i]->reference = 0;
2854 h->delayed_pic[i] = NULL;
2860 for (i = 0; i < MAX_PICTURE_COUNT; i++)
2861 unref_picture(h, &h->DPB[i]);
2862 h->cur_pic_ptr = NULL;
2863 unref_picture(h, &h->cur_pic);
2865 h->mb_x = h->mb_y = 0;
2867 h->parse_context.state = -1;
2868 h->parse_context.frame_start_found = 0;
2869 h->parse_context.overread = 0;
2870 h->parse_context.overread_index = 0;
2871 h->parse_context.index = 0;
2872 h->parse_context.last_index = 0;
2875 h->context_initialized = 0;
2878 int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
2880 const int max_frame_num = 1 << h->sps.log2_max_frame_num;
2883 h->frame_num_offset = h->prev_frame_num_offset;
2884 if (h->frame_num < h->prev_frame_num)
2885 h->frame_num_offset += max_frame_num;
2887 if (h->sps.poc_type == 0) {
2888 const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
2890 if (h->poc_lsb < h->prev_poc_lsb &&
2891 h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
2892 h->poc_msb = h->prev_poc_msb + max_poc_lsb;
2893 else if (h->poc_lsb > h->prev_poc_lsb &&
2894 h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
2895 h->poc_msb = h->prev_poc_msb - max_poc_lsb;
2897 h->poc_msb = h->prev_poc_msb;
2899 field_poc[1] = h->poc_msb + h->poc_lsb;
2900 if (h->picture_structure == PICT_FRAME)
2901 field_poc[1] += h->delta_poc_bottom;
2902 } else if (h->sps.poc_type == 1) {
2903 int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
2906 if (h->sps.poc_cycle_length != 0)
2907 abs_frame_num = h->frame_num_offset + h->frame_num;
2911 if (h->nal_ref_idc == 0 && abs_frame_num > 0)
2914 expected_delta_per_poc_cycle = 0;
2915 for (i = 0; i < h->sps.poc_cycle_length; i++)
2916 // FIXME integrate during sps parse
2917 expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
2919 if (abs_frame_num > 0) {
2920 int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
2921 int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
2923 expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
2924 for (i = 0; i <= frame_num_in_poc_cycle; i++)
2925 expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
2929 if (h->nal_ref_idc == 0)
2930 expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
2932 field_poc[0] = expectedpoc + h->delta_poc[0];
2933 field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
2935 if (h->picture_structure == PICT_FRAME)
2936 field_poc[1] += h->delta_poc[1];
2938 int poc = 2 * (h->frame_num_offset + h->frame_num);
2940 if (!h->nal_ref_idc)
2947 if (h->picture_structure != PICT_BOTTOM_FIELD)
2948 pic_field_poc[0] = field_poc[0];
2949 if (h->picture_structure != PICT_TOP_FIELD)
2950 pic_field_poc[1] = field_poc[1];
2951 *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
2957 * initialize scan tables
2959 static void init_scan_tables(H264Context *h)
2962 for (i = 0; i < 16; i++) {
2963 #define T(x) (x >> 2) | ((x << 2) & 0xF)
2964 h->zigzag_scan[i] = T(zigzag_scan[i]);
2965 h->field_scan[i] = T(field_scan[i]);
2968 for (i = 0; i < 64; i++) {
2969 #define T(x) (x >> 3) | ((x & 7) << 3)
2970 h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
2971 h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
2972 h->field_scan8x8[i] = T(field_scan8x8[i]);
2973 h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
2976 if (h->sps.transform_bypass) { // FIXME same ugly
2977 memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2978 memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
2979 memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2980 memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
2981 memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2982 memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2984 memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
2985 memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
2986 memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
2987 memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
2988 memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
2989 memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
2993 static int field_end(H264Context *h, int in_setup)
2995 AVCodecContext *const avctx = h->avctx;
2999 if (CONFIG_H264_VDPAU_DECODER &&
3000 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3001 ff_vdpau_h264_set_reference_frames(h);
3003 if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
3004 if (!h->droppable) {
3005 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3006 h->prev_poc_msb = h->poc_msb;
3007 h->prev_poc_lsb = h->poc_lsb;
3009 h->prev_frame_num_offset = h->frame_num_offset;
3010 h->prev_frame_num = h->frame_num;
3011 h->outputed_poc = h->next_outputed_poc;
3014 if (avctx->hwaccel) {
3015 if (avctx->hwaccel->end_frame(avctx) < 0)
3016 av_log(avctx, AV_LOG_ERROR,
3017 "hardware accelerator failed to decode picture\n");
3020 if (CONFIG_H264_VDPAU_DECODER &&
3021 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
3022 ff_vdpau_h264_picture_complete(h);
3025 * FIXME: Error handling code does not seem to support interlaced
3026 * when slices span multiple rows
3027 * The ff_er_add_slice calls don't work right for bottom
3028 * fields; they cause massive erroneous error concealing
3029 * Error marking covers both fields (top and bottom).
3030 * This causes a mismatched s->error_count
3031 * and a bad error table. Further, the error count goes to
3032 * INT_MAX when called for bottom field, because mb_y is
3033 * past end by one (callers fault) and resync_mb_y != 0
3034 * causes problems for the first MB line, too.
3036 if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
3037 h->er.cur_pic = h->cur_pic_ptr;
3038 ff_er_frame_end(&h->er);
3040 if (!in_setup && !h->droppable)
3041 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3042 h->picture_structure == PICT_BOTTOM_FIELD);
3045 h->current_slice = 0;
3051 * Replicate H264 "master" context to thread contexts.
3053 static int clone_slice(H264Context *dst, H264Context *src)
3055 memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
3056 dst->cur_pic_ptr = src->cur_pic_ptr;
3057 dst->cur_pic = src->cur_pic;
3058 dst->linesize = src->linesize;
3059 dst->uvlinesize = src->uvlinesize;
3060 dst->first_field = src->first_field;
3062 dst->prev_poc_msb = src->prev_poc_msb;
3063 dst->prev_poc_lsb = src->prev_poc_lsb;
3064 dst->prev_frame_num_offset = src->prev_frame_num_offset;
3065 dst->prev_frame_num = src->prev_frame_num;
3066 dst->short_ref_count = src->short_ref_count;
3068 memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
3069 memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
3070 memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
3072 memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
3073 memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
3079 * Compute profile from profile_idc and constraint_set?_flags.
3083 * @return profile as defined by FF_PROFILE_H264_*
3085 int ff_h264_get_profile(SPS *sps)
3087 int profile = sps->profile_idc;
3089 switch (sps->profile_idc) {
3090 case FF_PROFILE_H264_BASELINE:
3091 // constraint_set1_flag set to 1
3092 profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
3094 case FF_PROFILE_H264_HIGH_10:
3095 case FF_PROFILE_H264_HIGH_422:
3096 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
3097 // constraint_set3_flag set to 1
3098 profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
3105 static int h264_set_parameter_from_sps(H264Context *h)
3107 if (h->flags & CODEC_FLAG_LOW_DELAY ||
3108 (h->sps.bitstream_restriction_flag &&
3109 !h->sps.num_reorder_frames)) {
3110 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
3111 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
3112 "Reenabling low delay requires a codec flush.\n");
3117 if (h->avctx->has_b_frames < 2)
3118 h->avctx->has_b_frames = !h->low_delay;
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 ref_count[2], list_count;
3382 int num_ref_idx_active_override_flag;
3384 // set defaults, might be overridden a few lines later
3385 ref_count[0] = h->pps.ref_count[0];
3386 ref_count[1] = h->pps.ref_count[1];
3388 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3390 max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
3392 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3393 h->direct_spatial_mv_pred = get_bits1(&h->gb);
3394 num_ref_idx_active_override_flag = get_bits1(&h->gb);
3396 if (num_ref_idx_active_override_flag) {
3397 ref_count[0] = get_ue_golomb(&h->gb) + 1;
3398 if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
3399 ref_count[1] = get_ue_golomb(&h->gb) + 1;
3401 // full range is spec-ok in this case, even for frames
3405 if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
3406 av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]);
3407 h->ref_count[0] = h->ref_count[1] = 0;
3409 return AVERROR_INVALIDDATA;
3412 if (h->slice_type_nos == AV_PICTURE_TYPE_B)
3418 ref_count[0] = ref_count[1] = 0;
3421 if (list_count != h->list_count ||
3422 ref_count[0] != h->ref_count[0] ||
3423 ref_count[1] != h->ref_count[1]) {
3424 h->ref_count[0] = ref_count[0];
3425 h->ref_count[1] = ref_count[1];
3426 h->list_count = list_count;
3434 * Decode a slice header.
3435 * This will also call ff_MPV_common_init() and frame_start() as needed.
3437 * @param h h264context
3438 * @param h0 h264 master context (differs from 'h' when doing sliced based
3439 * parallel decoding)
3441 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
3443 static int decode_slice_header(H264Context *h, H264Context *h0)
3445 unsigned int first_mb_in_slice;
3446 unsigned int pps_id;
3448 unsigned int slice_type, tmp, i, j;
3449 int last_pic_structure, last_pic_droppable;
3451 int needs_reinit = 0;
3452 int field_pic_flag, bottom_field_flag;
3454 h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
3455 h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
3457 first_mb_in_slice = get_ue_golomb_long(&h->gb);
3459 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
3460 if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
3464 h0->current_slice = 0;
3465 if (!h0->first_field) {
3466 if (h->cur_pic_ptr && !h->droppable) {
3467 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
3468 h->picture_structure == PICT_BOTTOM_FIELD);
3470 h->cur_pic_ptr = NULL;
3474 slice_type = get_ue_golomb_31(&h->gb);
3475 if (slice_type > 9) {
3476 av_log(h->avctx, AV_LOG_ERROR,
3477 "slice type too large (%d) at %d %d\n",
3478 slice_type, h->mb_x, h->mb_y);
3479 return AVERROR_INVALIDDATA;
3481 if (slice_type > 4) {
3483 h->slice_type_fixed = 1;
3485 h->slice_type_fixed = 0;
3487 slice_type = golomb_to_pict_type[slice_type];
3488 h->slice_type = slice_type;
3489 h->slice_type_nos = slice_type & 3;
3491 if (h->nal_unit_type == NAL_IDR_SLICE &&
3492 h->slice_type_nos != AV_PICTURE_TYPE_I) {
3493 av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
3494 return AVERROR_INVALIDDATA;
3497 // to make a few old functions happy, it's wrong though
3498 h->pict_type = h->slice_type;
3500 pps_id = get_ue_golomb(&h->gb);
3501 if (pps_id >= MAX_PPS_COUNT) {
3502 av_log(h->avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
3503 return AVERROR_INVALIDDATA;
3505 if (!h0->pps_buffers[pps_id]) {
3506 av_log(h->avctx, AV_LOG_ERROR,
3507 "non-existing PPS %u referenced\n",
3509 return AVERROR_INVALIDDATA;
3511 if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {
3512 av_log(h->avctx, AV_LOG_ERROR,
3513 "PPS change from %d to %d forbidden\n",
3514 h0->au_pps_id, pps_id);
3515 return AVERROR_INVALIDDATA;
3517 h->pps = *h0->pps_buffers[pps_id];
3519 if (!h0->sps_buffers[h->pps.sps_id]) {
3520 av_log(h->avctx, AV_LOG_ERROR,
3521 "non-existing SPS %u referenced\n",
3523 return AVERROR_INVALIDDATA;
3526 if (h->pps.sps_id != h->current_sps_id ||
3527 h0->sps_buffers[h->pps.sps_id]->new) {
3529 h->sps = *h0->sps_buffers[h->pps.sps_id];
3531 if (h->mb_width != h->sps.mb_width ||
3532 h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
3533 h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
3534 h->cur_chroma_format_idc != h->sps.chroma_format_idc
3538 if (h->bit_depth_luma != h->sps.bit_depth_luma ||
3539 h->chroma_format_idc != h->sps.chroma_format_idc) {
3540 h->bit_depth_luma = h->sps.bit_depth_luma;
3541 h->chroma_format_idc = h->sps.chroma_format_idc;
3544 if ((ret = h264_set_parameter_from_sps(h)) < 0)
3548 h->avctx->profile = ff_h264_get_profile(&h->sps);
3549 h->avctx->level = h->sps.level_idc;
3550 h->avctx->refs = h->sps.ref_frame_count;
3552 must_reinit = (h->context_initialized &&
3553 ( 16*h->sps.mb_width != h->avctx->coded_width
3554 || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
3555 || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
3556 || h->cur_chroma_format_idc != h->sps.chroma_format_idc
3557 || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
3558 || h->mb_width != h->sps.mb_width
3559 || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
3561 if (h0->avctx->pix_fmt != get_pixel_format(h0, 0))
3564 h->mb_width = h->sps.mb_width;
3565 h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
3566 h->mb_num = h->mb_width * h->mb_height;
3567 h->mb_stride = h->mb_width + 1;
3569 h->b_stride = h->mb_width * 4;
3571 h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
3573 h->width = 16 * h->mb_width;
3574 h->height = 16 * h->mb_height;
3576 ret = init_dimensions(h);
3580 if (h->sps.video_signal_type_present_flag) {
3581 h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
3583 if (h->sps.colour_description_present_flag) {
3584 if (h->avctx->colorspace != h->sps.colorspace)
3586 h->avctx->color_primaries = h->sps.color_primaries;
3587 h->avctx->color_trc = h->sps.color_trc;
3588 h->avctx->colorspace = h->sps.colorspace;
3592 if (h->context_initialized &&
3593 (h->width != h->avctx->coded_width ||
3594 h->height != h->avctx->coded_height ||
3598 av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
3599 "slice %d\n", h0->current_slice + 1);
3600 return AVERROR_INVALIDDATA;
3605 if ((ret = get_pixel_format(h, 1)) < 0)
3607 h->avctx->pix_fmt = ret;
3609 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
3610 "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
3612 if ((ret = h264_slice_header_init(h, 1)) < 0) {
3613 av_log(h->avctx, AV_LOG_ERROR,
3614 "h264_slice_header_init() failed\n");
3618 if (!h->context_initialized) {
3620 av_log(h->avctx, AV_LOG_ERROR,
3621 "Cannot (re-)initialize context during parallel decoding.\n");
3622 return AVERROR_PATCHWELCOME;
3625 if ((ret = get_pixel_format(h, 1)) < 0)
3627 h->avctx->pix_fmt = ret;
3629 if ((ret = h264_slice_header_init(h, 0)) < 0) {
3630 av_log(h->avctx, AV_LOG_ERROR,
3631 "h264_slice_header_init() failed\n");
3636 if (h == h0 && h->dequant_coeff_pps != pps_id) {
3637 h->dequant_coeff_pps = pps_id;
3638 init_dequant_tables(h);
3641 h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
3644 h->mb_aff_frame = 0;
3645 last_pic_structure = h0->picture_structure;
3646 last_pic_droppable = h0->droppable;
3647 h->droppable = h->nal_ref_idc == 0;
3648 if (h->sps.frame_mbs_only_flag) {
3649 h->picture_structure = PICT_FRAME;
3651 if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
3652 av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
3655 field_pic_flag = get_bits1(&h->gb);
3656 if (field_pic_flag) {
3657 bottom_field_flag = get_bits1(&h->gb);
3658 h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
3660 h->picture_structure = PICT_FRAME;
3661 h->mb_aff_frame = h->sps.mb_aff;
3664 h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
3666 if (h0->current_slice != 0) {
3667 if (last_pic_structure != h->picture_structure ||
3668 last_pic_droppable != h->droppable) {
3669 av_log(h->avctx, AV_LOG_ERROR,
3670 "Changing field mode (%d -> %d) between slices is not allowed\n",
3671 last_pic_structure, h->picture_structure);
3672 h->picture_structure = last_pic_structure;
3673 h->droppable = last_pic_droppable;
3674 return AVERROR_INVALIDDATA;
3675 } else if (!h0->cur_pic_ptr) {
3676 av_log(h->avctx, AV_LOG_ERROR,
3677 "unset cur_pic_ptr on %d. slice\n",
3678 h0->current_slice + 1);
3679 return AVERROR_INVALIDDATA;
3682 /* Shorten frame num gaps so we don't have to allocate reference
3683 * frames just to throw them away */
3684 if (h->frame_num != h->prev_frame_num) {
3685 int unwrap_prev_frame_num = h->prev_frame_num;
3686 int max_frame_num = 1 << h->sps.log2_max_frame_num;
3688 if (unwrap_prev_frame_num > h->frame_num)
3689 unwrap_prev_frame_num -= max_frame_num;
3691 if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
3692 unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
3693 if (unwrap_prev_frame_num < 0)
3694 unwrap_prev_frame_num += max_frame_num;
3696 h->prev_frame_num = unwrap_prev_frame_num;
3700 /* See if we have a decoded first field looking for a pair...
3701 * Here, we're using that to see if we should mark previously
3702 * decode frames as "finished".
3703 * We have to do that before the "dummy" in-between frame allocation,
3704 * since that can modify h->cur_pic_ptr. */
3705 if (h0->first_field) {
3706 assert(h0->cur_pic_ptr);
3707 assert(h0->cur_pic_ptr->f.buf[0]);
3708 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3710 /* Mark old field/frame as completed */
3711 if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
3712 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3713 last_pic_structure == PICT_BOTTOM_FIELD);
3716 /* figure out if we have a complementary field pair */
3717 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3718 /* Previous field is unmatched. Don't display it, but let it
3719 * remain for reference if marked as such. */
3720 if (last_pic_structure != PICT_FRAME) {
3721 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3722 last_pic_structure == PICT_TOP_FIELD);
3725 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3726 /* This and previous field were reference, but had
3727 * different frame_nums. Consider this field first in
3728 * pair. Throw away previous field except for reference
3730 if (last_pic_structure != PICT_FRAME) {
3731 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3732 last_pic_structure == PICT_TOP_FIELD);
3735 /* Second field in complementary pair */
3736 if (!((last_pic_structure == PICT_TOP_FIELD &&
3737 h->picture_structure == PICT_BOTTOM_FIELD) ||
3738 (last_pic_structure == PICT_BOTTOM_FIELD &&
3739 h->picture_structure == PICT_TOP_FIELD))) {
3740 av_log(h->avctx, AV_LOG_ERROR,
3741 "Invalid field mode combination %d/%d\n",
3742 last_pic_structure, h->picture_structure);
3743 h->picture_structure = last_pic_structure;
3744 h->droppable = last_pic_droppable;
3745 return AVERROR_INVALIDDATA;
3746 } else if (last_pic_droppable != h->droppable) {
3747 avpriv_request_sample(h->avctx,
3748 "Found reference and non-reference fields in the same frame, which");
3749 h->picture_structure = last_pic_structure;
3750 h->droppable = last_pic_droppable;
3751 return AVERROR_PATCHWELCOME;
3757 while (h->frame_num != h->prev_frame_num && !h0->first_field &&
3758 h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
3759 Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
3760 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
3761 h->frame_num, h->prev_frame_num);
3762 if (!h->sps.gaps_in_frame_num_allowed_flag)
3763 for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
3764 h->last_pocs[i] = INT_MIN;
3765 ret = h264_frame_start(h);
3767 h0->first_field = 0;
3771 h->prev_frame_num++;
3772 h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
3773 h->cur_pic_ptr->frame_num = h->prev_frame_num;
3774 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
3775 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
3776 ret = ff_generate_sliding_window_mmcos(h, 1);
3777 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3779 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
3780 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3782 /* Error concealment: If a ref is missing, copy the previous ref
3784 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
3785 * many assumptions about there being no actual duplicates.
3786 * FIXME: This does not copy padding for out-of-frame motion
3787 * vectors. Given we are concealing a lost frame, this probably
3788 * is not noticeable by comparison, but it should be fixed. */
3789 if (h->short_ref_count) {
3791 av_image_copy(h->short_ref[0]->f.data,
3792 h->short_ref[0]->f.linesize,
3793 (const uint8_t **)prev->f.data,
3798 h->short_ref[0]->poc = prev->poc + 2;
3800 h->short_ref[0]->frame_num = h->prev_frame_num;
3804 /* See if we have a decoded first field looking for a pair...
3805 * We're using that to see whether to continue decoding in that
3806 * frame, or to allocate a new one. */
3807 if (h0->first_field) {
3808 assert(h0->cur_pic_ptr);
3809 assert(h0->cur_pic_ptr->f.buf[0]);
3810 assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
3812 /* figure out if we have a complementary field pair */
3813 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
3814 /* Previous field is unmatched. Don't display it, but let it
3815 * remain for reference if marked as such. */
3816 h0->cur_pic_ptr = NULL;
3817 h0->first_field = FIELD_PICTURE(h);
3819 if (h0->cur_pic_ptr->frame_num != h->frame_num) {
3820 ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
3821 h0->picture_structure==PICT_BOTTOM_FIELD);
3822 /* This and the previous field had different frame_nums.
3823 * Consider this field first in pair. Throw away previous
3824 * one except for reference purposes. */
3825 h0->first_field = 1;
3826 h0->cur_pic_ptr = NULL;
3828 /* Second field in complementary pair */
3829 h0->first_field = 0;
3833 /* Frame or first field in a potentially complementary pair */
3834 h0->first_field = FIELD_PICTURE(h);
3837 if (!FIELD_PICTURE(h) || h0->first_field) {
3838 if (h264_frame_start(h) < 0) {
3839 h0->first_field = 0;
3840 return AVERROR_INVALIDDATA;
3843 release_unused_pictures(h, 0);
3845 /* Some macroblocks can be accessed before they're available in case
3846 * of lost slices, MBAFF or threading. */
3847 if (FIELD_PICTURE(h)) {
3848 for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
3849 memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
3851 memset(h->slice_table, -1,
3852 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
3854 h0->last_slice_type = -1;
3856 if (h != h0 && (ret = clone_slice(h, h0)) < 0)
3859 /* can't be in alloc_tables because linesize isn't known there.
3860 * FIXME: redo bipred weight to not require extra buffer? */
3861 for (i = 0; i < h->slice_context_count; i++)
3862 if (h->thread_context[i]) {
3863 ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
3868 h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
3870 av_assert1(h->mb_num == h->mb_width * h->mb_height);
3871 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
3872 first_mb_in_slice >= h->mb_num) {
3873 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
3874 return AVERROR_INVALIDDATA;
3876 h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
3877 h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
3878 FIELD_OR_MBAFF_PICTURE(h);
3879 if (h->picture_structure == PICT_BOTTOM_FIELD)
3880 h->resync_mb_y = h->mb_y = h->mb_y + 1;
3881 av_assert1(h->mb_y < h->mb_height);
3883 if (h->picture_structure == PICT_FRAME) {
3884 h->curr_pic_num = h->frame_num;
3885 h->max_pic_num = 1 << h->sps.log2_max_frame_num;
3887 h->curr_pic_num = 2 * h->frame_num + 1;
3888 h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
3891 if (h->nal_unit_type == NAL_IDR_SLICE)
3892 get_ue_golomb(&h->gb); /* idr_pic_id */
3894 if (h->sps.poc_type == 0) {
3895 h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
3897 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3898 h->delta_poc_bottom = get_se_golomb(&h->gb);
3901 if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
3902 h->delta_poc[0] = get_se_golomb(&h->gb);
3904 if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
3905 h->delta_poc[1] = get_se_golomb(&h->gb);
3908 ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
3910 if (h->pps.redundant_pic_cnt_present)
3911 h->redundant_pic_count = get_ue_golomb(&h->gb);
3913 ret = ff_set_ref_count(h);
3917 if (slice_type != AV_PICTURE_TYPE_I &&
3918 (h0->current_slice == 0 ||
3919 slice_type != h0->last_slice_type ||
3920 memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
3922 ff_h264_fill_default_ref_list(h);
3925 if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
3926 ret = ff_h264_decode_ref_pic_list_reordering(h);
3928 h->ref_count[1] = h->ref_count[0] = 0;
3933 if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
3934 (h->pps.weighted_bipred_idc == 1 &&
3935 h->slice_type_nos == AV_PICTURE_TYPE_B))
3936 ff_pred_weight_table(h);
3937 else if (h->pps.weighted_bipred_idc == 2 &&
3938 h->slice_type_nos == AV_PICTURE_TYPE_B) {
3939 implicit_weight_table(h, -1);
3942 for (i = 0; i < 2; i++) {
3943 h->luma_weight_flag[i] = 0;
3944 h->chroma_weight_flag[i] = 0;
3948 // If frame-mt is enabled, only update mmco tables for the first slice
3949 // in a field. Subsequent slices can temporarily clobber h->mmco_index
3950 // or h->mmco, which will cause ref list mix-ups and decoding errors
3951 // further down the line. This may break decoding if the first slice is
3952 // corrupt, thus we only do this if frame-mt is enabled.
3953 if (h->nal_ref_idc) {
3954 ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
3955 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
3956 h0->current_slice == 0);
3957 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
3958 return AVERROR_INVALIDDATA;
3961 if (FRAME_MBAFF(h)) {
3962 ff_h264_fill_mbaff_ref_list(h);
3964 if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
3965 implicit_weight_table(h, 0);
3966 implicit_weight_table(h, 1);
3970 if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
3971 ff_h264_direct_dist_scale_factor(h);
3972 ff_h264_direct_ref_list_init(h);
3974 if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
3975 tmp = get_ue_golomb_31(&h->gb);
3977 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
3978 return AVERROR_INVALIDDATA;
3980 h->cabac_init_idc = tmp;
3983 h->last_qscale_diff = 0;
3984 tmp = h->pps.init_qp + get_se_golomb(&h->gb);
3985 if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
3986 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
3987 return AVERROR_INVALIDDATA;
3990 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
3991 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
3992 // FIXME qscale / qp ... stuff
3993 if (h->slice_type == AV_PICTURE_TYPE_SP)
3994 get_bits1(&h->gb); /* sp_for_switch_flag */
3995 if (h->slice_type == AV_PICTURE_TYPE_SP ||
3996 h->slice_type == AV_PICTURE_TYPE_SI)
3997 get_se_golomb(&h->gb); /* slice_qs_delta */
3999 h->deblocking_filter = 1;
4000 h->slice_alpha_c0_offset = 52;
4001 h->slice_beta_offset = 52;
4002 if (h->pps.deblocking_filter_parameters_present) {
4003 tmp = get_ue_golomb_31(&h->gb);
4005 av_log(h->avctx, AV_LOG_ERROR,
4006 "deblocking_filter_idc %u out of range\n", tmp);
4007 return AVERROR_INVALIDDATA;
4009 h->deblocking_filter = tmp;
4010 if (h->deblocking_filter < 2)
4011 h->deblocking_filter ^= 1; // 1<->0
4013 if (h->deblocking_filter) {
4014 h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
4015 h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
4016 if (h->slice_alpha_c0_offset > 104U ||
4017 h->slice_beta_offset > 104U) {
4018 av_log(h->avctx, AV_LOG_ERROR,
4019 "deblocking filter parameters %d %d out of range\n",
4020 h->slice_alpha_c0_offset, h->slice_beta_offset);
4021 return AVERROR_INVALIDDATA;
4026 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
4027 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
4028 h->slice_type_nos != AV_PICTURE_TYPE_I) ||
4029 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
4030 h->slice_type_nos == AV_PICTURE_TYPE_B) ||
4031 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
4032 h->nal_ref_idc == 0))
4033 h->deblocking_filter = 0;
4035 if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
4036 if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
4037 /* Cheat slightly for speed:
4038 * Do not bother to deblock across slices. */
4039 h->deblocking_filter = 2;
4041 h0->max_contexts = 1;
4042 if (!h0->single_decode_warning) {
4043 av_log(h->avctx, AV_LOG_INFO,
4044 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
4045 h0->single_decode_warning = 1;
4048 av_log(h->avctx, AV_LOG_ERROR,
4049 "Deblocking switched inside frame.\n");
4054 h->qp_thresh = 15 + 52 -
4055 FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
4057 h->pps.chroma_qp_index_offset[0],
4058 h->pps.chroma_qp_index_offset[1]) +
4059 6 * (h->sps.bit_depth_luma - 8);
4061 h0->last_slice_type = slice_type;
4062 memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
4063 h->slice_num = ++h0->current_slice;
4066 h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
4067 if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
4068 && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
4069 && h->slice_num >= MAX_SLICES) {
4070 //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
4071 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);
4074 for (j = 0; j < 2; j++) {
4076 int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
4077 for (i = 0; i < 16; i++) {
4079 if (j < h->list_count && i < h->ref_count[j] &&
4080 h->ref_list[j][i].f.buf[0]) {
4082 AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
4083 for (k = 0; k < h->short_ref_count; k++)
4084 if (h->short_ref[k]->f.buf[0]->buffer == buf) {
4088 for (k = 0; k < h->long_ref_count; k++)
4089 if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
4090 id_list[i] = h->short_ref_count + k;
4098 for (i = 0; i < 16; i++)
4099 ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
4101 ref2frm[18 + 1] = -1;
4102 for (i = 16; i < 48; i++)
4103 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
4104 (h->ref_list[j][i].reference & 3);
4107 if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0];
4108 if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0];
4109 h->er.ref_count = h->ref_count[0];
4110 h0->au_pps_id = pps_id;
4112 h0->sps_buffers[h->pps.sps_id]->new = 0;
4113 h->current_sps_id = h->pps.sps_id;
4115 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
4116 av_log(h->avctx, AV_LOG_DEBUG,
4117 "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",
4119 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
4121 av_get_picture_type_char(h->slice_type),
4122 h->slice_type_fixed ? " fix" : "",
4123 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
4124 pps_id, h->frame_num,
4125 h->cur_pic_ptr->field_poc[0],
4126 h->cur_pic_ptr->field_poc[1],
4127 h->ref_count[0], h->ref_count[1],
4129 h->deblocking_filter,
4130 h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
4132 h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
4133 h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
4139 int ff_h264_get_slice_type(const H264Context *h)
4141 switch (h->slice_type) {
4142 case AV_PICTURE_TYPE_P:
4144 case AV_PICTURE_TYPE_B:
4146 case AV_PICTURE_TYPE_I:
4148 case AV_PICTURE_TYPE_SP:
4150 case AV_PICTURE_TYPE_SI:
4153 return AVERROR_INVALIDDATA;
4157 static av_always_inline void fill_filter_caches_inter(H264Context *h,
4158 int mb_type, int top_xy,
4159 int left_xy[LEFT_MBS],
4161 int left_type[LEFT_MBS],
4162 int mb_xy, int list)
4164 int b_stride = h->b_stride;
4165 int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
4166 int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
4167 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
4168 if (USES_LIST(top_type, list)) {
4169 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
4170 const int b8_xy = 4 * top_xy + 2;
4171 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4172 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
4173 ref_cache[0 - 1 * 8] =
4174 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
4175 ref_cache[2 - 1 * 8] =
4176 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
4178 AV_ZERO128(mv_dst - 1 * 8);
4179 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4182 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
4183 if (USES_LIST(left_type[LTOP], list)) {
4184 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
4185 const int b8_xy = 4 * left_xy[LTOP] + 1;
4186 int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4187 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
4188 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
4189 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
4190 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
4192 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
4193 ref_cache[-1 + 16] =
4194 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
4196 AV_ZERO32(mv_dst - 1 + 0);
4197 AV_ZERO32(mv_dst - 1 + 8);
4198 AV_ZERO32(mv_dst - 1 + 16);
4199 AV_ZERO32(mv_dst - 1 + 24);
4202 ref_cache[-1 + 16] =
4203 ref_cache[-1 + 24] = LIST_NOT_USED;
4208 if (!USES_LIST(mb_type, list)) {
4209 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
4210 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4211 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4212 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4213 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
4218 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
4219 int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
4220 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
4221 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
4222 AV_WN32A(&ref_cache[0 * 8], ref01);
4223 AV_WN32A(&ref_cache[1 * 8], ref01);
4224 AV_WN32A(&ref_cache[2 * 8], ref23);
4225 AV_WN32A(&ref_cache[3 * 8], ref23);
4229 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
4230 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
4231 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
4232 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
4233 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
4239 * @return non zero if the loop filter can be skipped
4241 static int fill_filter_caches(H264Context *h, int mb_type)
4243 const int mb_xy = h->mb_xy;
4244 int top_xy, left_xy[LEFT_MBS];
4245 int top_type, left_type[LEFT_MBS];
4249 top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
4251 /* Wow, what a mess, why didn't they simplify the interlacing & intra
4252 * stuff, I can't imagine that these complex rules are worth it. */
4254 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
4255 if (FRAME_MBAFF(h)) {
4256 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
4257 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
4259 if (left_mb_field_flag != curr_mb_field_flag)
4260 left_xy[LTOP] -= h->mb_stride;
4262 if (curr_mb_field_flag)
4263 top_xy += h->mb_stride &
4264 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
4265 if (left_mb_field_flag != curr_mb_field_flag)
4266 left_xy[LBOT] += h->mb_stride;
4270 h->top_mb_xy = top_xy;
4271 h->left_mb_xy[LTOP] = left_xy[LTOP];
4272 h->left_mb_xy[LBOT] = left_xy[LBOT];
4274 /* For sufficiently low qp, filtering wouldn't do anything.
4275 * This is a conservative estimate: could also check beta_offset
4276 * and more accurate chroma_qp. */
4277 int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
4278 int qp = h->cur_pic.qscale_table[mb_xy];
4279 if (qp <= qp_thresh &&
4280 (left_xy[LTOP] < 0 ||
4281 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
4283 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
4284 if (!FRAME_MBAFF(h))
4286 if ((left_xy[LTOP] < 0 ||
4287 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
4288 (top_xy < h->mb_stride ||
4289 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
4294 top_type = h->cur_pic.mb_type[top_xy];
4295 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
4296 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
4297 if (h->deblocking_filter == 2) {
4298 if (h->slice_table[top_xy] != h->slice_num)
4300 if (h->slice_table[left_xy[LBOT]] != h->slice_num)
4301 left_type[LTOP] = left_type[LBOT] = 0;
4303 if (h->slice_table[top_xy] == 0xFFFF)
4305 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
4306 left_type[LTOP] = left_type[LBOT] = 0;
4308 h->top_type = top_type;
4309 h->left_type[LTOP] = left_type[LTOP];
4310 h->left_type[LBOT] = left_type[LBOT];
4312 if (IS_INTRA(mb_type))
4315 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4316 top_type, left_type, mb_xy, 0);
4317 if (h->list_count == 2)
4318 fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
4319 top_type, left_type, mb_xy, 1);
4321 nnz = h->non_zero_count[mb_xy];
4322 nnz_cache = h->non_zero_count_cache;
4323 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
4324 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
4325 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
4326 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
4327 h->cbp = h->cbp_table[mb_xy];
4330 nnz = h->non_zero_count[top_xy];
4331 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
4334 if (left_type[LTOP]) {
4335 nnz = h->non_zero_count[left_xy[LTOP]];
4336 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
4337 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
4338 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
4339 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
4342 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
4343 * from what the loop filter needs */
4344 if (!CABAC(h) && h->pps.transform_8x8_mode) {
4345 if (IS_8x8DCT(top_type)) {
4346 nnz_cache[4 + 8 * 0] =
4347 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
4348 nnz_cache[6 + 8 * 0] =
4349 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
4351 if (IS_8x8DCT(left_type[LTOP])) {
4352 nnz_cache[3 + 8 * 1] =
4353 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
4355 if (IS_8x8DCT(left_type[LBOT])) {
4356 nnz_cache[3 + 8 * 3] =
4357 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
4360 if (IS_8x8DCT(mb_type)) {
4361 nnz_cache[scan8[0]] =
4362 nnz_cache[scan8[1]] =
4363 nnz_cache[scan8[2]] =
4364 nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
4366 nnz_cache[scan8[0 + 4]] =
4367 nnz_cache[scan8[1 + 4]] =
4368 nnz_cache[scan8[2 + 4]] =
4369 nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
4371 nnz_cache[scan8[0 + 8]] =
4372 nnz_cache[scan8[1 + 8]] =
4373 nnz_cache[scan8[2 + 8]] =
4374 nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
4376 nnz_cache[scan8[0 + 12]] =
4377 nnz_cache[scan8[1 + 12]] =
4378 nnz_cache[scan8[2 + 12]] =
4379 nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
4386 static void loop_filter(H264Context *h, int start_x, int end_x)
4388 uint8_t *dest_y, *dest_cb, *dest_cr;
4389 int linesize, uvlinesize, mb_x, mb_y;
4390 const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
4391 const int old_slice_type = h->slice_type;
4392 const int pixel_shift = h->pixel_shift;
4393 const int block_h = 16 >> h->chroma_y_shift;
4395 if (h->deblocking_filter) {
4396 for (mb_x = start_x; mb_x < end_x; mb_x++)
4397 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
4399 mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
4400 h->slice_num = h->slice_table[mb_xy];
4401 mb_type = h->cur_pic.mb_type[mb_xy];
4402 h->list_count = h->list_counts[mb_xy];
4406 h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
4410 dest_y = h->cur_pic.f.data[0] +
4411 ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
4412 dest_cb = h->cur_pic.f.data[1] +
4413 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4414 mb_y * h->uvlinesize * block_h;
4415 dest_cr = h->cur_pic.f.data[2] +
4416 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
4417 mb_y * h->uvlinesize * block_h;
4418 // FIXME simplify above
4421 linesize = h->mb_linesize = h->linesize * 2;
4422 uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
4423 if (mb_y & 1) { // FIXME move out of this function?
4424 dest_y -= h->linesize * 15;
4425 dest_cb -= h->uvlinesize * (block_h - 1);
4426 dest_cr -= h->uvlinesize * (block_h - 1);
4429 linesize = h->mb_linesize = h->linesize;
4430 uvlinesize = h->mb_uvlinesize = h->uvlinesize;
4432 backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
4434 if (fill_filter_caches(h, mb_type))
4436 h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
4437 h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
4439 if (FRAME_MBAFF(h)) {
4440 ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
4441 linesize, uvlinesize);
4443 ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
4444 dest_cr, linesize, uvlinesize);
4448 h->slice_type = old_slice_type;
4450 h->mb_y = end_mb_y - FRAME_MBAFF(h);
4451 h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
4452 h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
4455 static void predict_field_decoding_flag(H264Context *h)
4457 const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
4458 int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
4459 h->cur_pic.mb_type[mb_xy - 1] :
4460 (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
4461 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
4462 h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
4466 * Draw edges and report progress for the last MB row.
4468 static void decode_finish_row(H264Context *h)
4470 int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
4471 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
4472 int height = 16 << FRAME_MBAFF(h);
4473 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
4475 if (h->deblocking_filter) {
4476 if ((top + height) >= pic_height)
4477 height += deblock_border;
4478 top -= deblock_border;
4481 if (top >= pic_height || (top + height) < 0)
4484 height = FFMIN(height, pic_height - top);
4486 height = top + height;
4490 ff_h264_draw_horiz_band(h, top, height);
4492 if (h->droppable || h->er.error_occurred)
4495 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
4496 h->picture_structure == PICT_BOTTOM_FIELD);
4499 static void er_add_slice(H264Context *h, int startx, int starty,
4500 int endx, int endy, int status)
4502 if (CONFIG_ERROR_RESILIENCE) {
4503 ERContext *er = &h->er;
4505 ff_er_add_slice(er, startx, starty, endx, endy, status);
4509 static int decode_slice(struct AVCodecContext *avctx, void *arg)
4511 H264Context *h = *(void **)arg;
4512 int lf_x_start = h->mb_x;
4514 h->mb_skip_run = -1;
4516 av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
4518 h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
4519 avctx->codec_id != AV_CODEC_ID_H264 ||
4520 (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
4522 if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
4523 const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
4525 int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
4526 prev_status &= ~ VP_START;
4527 if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
4528 h->er.error_occurred = 1;
4534 align_get_bits(&h->gb);
4537 ff_init_cabac_decoder(&h->cabac,
4538 h->gb.buffer + get_bits_count(&h->gb) / 8,
4539 (get_bits_left(&h->gb) + 7) / 8);
4541 ff_h264_init_cabac_states(h);
4545 int ret = ff_h264_decode_mb_cabac(h);
4547 // STOP_TIMER("decode_mb_cabac")
4550 ff_h264_hl_decode_mb(h);
4552 // FIXME optimal? or let mb_decode decode 16x32 ?
4553 if (ret >= 0 && FRAME_MBAFF(h)) {
4556 ret = ff_h264_decode_mb_cabac(h);
4559 ff_h264_hl_decode_mb(h);
4562 eos = get_cabac_terminate(&h->cabac);
4564 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
4565 h->cabac.bytestream > h->cabac.bytestream_end + 2) {
4566 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4567 h->mb_y, ER_MB_END);
4568 if (h->mb_x >= lf_x_start)
4569 loop_filter(h, lf_x_start, h->mb_x + 1);
4572 if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
4573 av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
4574 if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
4575 av_log(h->avctx, AV_LOG_ERROR,
4576 "error while decoding MB %d %d, bytestream (%td)\n",
4578 h->cabac.bytestream_end - h->cabac.bytestream);
4579 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4580 h->mb_y, ER_MB_ERROR);
4581 return AVERROR_INVALIDDATA;
4584 if (++h->mb_x >= h->mb_width) {
4585 loop_filter(h, lf_x_start, h->mb_x);
4586 h->mb_x = lf_x_start = 0;
4587 decode_finish_row(h);
4589 if (FIELD_OR_MBAFF_PICTURE(h)) {
4591 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4592 predict_field_decoding_flag(h);
4596 if (eos || h->mb_y >= h->mb_height) {
4597 tprintf(h->avctx, "slice end %d %d\n",
4598 get_bits_count(&h->gb), h->gb.size_in_bits);
4599 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
4600 h->mb_y, ER_MB_END);
4601 if (h->mb_x > lf_x_start)
4602 loop_filter(h, lf_x_start, h->mb_x);
4608 int ret = ff_h264_decode_mb_cavlc(h);
4611 ff_h264_hl_decode_mb(h);
4613 // FIXME optimal? or let mb_decode decode 16x32 ?
4614 if (ret >= 0 && FRAME_MBAFF(h)) {
4616 ret = ff_h264_decode_mb_cavlc(h);
4619 ff_h264_hl_decode_mb(h);
4624 av_log(h->avctx, AV_LOG_ERROR,
4625 "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
4626 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4627 h->mb_y, ER_MB_ERROR);
4631 if (++h->mb_x >= h->mb_width) {
4632 loop_filter(h, lf_x_start, h->mb_x);
4633 h->mb_x = lf_x_start = 0;
4634 decode_finish_row(h);
4636 if (FIELD_OR_MBAFF_PICTURE(h)) {
4638 if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
4639 predict_field_decoding_flag(h);
4641 if (h->mb_y >= h->mb_height) {
4642 tprintf(h->avctx, "slice end %d %d\n",
4643 get_bits_count(&h->gb), h->gb.size_in_bits);
4645 if ( get_bits_left(&h->gb) == 0
4646 || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
4647 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4648 h->mb_x - 1, h->mb_y,
4653 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4657 return AVERROR_INVALIDDATA;
4662 if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
4663 tprintf(h->avctx, "slice end %d %d\n",
4664 get_bits_count(&h->gb), h->gb.size_in_bits);
4666 if (get_bits_left(&h->gb) == 0) {
4667 er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
4668 h->mb_x - 1, h->mb_y,
4670 if (h->mb_x > lf_x_start)
4671 loop_filter(h, lf_x_start, h->mb_x);
4675 er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
4676 h->mb_y, ER_MB_ERROR);
4678 return AVERROR_INVALIDDATA;
4686 * Call decode_slice() for each context.
4688 * @param h h264 master context
4689 * @param context_count number of contexts to execute
4691 static int execute_decode_slices(H264Context *h, int context_count)
4693 AVCodecContext *const avctx = h->avctx;
4697 av_assert0(h->mb_y < h->mb_height);
4699 if (h->avctx->hwaccel ||
4700 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4702 if (context_count == 1) {
4703 return decode_slice(avctx, &h);
4705 av_assert0(context_count > 0);
4706 for (i = 1; i < context_count; i++) {
4707 hx = h->thread_context[i];
4708 if (CONFIG_ERROR_RESILIENCE) {
4709 hx->er.error_count = 0;
4711 hx->x264_build = h->x264_build;
4714 avctx->execute(avctx, decode_slice, h->thread_context,
4715 NULL, context_count, sizeof(void *));
4717 /* pull back stuff from slices to master context */
4718 hx = h->thread_context[context_count - 1];
4721 h->droppable = hx->droppable;
4722 h->picture_structure = hx->picture_structure;
4723 if (CONFIG_ERROR_RESILIENCE) {
4724 for (i = 1; i < context_count; i++)
4725 h->er.error_count += h->thread_context[i]->er.error_count;
4732 static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
4734 static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
4735 int parse_extradata)
4737 AVCodecContext *const avctx = h->avctx;
4738 H264Context *hx; ///< thread context
4742 int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
4743 int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
4746 int first_slice = 0;
4749 h->nal_unit_type= 0;
4751 if(!h->slice_context_count)
4752 h->slice_context_count= 1;
4753 h->max_contexts = h->slice_context_count;
4754 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
4755 h->current_slice = 0;
4756 if (!h->first_field)
4757 h->cur_pic_ptr = NULL;
4758 ff_h264_reset_sei(h);
4761 if (h->nal_length_size == 4) {
4762 if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
4764 }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
4768 for (; pass <= 1; pass++) {
4771 next_avc = h->is_avc ? 0 : buf_size;
4781 if (buf_index >= next_avc) {
4782 if (buf_index >= buf_size - h->nal_length_size)
4785 for (i = 0; i < h->nal_length_size; i++)
4786 nalsize = (nalsize << 8) | buf[buf_index++];
4787 if (nalsize <= 0 || nalsize > buf_size - buf_index) {
4788 av_log(h->avctx, AV_LOG_ERROR,
4789 "AVC: nal size %d\n", nalsize);
4792 next_avc = buf_index + nalsize;
4794 // start code prefix search
4795 for (; buf_index + 3 < next_avc; buf_index++)
4796 // This should always succeed in the first iteration.
4797 if (buf[buf_index] == 0 &&
4798 buf[buf_index + 1] == 0 &&
4799 buf[buf_index + 2] == 1)
4802 if (buf_index + 3 >= buf_size) {
4803 buf_index = buf_size;
4808 if (buf_index >= next_avc)
4812 hx = h->thread_context[context_count];
4814 ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
4815 &consumed, next_avc - buf_index);
4816 if (ptr == NULL || dst_length < 0) {
4820 i = buf_index + consumed;
4821 if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
4822 buf[i] == 0x00 && buf[i + 1] == 0x00 &&
4823 buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
4824 h->workaround_bugs |= FF_BUG_TRUNCATED;
4826 if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
4827 while (dst_length > 0 && ptr[dst_length - 1] == 0)
4829 bit_length = !dst_length ? 0
4831 decode_rbsp_trailing(h, ptr + dst_length - 1));
4833 if (h->avctx->debug & FF_DEBUG_STARTCODE)
4834 av_log(h->avctx, AV_LOG_DEBUG,
4835 "NAL %d/%d at %d/%d length %d pass %d\n",
4836 hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
4838 if (h->is_avc && (nalsize != consumed) && nalsize)
4839 av_log(h->avctx, AV_LOG_DEBUG,
4840 "AVC: Consumed only %d bytes instead of %d\n",
4843 buf_index += consumed;
4847 /* packets can sometimes contain multiple PPS/SPS,
4848 * e.g. two PAFF field pictures in one packet, or a demuxer
4849 * which splits NALs strangely if so, when frame threading we
4850 * can't start the next thread until we've read all of them */
4851 switch (hx->nal_unit_type) {
4854 nals_needed = nal_index;
4859 init_get_bits(&hx->gb, ptr, bit_length);
4860 if (!get_ue_golomb(&hx->gb) || !first_slice)
4861 nals_needed = nal_index;
4863 first_slice = hx->nal_unit_type;
4869 switch (hx->nal_unit_type) {
4873 first_slice = hx->nal_unit_type;
4876 if (avctx->skip_frame >= AVDISCARD_NONREF &&
4877 h->nal_ref_idc == 0 &&
4878 h->nal_unit_type != NAL_SEI)
4882 if ( !(avctx->active_thread_type & FF_THREAD_FRAME)
4883 || nals_needed >= nal_index)
4885 /* Ignore per frame NAL unit type during extradata
4886 * parsing. Decoding slices is not possible in codec init
4888 if (parse_extradata) {
4889 switch (hx->nal_unit_type) {
4895 av_log(h->avctx, AV_LOG_WARNING,
4896 "Ignoring NAL %d in global header/extradata\n",
4898 // fall through to next case
4899 case NAL_AUXILIARY_SLICE:
4900 hx->nal_unit_type = NAL_FF_IGNORE;
4906 switch (hx->nal_unit_type) {
4908 if (first_slice != NAL_IDR_SLICE) {
4909 av_log(h->avctx, AV_LOG_ERROR,
4910 "Invalid mix of idr and non-idr slices\n");
4915 idr(h); // FIXME ensure we don't lose some frames if there is reordering
4918 init_get_bits(&hx->gb, ptr, bit_length);
4920 hx->inter_gb_ptr = &hx->gb;
4921 hx->data_partitioning = 0;
4923 if ((err = decode_slice_header(hx, h)))
4926 if (h->sei_recovery_frame_cnt >= 0) {
4927 if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
4928 h->valid_recovery_point = 1;
4930 if ( h->recovery_frame < 0
4931 || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
4932 h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
4933 ((1 << h->sps.log2_max_frame_num) - 1);
4935 if (!h->valid_recovery_point)
4936 h->recovery_frame = h->frame_num;
4940 h->cur_pic_ptr->f.key_frame |=
4941 (hx->nal_unit_type == NAL_IDR_SLICE);
4943 if (hx->nal_unit_type == NAL_IDR_SLICE ||
4944 h->recovery_frame == h->frame_num) {
4945 h->recovery_frame = -1;
4946 h->cur_pic_ptr->recovered = 1;
4948 // If we have an IDR, all frames after it in decoded order are
4950 if (hx->nal_unit_type == NAL_IDR_SLICE)
4951 h->frame_recovered |= FRAME_RECOVERED_IDR;
4952 h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
4953 h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
4955 h->cur_pic_ptr->recovered |= h->frame_recovered;
4957 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
4960 if (h->current_slice == 1) {
4961 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
4962 decode_postinit(h, nal_index >= nals_needed);
4964 if (h->avctx->hwaccel &&
4965 (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
4967 if (CONFIG_H264_VDPAU_DECODER &&
4968 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
4969 ff_vdpau_h264_picture_start(h);
4972 if (hx->redundant_pic_count == 0 &&
4973 (avctx->skip_frame < AVDISCARD_NONREF ||
4975 (avctx->skip_frame < AVDISCARD_BIDIR ||
4976 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
4977 (avctx->skip_frame < AVDISCARD_NONKEY ||
4978 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
4979 avctx->skip_frame < AVDISCARD_ALL) {
4980 if (avctx->hwaccel) {
4981 ret = avctx->hwaccel->decode_slice(avctx,
4982 &buf[buf_index - consumed],
4986 } else if (CONFIG_H264_VDPAU_DECODER &&
4987 h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
4988 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4990 sizeof(start_code));
4991 ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
4992 &buf[buf_index - consumed],
4999 if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
5000 av_log(h->avctx, AV_LOG_ERROR,
5001 "Decoding in chunks is not supported for "
5002 "partitioned slices.\n");
5003 return AVERROR(ENOSYS);
5006 init_get_bits(&hx->gb, ptr, bit_length);
5008 hx->inter_gb_ptr = NULL;
5010 if ((err = decode_slice_header(hx, h)) < 0) {
5011 /* make sure data_partitioning is cleared if it was set
5012 * before, so we don't try decoding a slice without a valid
5013 * slice header later */
5014 h->data_partitioning = 0;
5018 hx->data_partitioning = 1;
5021 init_get_bits(&hx->intra_gb, ptr, bit_length);
5022 hx->intra_gb_ptr = &hx->intra_gb;
5025 init_get_bits(&hx->inter_gb, ptr, bit_length);
5026 hx->inter_gb_ptr = &hx->inter_gb;
5028 av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
5031 if (hx->redundant_pic_count == 0 &&
5033 hx->data_partitioning &&
5034 h->cur_pic_ptr && h->context_initialized &&
5035 (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
5036 (avctx->skip_frame < AVDISCARD_BIDIR ||
5037 hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
5038 (avctx->skip_frame < AVDISCARD_NONKEY ||
5039 hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
5040 avctx->skip_frame < AVDISCARD_ALL)
5044 init_get_bits(&h->gb, ptr, bit_length);
5045 ff_h264_decode_sei(h);
5048 init_get_bits(&h->gb, ptr, bit_length);
5049 if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
5050 av_log(h->avctx, AV_LOG_DEBUG,
5051 "SPS decoding failure, trying again with the complete NAL\n");
5053 av_assert0(next_avc - buf_index + consumed == nalsize);
5054 if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
5056 init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
5057 8*(next_avc - buf_index + consumed - 1));
5058 ff_h264_decode_seq_parameter_set(h);
5063 init_get_bits(&h->gb, ptr, bit_length);
5064 ff_h264_decode_picture_parameter_set(h, bit_length);
5067 case NAL_END_SEQUENCE:
5068 case NAL_END_STREAM:
5069 case NAL_FILLER_DATA:
5071 case NAL_AUXILIARY_SLICE:
5076 av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
5077 hx->nal_unit_type, bit_length);
5080 if (context_count == h->max_contexts) {
5081 execute_decode_slices(h, context_count);
5086 av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
5087 h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
5088 } else if (err == 1) {
5089 /* Slice could not be decoded in parallel mode, copy down
5090 * NAL unit stuff to context 0 and restart. Note that
5091 * rbsp_buffer is not transferred, but since we no longer
5092 * run in parallel mode this should not be an issue. */
5093 h->nal_unit_type = hx->nal_unit_type;
5094 h->nal_ref_idc = hx->nal_ref_idc;
5101 execute_decode_slices(h, context_count);
5105 if (h->cur_pic_ptr && !h->droppable) {
5106 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
5107 h->picture_structure == PICT_BOTTOM_FIELD);
5110 return (ret < 0) ? ret : buf_index;
5114 * Return the number of bytes consumed for building the current frame.
5116 static int get_consumed_bytes(int pos, int buf_size)
5119 pos = 1; // avoid infinite loops (i doubt that is needed but ...)
5120 if (pos + 10 > buf_size)
5121 pos = buf_size; // oops ;)
5126 static int output_frame(H264Context *h, AVFrame *dst, Picture *srcp)
5128 AVFrame *src = &srcp->f;
5130 int ret = av_frame_ref(dst, src);
5134 av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
5139 for (i = 0; i < 3; i++) {
5140 int hshift = (i > 0) ? h->chroma_x_shift : 0;
5141 int vshift = (i > 0) ? h->chroma_y_shift : 0;
5142 int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
5143 (srcp->crop_top >> vshift) * dst->linesize[i];
5144 dst->data[i] += off;
5149 static int h264_decode_frame(AVCodecContext *avctx, void *data,
5150 int *got_frame, AVPacket *avpkt)
5152 const uint8_t *buf = avpkt->data;
5153 int buf_size = avpkt->size;
5154 H264Context *h = avctx->priv_data;
5155 AVFrame *pict = data;
5161 h->flags = avctx->flags;
5162 /* reset data partitioning here, to ensure GetBitContexts from previous
5163 * packets do not get used. */
5164 h->data_partitioning = 0;
5166 /* end of stream, output what is still in the buffers */
5167 if (buf_size == 0) {
5170 h->cur_pic_ptr = NULL;
5173 // FIXME factorize this with the output code below
5174 out = h->delayed_pic[0];
5177 h->delayed_pic[i] &&
5178 !h->delayed_pic[i]->f.key_frame &&
5179 !h->delayed_pic[i]->mmco_reset;
5181 if (h->delayed_pic[i]->poc < out->poc) {
5182 out = h->delayed_pic[i];
5186 for (i = out_idx; h->delayed_pic[i]; i++)
5187 h->delayed_pic[i] = h->delayed_pic[i + 1];
5190 out->reference &= ~DELAYED_PIC_REF;
5191 ret = output_frame(h, pict, out);
5199 if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
5200 int cnt= buf[5]&0x1f;
5201 const uint8_t *p= buf+6;
5203 int nalsize= AV_RB16(p) + 2;
5204 if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
5212 int nalsize= AV_RB16(p) + 2;
5213 if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
5218 return ff_h264_decode_extradata(h, buf, buf_size);
5222 buf_index = decode_nal_units(h, buf, buf_size, 0);
5224 return AVERROR_INVALIDDATA;
5226 if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
5227 av_assert0(buf_index <= buf_size);
5231 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
5232 if (avctx->skip_frame >= AVDISCARD_NONREF ||
5233 buf_size >= 4 && !memcmp("Q264", buf, 4))
5235 av_log(avctx, AV_LOG_ERROR, "no frame!\n");
5236 return AVERROR_INVALIDDATA;
5239 if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
5240 (h->mb_y >= h->mb_height && h->mb_height)) {
5241 if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
5242 decode_postinit(h, 1);
5246 /* Wait for second field. */
5248 if (h->next_output_pic && (
5249 h->next_output_pic->recovered)) {
5250 if (!h->next_output_pic->recovered)
5251 h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
5253 ret = output_frame(h, pict, h->next_output_pic);
5257 if (CONFIG_MPEGVIDEO) {
5258 ff_print_debug_info2(h->avctx, h->next_output_pic, pict, h->er.mbskip_table,
5260 h->mb_width, h->mb_height, h->mb_stride, 1);
5265 assert(pict->buf[0] || !*got_frame);
5267 return get_consumed_bytes(buf_index, buf_size);
5270 av_cold void ff_h264_free_context(H264Context *h)
5274 free_tables(h, 1); // FIXME cleanup init stuff perhaps
5276 for (i = 0; i < MAX_SPS_COUNT; i++)
5277 av_freep(h->sps_buffers + i);
5279 for (i = 0; i < MAX_PPS_COUNT; i++)
5280 av_freep(h->pps_buffers + i);
5283 static av_cold int h264_decode_end(AVCodecContext *avctx)
5285 H264Context *h = avctx->priv_data;
5287 ff_h264_remove_all_refs(h);
5288 ff_h264_free_context(h);
5290 unref_picture(h, &h->cur_pic);
5295 static const AVProfile profiles[] = {
5296 { FF_PROFILE_H264_BASELINE, "Baseline" },
5297 { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
5298 { FF_PROFILE_H264_MAIN, "Main" },
5299 { FF_PROFILE_H264_EXTENDED, "Extended" },
5300 { FF_PROFILE_H264_HIGH, "High" },
5301 { FF_PROFILE_H264_HIGH_10, "High 10" },
5302 { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
5303 { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
5304 { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
5305 { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
5306 { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
5307 { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
5308 { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
5309 { FF_PROFILE_UNKNOWN },
5312 static const AVOption h264_options[] = {
5313 {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
5314 {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
5318 static const AVClass h264_class = {
5319 .class_name = "H264 Decoder",
5320 .item_name = av_default_item_name,
5321 .option = h264_options,
5322 .version = LIBAVUTIL_VERSION_INT,
5325 static const AVClass h264_vdpau_class = {
5326 .class_name = "H264 VDPAU Decoder",
5327 .item_name = av_default_item_name,
5328 .option = h264_options,
5329 .version = LIBAVUTIL_VERSION_INT,
5332 AVCodec ff_h264_decoder = {
5334 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
5335 .type = AVMEDIA_TYPE_VIDEO,
5336 .id = AV_CODEC_ID_H264,
5337 .priv_data_size = sizeof(H264Context),
5338 .init = ff_h264_decode_init,
5339 .close = h264_decode_end,
5340 .decode = h264_decode_frame,
5341 .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
5342 CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
5343 CODEC_CAP_FRAME_THREADS,
5345 .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
5346 .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
5347 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5348 .priv_class = &h264_class,
5351 #if CONFIG_H264_VDPAU_DECODER
5352 AVCodec ff_h264_vdpau_decoder = {
5353 .name = "h264_vdpau",
5354 .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
5355 .type = AVMEDIA_TYPE_VIDEO,
5356 .id = AV_CODEC_ID_H264,
5357 .priv_data_size = sizeof(H264Context),
5358 .init = ff_h264_decode_init,
5359 .close = h264_decode_end,
5360 .decode = h264_decode_frame,
5361 .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
5363 .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
5365 .profiles = NULL_IF_CONFIG_SMALL(profiles),
5366 .priv_class = &h264_vdpau_class,