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 Libav.
7 * Libav 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 * Libav 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 Libav; 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 #include "libavutil/avassert.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/timer.h"
33 #include "cabac_functions.h"
34 #include "error_resilience.h"
38 #include "h264chroma.h"
39 #include "h264_mvpred.h"
42 #include "mpegutils.h"
43 #include "rectangle.h"
46 static const uint8_t field_scan[16] = {
47 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
48 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
49 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
50 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
53 static const uint8_t field_scan8x8[64] = {
54 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
55 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
56 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
57 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
58 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
59 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
60 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
61 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
62 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
63 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
64 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
65 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
66 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
67 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
68 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
69 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
72 static const uint8_t field_scan8x8_cavlc[64] = {
73 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
74 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
75 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
76 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
77 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
78 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
79 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
80 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
81 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
82 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
83 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
84 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
85 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
86 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
87 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
88 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
91 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
92 static const uint8_t zigzag_scan8x8_cavlc[64] = {
93 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
94 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
95 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
96 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
97 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
98 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
99 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
100 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
101 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
102 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
103 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
104 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
105 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
106 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
107 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
108 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
111 static void release_unused_pictures(H264Context *h, int remove_current)
115 /* release non reference frames */
116 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
117 if (h->DPB[i].f->buf[0] && !h->DPB[i].reference &&
118 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
119 ff_h264_unref_picture(h, &h->DPB[i]);
124 static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
126 const H264Context *h = sl->h264;
127 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
129 av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
130 // edge emu needs blocksize + filter length - 1
131 // (= 21x21 for h264)
132 av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
134 av_fast_malloc(&sl->top_borders[0], &sl->top_borders_allocated[0],
135 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
136 av_fast_malloc(&sl->top_borders[1], &sl->top_borders_allocated[1],
137 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
139 if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
140 !sl->top_borders[0] || !sl->top_borders[1]) {
141 av_freep(&sl->bipred_scratchpad);
142 av_freep(&sl->edge_emu_buffer);
143 av_freep(&sl->top_borders[0]);
144 av_freep(&sl->top_borders[1]);
146 sl->bipred_scratchpad_allocated = 0;
147 sl->edge_emu_buffer_allocated = 0;
148 sl->top_borders_allocated[0] = 0;
149 sl->top_borders_allocated[1] = 0;
150 return AVERROR(ENOMEM);
156 static int init_table_pools(H264Context *h)
158 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
159 const int mb_array_size = h->mb_stride * h->mb_height;
160 const int b4_stride = h->mb_width * 4 + 1;
161 const int b4_array_size = b4_stride * h->mb_height * 4;
163 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
165 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
166 sizeof(uint32_t), av_buffer_allocz);
167 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
168 sizeof(int16_t), av_buffer_allocz);
169 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
171 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
172 !h->ref_index_pool) {
173 av_buffer_pool_uninit(&h->qscale_table_pool);
174 av_buffer_pool_uninit(&h->mb_type_pool);
175 av_buffer_pool_uninit(&h->motion_val_pool);
176 av_buffer_pool_uninit(&h->ref_index_pool);
177 return AVERROR(ENOMEM);
183 static int alloc_picture(H264Context *h, H264Picture *pic)
187 av_assert0(!pic->f->data[0]);
190 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
191 AV_GET_BUFFER_FLAG_REF : 0);
195 if (h->avctx->hwaccel) {
196 const AVHWAccel *hwaccel = h->avctx->hwaccel;
197 av_assert0(!pic->hwaccel_picture_private);
198 if (hwaccel->frame_priv_data_size) {
199 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
200 if (!pic->hwaccel_priv_buf)
201 return AVERROR(ENOMEM);
202 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
206 if (!h->qscale_table_pool) {
207 ret = init_table_pools(h);
212 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
213 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
214 if (!pic->qscale_table_buf || !pic->mb_type_buf)
217 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
218 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
220 for (i = 0; i < 2; i++) {
221 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
222 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
223 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
226 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
227 pic->ref_index[i] = pic->ref_index_buf[i]->data;
232 ff_h264_unref_picture(h, pic);
233 return (ret < 0) ? ret : AVERROR(ENOMEM);
236 static inline int pic_is_unused(H264Context *h, H264Picture *pic)
243 static int find_unused_picture(H264Context *h)
247 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
248 if (pic_is_unused(h, &h->DPB[i]))
251 if (i == H264_MAX_PICTURE_COUNT)
252 return AVERROR_INVALIDDATA;
257 static int initialize_cur_frame(H264Context *h)
262 release_unused_pictures(h, 1);
263 ff_h264_unref_picture(h, &h->cur_pic);
264 h->cur_pic_ptr = NULL;
266 ret = find_unused_picture(h);
268 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
273 ret = alloc_picture(h, cur);
277 ret = ff_h264_ref_picture(h, &h->cur_pic, cur);
280 h->cur_pic_ptr = cur;
285 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
287 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
288 ((pic && pic >= old_ctx->DPB && \
289 pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
290 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
292 static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
293 H264Context *new_base,
294 H264Context *old_base)
298 for (i = 0; i < count; i++) {
299 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
300 IN_RANGE(from[i], old_base->DPB,
301 sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
303 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
307 #define copy_fields(to, from, start_field, end_field) \
308 memcpy(&to->start_field, &from->start_field, \
309 (char *)&to->end_field - (char *)&to->start_field)
311 static int h264_slice_header_init(H264Context *h);
313 int ff_h264_update_thread_context(AVCodecContext *dst,
314 const AVCodecContext *src)
316 H264Context *h = dst->priv_data, *h1 = src->priv_data;
317 int inited = h->context_initialized, err = 0;
321 if (dst == src || !h1->context_initialized)
325 return AVERROR_INVALIDDATA;
328 (h->width != h1->width ||
329 h->height != h1->height ||
330 h->mb_width != h1->mb_width ||
331 h->mb_height != h1->mb_height ||
333 h->ps.sps->bit_depth_luma != h1->ps.sps->bit_depth_luma ||
334 h->ps.sps->chroma_format_idc != h1->ps.sps->chroma_format_idc ||
335 h->ps.sps->colorspace != h1->ps.sps->colorspace)) {
340 for (i = 0; i < FF_ARRAY_ELEMS(h->ps.sps_list); i++) {
341 av_buffer_unref(&h->ps.sps_list[i]);
342 if (h1->ps.sps_list[i]) {
343 h->ps.sps_list[i] = av_buffer_ref(h1->ps.sps_list[i]);
344 if (!h->ps.sps_list[i])
345 return AVERROR(ENOMEM);
348 for (i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++) {
349 av_buffer_unref(&h->ps.pps_list[i]);
350 if (h1->ps.pps_list[i]) {
351 h->ps.pps_list[i] = av_buffer_ref(h1->ps.pps_list[i]);
352 if (!h->ps.pps_list[i])
353 return AVERROR(ENOMEM);
357 h->ps.sps = h1->ps.sps;
359 if (need_reinit || !inited) {
360 h->width = h1->width;
361 h->height = h1->height;
362 h->mb_height = h1->mb_height;
363 h->mb_width = h1->mb_width;
364 h->mb_num = h1->mb_num;
365 h->mb_stride = h1->mb_stride;
366 h->b_stride = h1->b_stride;
368 if ((err = h264_slice_header_init(h)) < 0) {
369 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
373 /* copy block_offset since frame_start may not be called */
374 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
377 h->avctx->coded_height = h1->avctx->coded_height;
378 h->avctx->coded_width = h1->avctx->coded_width;
379 h->avctx->width = h1->avctx->width;
380 h->avctx->height = h1->avctx->height;
381 h->coded_picture_number = h1->coded_picture_number;
382 h->first_field = h1->first_field;
383 h->picture_structure = h1->picture_structure;
384 h->droppable = h1->droppable;
385 h->low_delay = h1->low_delay;
387 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
388 ff_h264_unref_picture(h, &h->DPB[i]);
389 if (h1->DPB[i].f->buf[0] &&
390 (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
394 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
395 ff_h264_unref_picture(h, &h->cur_pic);
396 if (h1->cur_pic.f->buf[0]) {
397 ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
402 h->enable_er = h1->enable_er;
403 h->workaround_bugs = h1->workaround_bugs;
404 h->low_delay = h1->low_delay;
405 h->droppable = h1->droppable;
407 // extradata/NAL handling
408 h->is_avc = h1->is_avc;
409 h->nal_length_size = h1->nal_length_size;
412 copy_fields(h, h1, poc, current_slice);
414 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
415 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
416 copy_picture_range(h->delayed_pic, h1->delayed_pic,
417 MAX_DELAYED_PIC_COUNT + 2, h, h1);
423 err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
424 h->poc.prev_poc_msb = h->poc.poc_msb;
425 h->poc.prev_poc_lsb = h->poc.poc_lsb;
427 h->poc.prev_frame_num_offset = h->poc.frame_num_offset;
428 h->poc.prev_frame_num = h->poc.frame_num;
430 h->recovery_frame = h1->recovery_frame;
431 h->frame_recovered = h1->frame_recovered;
436 static int h264_frame_start(H264Context *h)
440 const int pixel_shift = h->pixel_shift;
442 ret = initialize_cur_frame(h);
446 pic = h->cur_pic_ptr;
447 pic->reference = h->droppable ? 0 : h->picture_structure;
448 pic->f->coded_picture_number = h->coded_picture_number++;
449 pic->field_picture = h->picture_structure != PICT_FRAME;
450 pic->frame_num = h->poc.frame_num;
452 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
454 * See decode_nal_units().
456 pic->f->key_frame = 0;
460 if (CONFIG_ERROR_RESILIENCE && h->enable_er)
461 ff_er_frame_start(&h->slice_ctx[0].er);
463 for (i = 0; i < 16; i++) {
464 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
465 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
467 for (i = 0; i < 16; i++) {
468 h->block_offset[16 + i] =
469 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
470 h->block_offset[48 + 16 + i] =
471 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
474 /* Some macroblocks can be accessed before they're available in case
475 * of lost slices, MBAFF or threading. */
476 memset(h->slice_table, -1,
477 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
479 /* We mark the current picture as non-reference after allocating it, so
480 * that if we break out due to an error it can be released automatically
481 * in the next ff_mpv_frame_start().
483 h->cur_pic_ptr->reference = 0;
485 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
487 h->next_output_pic = NULL;
489 assert(h->cur_pic_ptr->long_ref == 0);
494 static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
496 uint8_t *src_cb, uint8_t *src_cr,
497 int linesize, int uvlinesize,
502 const int pixel_shift = h->pixel_shift;
503 int chroma444 = CHROMA444(h);
504 int chroma422 = CHROMA422(h);
507 src_cb -= uvlinesize;
508 src_cr -= uvlinesize;
510 if (!simple && FRAME_MBAFF(h)) {
513 top_border = sl->top_borders[0][sl->mb_x];
514 AV_COPY128(top_border, src_y + 15 * linesize);
516 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
517 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
520 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
521 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
522 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
523 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
525 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
526 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
528 } else if (chroma422) {
530 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
531 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
533 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
534 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
538 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
539 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
541 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
542 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
547 } else if (MB_MBAFF(sl)) {
553 top_border = sl->top_borders[top_idx][sl->mb_x];
554 /* There are two lines saved, the line above the top macroblock
555 * of a pair, and the line above the bottom macroblock. */
556 AV_COPY128(top_border, src_y + 16 * linesize);
558 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
560 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
563 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
564 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
565 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
566 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
568 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
569 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
571 } else if (chroma422) {
573 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
574 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
576 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
577 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
581 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
582 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
584 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
585 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
592 * Initialize implicit_weight table.
593 * @param field 0/1 initialize the weight for interlaced MBAFF
594 * -1 initializes the rest
596 static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
598 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
600 for (i = 0; i < 2; i++) {
601 sl->pwt.luma_weight_flag[i] = 0;
602 sl->pwt.chroma_weight_flag[i] = 0;
606 if (h->picture_structure == PICT_FRAME) {
607 cur_poc = h->cur_pic_ptr->poc;
609 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
611 if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
612 sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {
613 sl->pwt.use_weight = 0;
614 sl->pwt.use_weight_chroma = 0;
618 ref_count0 = sl->ref_count[0];
619 ref_count1 = sl->ref_count[1];
621 cur_poc = h->cur_pic_ptr->field_poc[field];
623 ref_count0 = 16 + 2 * sl->ref_count[0];
624 ref_count1 = 16 + 2 * sl->ref_count[1];
627 sl->pwt.use_weight = 2;
628 sl->pwt.use_weight_chroma = 2;
629 sl->pwt.luma_log2_weight_denom = 5;
630 sl->pwt.chroma_log2_weight_denom = 5;
632 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
633 int poc0 = sl->ref_list[0][ref0].poc;
634 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
636 if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
637 int poc1 = sl->ref_list[1][ref1].poc;
638 int td = av_clip_int8(poc1 - poc0);
640 int tb = av_clip_int8(cur_poc - poc0);
641 int tx = (16384 + (FFABS(td) >> 1)) / td;
642 int dist_scale_factor = (tb * tx + 32) >> 8;
643 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
644 w = 64 - dist_scale_factor;
648 sl->pwt.implicit_weight[ref0][ref1][0] =
649 sl->pwt.implicit_weight[ref0][ref1][1] = w;
651 sl->pwt.implicit_weight[ref0][ref1][field] = w;
658 * initialize scan tables
660 static void init_scan_tables(H264Context *h)
663 for (i = 0; i < 16; i++) {
664 #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
665 h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
666 h->field_scan[i] = TRANSPOSE(field_scan[i]);
669 for (i = 0; i < 64; i++) {
670 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
671 h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
672 h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
673 h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
674 h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
677 if (h->ps.sps->transform_bypass) { // FIXME same ugly
678 h->zigzag_scan_q0 = ff_zigzag_scan;
679 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
680 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
681 h->field_scan_q0 = field_scan;
682 h->field_scan8x8_q0 = field_scan8x8;
683 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
685 h->zigzag_scan_q0 = h->zigzag_scan;
686 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
687 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
688 h->field_scan_q0 = h->field_scan;
689 h->field_scan8x8_q0 = h->field_scan8x8;
690 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
694 static enum AVPixelFormat get_pixel_format(H264Context *h)
696 #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
697 CONFIG_H264_D3D11VA_HWACCEL + \
698 CONFIG_H264_VAAPI_HWACCEL + \
699 (CONFIG_H264_VDA_HWACCEL * 2) + \
700 CONFIG_H264_VDPAU_HWACCEL)
701 enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
702 const enum AVPixelFormat *choices = pix_fmts;
704 switch (h->ps.sps->bit_depth_luma) {
707 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
708 *fmt++ = AV_PIX_FMT_GBRP9;
710 *fmt++ = AV_PIX_FMT_YUV444P9;
711 } else if (CHROMA422(h))
712 *fmt++ = AV_PIX_FMT_YUV422P9;
714 *fmt++ = AV_PIX_FMT_YUV420P9;
718 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
719 *fmt++ = AV_PIX_FMT_GBRP10;
721 *fmt++ = AV_PIX_FMT_YUV444P10;
722 } else if (CHROMA422(h))
723 *fmt++ = AV_PIX_FMT_YUV422P10;
725 *fmt++ = AV_PIX_FMT_YUV420P10;
728 #if CONFIG_H264_VDPAU_HWACCEL
729 *fmt++ = AV_PIX_FMT_VDPAU;
732 if (h->avctx->colorspace == AVCOL_SPC_RGB)
733 *fmt++ = AV_PIX_FMT_GBRP;
734 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
735 *fmt++ = AV_PIX_FMT_YUVJ444P;
737 *fmt++ = AV_PIX_FMT_YUV444P;
738 } else if (CHROMA422(h)) {
739 if (h->avctx->color_range == AVCOL_RANGE_JPEG)
740 *fmt++ = AV_PIX_FMT_YUVJ422P;
742 *fmt++ = AV_PIX_FMT_YUV422P;
744 #if CONFIG_H264_DXVA2_HWACCEL
745 *fmt++ = AV_PIX_FMT_DXVA2_VLD;
747 #if CONFIG_H264_D3D11VA_HWACCEL
748 *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
750 #if CONFIG_H264_VAAPI_HWACCEL
751 *fmt++ = AV_PIX_FMT_VAAPI;
753 #if CONFIG_H264_VDA_HWACCEL
754 *fmt++ = AV_PIX_FMT_VDA_VLD;
755 *fmt++ = AV_PIX_FMT_VDA;
757 if (h->avctx->codec->pix_fmts)
758 choices = h->avctx->codec->pix_fmts;
759 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
760 *fmt++ = AV_PIX_FMT_YUVJ420P;
762 *fmt++ = AV_PIX_FMT_YUV420P;
766 av_log(h->avctx, AV_LOG_ERROR,
767 "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);
768 return AVERROR_INVALIDDATA;
771 *fmt = AV_PIX_FMT_NONE;
773 return ff_get_format(h->avctx, choices);
776 /* export coded and cropped frame dimensions to AVCodecContext */
777 static int init_dimensions(H264Context *h)
779 SPS *sps = h->ps.sps;
780 int width = h->width - (sps->crop_right + sps->crop_left);
781 int height = h->height - (sps->crop_top + sps->crop_bottom);
783 /* handle container cropping */
784 if (FFALIGN(h->avctx->width, 16) == FFALIGN(width, 16) &&
785 FFALIGN(h->avctx->height, 16) == FFALIGN(height, 16)) {
786 width = h->avctx->width;
787 height = h->avctx->height;
790 if (width <= 0 || height <= 0) {
791 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
793 if (h->avctx->err_recognition & AV_EF_EXPLODE)
794 return AVERROR_INVALIDDATA;
796 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
807 h->avctx->coded_width = h->width;
808 h->avctx->coded_height = h->height;
809 h->avctx->width = width;
810 h->avctx->height = height;
815 static int h264_slice_header_init(H264Context *h)
817 const SPS *sps = h->ps.sps;
818 int nb_slices = (HAVE_THREADS &&
819 h->avctx->active_thread_type & FF_THREAD_SLICE) ?
820 h->avctx->thread_count : 1;
823 ff_set_sar(h->avctx, sps->sar);
824 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
825 &h->chroma_x_shift, &h->chroma_y_shift);
827 if (sps->timing_info_present_flag) {
828 int64_t den = sps->time_scale;
829 if (h->x264_build < 44U)
831 av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
832 sps->num_units_in_tick, den, 1 << 30);
835 ff_h264_free_tables(h);
838 h->prev_interlaced_frame = 1;
841 ret = ff_h264_alloc_tables(h);
843 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
847 if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 10) {
848 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
849 sps->bit_depth_luma);
850 return AVERROR_INVALIDDATA;
853 h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
854 h->pixel_shift = sps->bit_depth_luma > 8;
855 h->chroma_format_idc = sps->chroma_format_idc;
856 h->bit_depth_luma = sps->bit_depth_luma;
858 ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
859 sps->chroma_format_idc);
860 ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
861 ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
862 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
863 sps->chroma_format_idc);
864 ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
866 if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
869 max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);
871 max_slices = H264_MAX_THREADS;
872 av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"
873 " reducing to %d\n", nb_slices, max_slices);
874 nb_slices = max_slices;
876 h->slice_context_count = nb_slices;
878 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
879 ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
881 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
885 for (i = 0; i < h->slice_context_count; i++) {
886 H264SliceContext *sl = &h->slice_ctx[i];
889 sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
890 sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
891 sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
893 if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
894 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
900 h->context_initialized = 1;
906 * Decode a slice header.
907 * This will (re)intialize the decoder and call h264_frame_start() as needed.
909 * @param h h264context
911 * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
913 int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl)
917 unsigned int first_mb_in_slice;
920 unsigned int slice_type, tmp, i, j;
921 int last_pic_structure, last_pic_droppable;
922 int needs_reinit = 0;
923 int field_pic_flag, bottom_field_flag;
924 int frame_num, droppable, picture_structure;
925 int mb_aff_frame = 0;
927 h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
928 h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
930 first_mb_in_slice = get_ue_golomb(&sl->gb);
932 if (first_mb_in_slice == 0) { // FIXME better field boundary detection
933 if (h->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
934 ff_h264_field_end(h, sl, 1);
937 h->current_slice = 0;
938 if (!h->first_field) {
939 if (h->cur_pic_ptr && !h->droppable) {
940 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
941 h->picture_structure == PICT_BOTTOM_FIELD);
943 h->cur_pic_ptr = NULL;
947 slice_type = get_ue_golomb_31(&sl->gb);
948 if (slice_type > 9) {
949 av_log(h->avctx, AV_LOG_ERROR,
950 "slice type %d too large at %d\n",
951 slice_type, first_mb_in_slice);
952 return AVERROR_INVALIDDATA;
954 if (slice_type > 4) {
956 sl->slice_type_fixed = 1;
958 sl->slice_type_fixed = 0;
960 slice_type = ff_h264_golomb_to_pict_type[slice_type];
961 sl->slice_type = slice_type;
962 sl->slice_type_nos = slice_type & 3;
964 if (h->nal_unit_type == NAL_IDR_SLICE &&
965 sl->slice_type_nos != AV_PICTURE_TYPE_I) {
966 av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
967 return AVERROR_INVALIDDATA;
970 // to make a few old functions happy, it's wrong though
971 if (!h->setup_finished)
972 h->pict_type = sl->slice_type;
974 pps_id = get_ue_golomb(&sl->gb);
975 if (pps_id >= MAX_PPS_COUNT) {
976 av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
977 return AVERROR_INVALIDDATA;
979 if (!h->ps.pps_list[pps_id]) {
980 av_log(h->avctx, AV_LOG_ERROR,
981 "non-existing PPS %u referenced\n",
983 return AVERROR_INVALIDDATA;
985 if (!h->setup_finished) {
986 h->ps.pps = (const PPS*)h->ps.pps_list[pps_id]->data;
987 } else if (h->ps.pps != (const PPS*)h->ps.pps_list[pps_id]->data) {
988 av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
989 return AVERROR_INVALIDDATA;
992 if (!h->ps.sps_list[h->ps.pps->sps_id]) {
993 av_log(h->avctx, AV_LOG_ERROR,
994 "non-existing SPS %u referenced\n",
996 return AVERROR_INVALIDDATA;
999 if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
1000 h->ps.sps = (SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data;
1002 if (h->bit_depth_luma != h->ps.sps->bit_depth_luma ||
1003 h->chroma_format_idc != h->ps.sps->chroma_format_idc)
1006 if (h->flags & AV_CODEC_FLAG_LOW_DELAY ||
1007 (h->ps.sps->bitstream_restriction_flag &&
1008 !h->ps.sps->num_reorder_frames)) {
1009 if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
1010 av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
1011 "Reenabling low delay requires a codec flush.\n");
1016 if (h->avctx->has_b_frames < 2)
1017 h->avctx->has_b_frames = !h->low_delay;
1024 if (!h->setup_finished) {
1025 h->avctx->profile = ff_h264_get_profile(sps);
1026 h->avctx->level = sps->level_idc;
1027 h->avctx->refs = sps->ref_frame_count;
1029 if (h->mb_width != sps->mb_width ||
1030 h->mb_height != sps->mb_height * (2 - sps->frame_mbs_only_flag))
1033 h->mb_width = sps->mb_width;
1034 h->mb_height = sps->mb_height * (2 - sps->frame_mbs_only_flag);
1035 h->mb_num = h->mb_width * h->mb_height;
1036 h->mb_stride = h->mb_width + 1;
1038 h->b_stride = h->mb_width * 4;
1040 h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
1042 h->width = 16 * h->mb_width;
1043 h->height = 16 * h->mb_height;
1045 ret = init_dimensions(h);
1049 if (sps->video_signal_type_present_flag) {
1050 h->avctx->color_range = sps->full_range ? AVCOL_RANGE_JPEG
1052 if (sps->colour_description_present_flag) {
1053 if (h->avctx->colorspace != sps->colorspace)
1055 h->avctx->color_primaries = sps->color_primaries;
1056 h->avctx->color_trc = sps->color_trc;
1057 h->avctx->colorspace = sps->colorspace;
1062 if (h->context_initialized && needs_reinit) {
1063 h->context_initialized = 0;
1064 if (sl != h->slice_ctx) {
1065 av_log(h->avctx, AV_LOG_ERROR,
1066 "changing width %d -> %d / height %d -> %d on "
1068 h->width, h->avctx->coded_width,
1069 h->height, h->avctx->coded_height,
1070 h->current_slice + 1);
1071 return AVERROR_INVALIDDATA;
1074 ff_h264_flush_change(h);
1076 if ((ret = get_pixel_format(h)) < 0)
1078 h->avctx->pix_fmt = ret;
1080 av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
1081 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
1083 if ((ret = h264_slice_header_init(h)) < 0) {
1084 av_log(h->avctx, AV_LOG_ERROR,
1085 "h264_slice_header_init() failed\n");
1089 if (!h->context_initialized) {
1090 if (sl != h->slice_ctx) {
1091 av_log(h->avctx, AV_LOG_ERROR,
1092 "Cannot (re-)initialize context during parallel decoding.\n");
1093 return AVERROR_PATCHWELCOME;
1096 if ((ret = get_pixel_format(h)) < 0)
1098 h->avctx->pix_fmt = ret;
1100 if ((ret = h264_slice_header_init(h)) < 0) {
1101 av_log(h->avctx, AV_LOG_ERROR,
1102 "h264_slice_header_init() failed\n");
1107 frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
1108 if (!h->setup_finished)
1109 h->poc.frame_num = frame_num;
1113 last_pic_structure = h->picture_structure;
1114 last_pic_droppable = h->droppable;
1116 droppable = h->nal_ref_idc == 0;
1117 if (sps->frame_mbs_only_flag) {
1118 picture_structure = PICT_FRAME;
1120 field_pic_flag = get_bits1(&sl->gb);
1121 if (field_pic_flag) {
1122 bottom_field_flag = get_bits1(&sl->gb);
1123 picture_structure = PICT_TOP_FIELD + bottom_field_flag;
1125 picture_structure = PICT_FRAME;
1126 mb_aff_frame = sps->mb_aff;
1129 if (!h->setup_finished) {
1130 h->droppable = droppable;
1131 h->picture_structure = picture_structure;
1132 h->mb_aff_frame = mb_aff_frame;
1134 sl->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
1136 if (h->current_slice != 0) {
1137 if (last_pic_structure != picture_structure ||
1138 last_pic_droppable != droppable) {
1139 av_log(h->avctx, AV_LOG_ERROR,
1140 "Changing field mode (%d -> %d) between slices is not allowed\n",
1141 last_pic_structure, h->picture_structure);
1142 return AVERROR_INVALIDDATA;
1143 } else if (!h->cur_pic_ptr) {
1144 av_log(h->avctx, AV_LOG_ERROR,
1145 "unset cur_pic_ptr on slice %d\n",
1146 h->current_slice + 1);
1147 return AVERROR_INVALIDDATA;
1150 /* Shorten frame num gaps so we don't have to allocate reference
1151 * frames just to throw them away */
1152 if (h->poc.frame_num != h->poc.prev_frame_num) {
1153 int unwrap_prev_frame_num = h->poc.prev_frame_num;
1154 int max_frame_num = 1 << sps->log2_max_frame_num;
1156 if (unwrap_prev_frame_num > h->poc.frame_num)
1157 unwrap_prev_frame_num -= max_frame_num;
1159 if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
1160 unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
1161 if (unwrap_prev_frame_num < 0)
1162 unwrap_prev_frame_num += max_frame_num;
1164 h->poc.prev_frame_num = unwrap_prev_frame_num;
1168 /* See if we have a decoded first field looking for a pair...
1169 * Here, we're using that to see if we should mark previously
1170 * decode frames as "finished".
1171 * We have to do that before the "dummy" in-between frame allocation,
1172 * since that can modify s->current_picture_ptr. */
1173 if (h->first_field) {
1174 assert(h->cur_pic_ptr);
1175 assert(h->cur_pic_ptr->f->buf[0]);
1176 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1178 /* figure out if we have a complementary field pair */
1179 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1180 /* Previous field is unmatched. Don't display it, but let it
1181 * remain for reference if marked as such. */
1182 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1183 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1184 last_pic_structure == PICT_TOP_FIELD);
1187 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1188 /* This and previous field were reference, but had
1189 * different frame_nums. Consider this field first in
1190 * pair. Throw away previous field except for reference
1192 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1193 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1194 last_pic_structure == PICT_TOP_FIELD);
1197 /* Second field in complementary pair */
1198 if (!((last_pic_structure == PICT_TOP_FIELD &&
1199 h->picture_structure == PICT_BOTTOM_FIELD) ||
1200 (last_pic_structure == PICT_BOTTOM_FIELD &&
1201 h->picture_structure == PICT_TOP_FIELD))) {
1202 av_log(h->avctx, AV_LOG_ERROR,
1203 "Invalid field mode combination %d/%d\n",
1204 last_pic_structure, h->picture_structure);
1205 h->picture_structure = last_pic_structure;
1206 h->droppable = last_pic_droppable;
1207 return AVERROR_INVALIDDATA;
1208 } else if (last_pic_droppable != h->droppable) {
1209 avpriv_request_sample(h->avctx,
1210 "Found reference and non-reference fields in the same frame, which");
1211 h->picture_structure = last_pic_structure;
1212 h->droppable = last_pic_droppable;
1213 return AVERROR_PATCHWELCOME;
1219 while (h->poc.frame_num != h->poc.prev_frame_num &&
1220 h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
1221 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1222 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1223 h->poc.frame_num, h->poc.prev_frame_num);
1224 ret = initialize_cur_frame(h);
1230 h->poc.prev_frame_num++;
1231 h->poc.prev_frame_num %= 1 << sps->log2_max_frame_num;
1232 h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
1233 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1234 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1235 ret = ff_generate_sliding_window_mmcos(h, 1);
1236 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1238 ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
1239 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1241 /* Error concealment: If a ref is missing, copy the previous ref
1243 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1244 * many assumptions about there being no actual duplicates.
1245 * FIXME: This does not copy padding for out-of-frame motion
1246 * vectors. Given we are concealing a lost frame, this probably
1247 * is not noticeable by comparison, but it should be fixed. */
1248 if (h->short_ref_count) {
1250 h->short_ref[0]->f->width == prev->f->width &&
1251 h->short_ref[0]->f->height == prev->f->height &&
1252 h->short_ref[0]->f->format == prev->f->format) {
1253 av_image_copy(h->short_ref[0]->f->data,
1254 h->short_ref[0]->f->linesize,
1255 (const uint8_t **)prev->f->data,
1260 h->short_ref[0]->poc = prev->poc + 2;
1262 h->short_ref[0]->frame_num = h->poc.prev_frame_num;
1266 /* See if we have a decoded first field looking for a pair...
1267 * We're using that to see whether to continue decoding in that
1268 * frame, or to allocate a new one. */
1269 if (h->first_field) {
1270 assert(h->cur_pic_ptr);
1271 assert(h->cur_pic_ptr->f->buf[0]);
1272 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1274 /* figure out if we have a complementary field pair */
1275 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1276 /* Previous field is unmatched. Don't display it, but let it
1277 * remain for reference if marked as such. */
1278 h->cur_pic_ptr = NULL;
1279 h->first_field = FIELD_PICTURE(h);
1281 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1282 /* This and the previous field had different frame_nums.
1283 * Consider this field first in pair. Throw away previous
1284 * one except for reference purposes. */
1286 h->cur_pic_ptr = NULL;
1288 /* Second field in complementary pair */
1293 /* Frame or first field in a potentially complementary pair */
1294 h->first_field = FIELD_PICTURE(h);
1297 if (!FIELD_PICTURE(h) || h->first_field) {
1298 if (h264_frame_start(h) < 0) {
1300 return AVERROR_INVALIDDATA;
1303 release_unused_pictures(h, 0);
1307 assert(h->mb_num == h->mb_width * h->mb_height);
1308 if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1309 first_mb_in_slice >= h->mb_num) {
1310 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1311 return AVERROR_INVALIDDATA;
1313 sl->resync_mb_x = sl->mb_x = first_mb_in_slice % h->mb_width;
1314 sl->resync_mb_y = sl->mb_y = (first_mb_in_slice / h->mb_width) <<
1315 FIELD_OR_MBAFF_PICTURE(h);
1316 if (h->picture_structure == PICT_BOTTOM_FIELD)
1317 sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
1318 assert(sl->mb_y < h->mb_height);
1320 if (h->picture_structure == PICT_FRAME) {
1321 h->curr_pic_num = h->poc.frame_num;
1322 h->max_pic_num = 1 << sps->log2_max_frame_num;
1324 h->curr_pic_num = 2 * h->poc.frame_num + 1;
1325 h->max_pic_num = 1 << (sps->log2_max_frame_num + 1);
1328 if (h->nal_unit_type == NAL_IDR_SLICE)
1329 get_ue_golomb(&sl->gb); /* idr_pic_id */
1331 if (sps->poc_type == 0) {
1332 int poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
1334 if (!h->setup_finished)
1335 h->poc.poc_lsb = poc_lsb;
1337 if (pps->pic_order_present == 1 && h->picture_structure == PICT_FRAME) {
1338 int delta_poc_bottom = get_se_golomb(&sl->gb);
1339 if (!h->setup_finished)
1340 h->poc.delta_poc_bottom = delta_poc_bottom;
1344 if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
1345 int delta_poc = get_se_golomb(&sl->gb);
1347 if (!h->setup_finished)
1348 h->poc.delta_poc[0] = delta_poc;
1350 if (pps->pic_order_present == 1 && h->picture_structure == PICT_FRAME) {
1351 delta_poc = get_se_golomb(&sl->gb);
1353 if (!h->setup_finished)
1354 h->poc.delta_poc[1] = delta_poc;
1358 if (!h->setup_finished)
1359 ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
1360 sps, &h->poc, h->picture_structure, h->nal_ref_idc);
1362 if (pps->redundant_pic_cnt_present)
1363 sl->redundant_pic_count = get_ue_golomb(&sl->gb);
1365 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1366 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1368 ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
1369 &sl->gb, pps, sl->slice_type_nos,
1370 h->picture_structure);
1374 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1375 ret = ff_h264_decode_ref_pic_list_reordering(h, sl);
1377 sl->ref_count[1] = sl->ref_count[0] = 0;
1382 if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
1383 (pps->weighted_bipred_idc == 1 &&
1384 sl->slice_type_nos == AV_PICTURE_TYPE_B))
1385 ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
1386 sl->slice_type_nos, &sl->pwt);
1387 else if (pps->weighted_bipred_idc == 2 &&
1388 sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1389 implicit_weight_table(h, sl, -1);
1391 sl->pwt.use_weight = 0;
1392 for (i = 0; i < 2; i++) {
1393 sl->pwt.luma_weight_flag[i] = 0;
1394 sl->pwt.chroma_weight_flag[i] = 0;
1398 // If frame-mt is enabled, only update mmco tables for the first slice
1399 // in a field. Subsequent slices can temporarily clobber h->mmco_index
1400 // or h->mmco, which will cause ref list mix-ups and decoding errors
1401 // further down the line. This may break decoding if the first slice is
1402 // corrupt, thus we only do this if frame-mt is enabled.
1403 if (h->nal_ref_idc) {
1404 ret = ff_h264_decode_ref_pic_marking(h, &sl->gb,
1405 !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
1406 h->current_slice == 0);
1407 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1408 return AVERROR_INVALIDDATA;
1411 if (FRAME_MBAFF(h)) {
1412 ff_h264_fill_mbaff_ref_list(h, sl);
1414 if (pps->weighted_bipred_idc == 2 && sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1415 implicit_weight_table(h, sl, 0);
1416 implicit_weight_table(h, sl, 1);
1420 if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
1421 ff_h264_direct_dist_scale_factor(h, sl);
1422 ff_h264_direct_ref_list_init(h, sl);
1424 if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1425 tmp = get_ue_golomb_31(&sl->gb);
1427 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1428 return AVERROR_INVALIDDATA;
1430 sl->cabac_init_idc = tmp;
1433 sl->last_qscale_diff = 0;
1434 tmp = pps->init_qp + get_se_golomb(&sl->gb);
1435 if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
1436 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1437 return AVERROR_INVALIDDATA;
1440 sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
1441 sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
1442 // FIXME qscale / qp ... stuff
1443 if (sl->slice_type == AV_PICTURE_TYPE_SP)
1444 get_bits1(&sl->gb); /* sp_for_switch_flag */
1445 if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1446 sl->slice_type == AV_PICTURE_TYPE_SI)
1447 get_se_golomb(&sl->gb); /* slice_qs_delta */
1449 sl->deblocking_filter = 1;
1450 sl->slice_alpha_c0_offset = 0;
1451 sl->slice_beta_offset = 0;
1452 if (pps->deblocking_filter_parameters_present) {
1453 tmp = get_ue_golomb_31(&sl->gb);
1455 av_log(h->avctx, AV_LOG_ERROR,
1456 "deblocking_filter_idc %u out of range\n", tmp);
1457 return AVERROR_INVALIDDATA;
1459 sl->deblocking_filter = tmp;
1460 if (sl->deblocking_filter < 2)
1461 sl->deblocking_filter ^= 1; // 1<->0
1463 if (sl->deblocking_filter) {
1464 sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
1465 sl->slice_beta_offset = get_se_golomb(&sl->gb) * 2;
1466 if (sl->slice_alpha_c0_offset > 12 ||
1467 sl->slice_alpha_c0_offset < -12 ||
1468 sl->slice_beta_offset > 12 ||
1469 sl->slice_beta_offset < -12) {
1470 av_log(h->avctx, AV_LOG_ERROR,
1471 "deblocking filter parameters %d %d out of range\n",
1472 sl->slice_alpha_c0_offset, sl->slice_beta_offset);
1473 return AVERROR_INVALIDDATA;
1478 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1479 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
1480 sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
1481 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
1482 sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
1483 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1484 h->nal_ref_idc == 0))
1485 sl->deblocking_filter = 0;
1487 if (sl->deblocking_filter == 1 && h->max_contexts > 1) {
1488 if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
1489 /* Cheat slightly for speed:
1490 * Do not bother to deblock across slices. */
1491 sl->deblocking_filter = 2;
1493 h->max_contexts = 1;
1494 if (!h->single_decode_warning) {
1495 av_log(h->avctx, AV_LOG_INFO,
1496 "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
1497 h->single_decode_warning = 1;
1499 if (sl != h->slice_ctx) {
1500 av_log(h->avctx, AV_LOG_ERROR,
1501 "Deblocking switched inside frame.\n");
1506 sl->qp_thresh = 15 -
1507 FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
1509 pps->chroma_qp_index_offset[0],
1510 pps->chroma_qp_index_offset[1]) +
1511 6 * (sps->bit_depth_luma - 8);
1513 sl->slice_num = ++h->current_slice;
1514 if (sl->slice_num >= MAX_SLICES) {
1515 av_log(h->avctx, AV_LOG_ERROR,
1516 "Too many slices, increase MAX_SLICES and recompile\n");
1519 for (j = 0; j < 2; j++) {
1521 int *ref2frm = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
1522 for (i = 0; i < 16; i++) {
1524 if (j < sl->list_count && i < sl->ref_count[j] &&
1525 sl->ref_list[j][i].parent->f->buf[0]) {
1527 AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
1528 for (k = 0; k < h->short_ref_count; k++)
1529 if (h->short_ref[k]->f->buf[0]->buffer == buf) {
1533 for (k = 0; k < h->long_ref_count; k++)
1534 if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
1535 id_list[i] = h->short_ref_count + k;
1543 for (i = 0; i < 16; i++)
1544 ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
1546 ref2frm[18 + 1] = -1;
1547 for (i = 16; i < 48; i++)
1548 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
1549 (sl->ref_list[j][i].reference & 3);
1552 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
1553 av_log(h->avctx, AV_LOG_DEBUG,
1554 "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",
1556 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
1558 av_get_picture_type_char(sl->slice_type),
1559 sl->slice_type_fixed ? " fix" : "",
1560 h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
1561 pps_id, h->poc.frame_num,
1562 h->cur_pic_ptr->field_poc[0],
1563 h->cur_pic_ptr->field_poc[1],
1564 sl->ref_count[0], sl->ref_count[1],
1566 sl->deblocking_filter,
1567 sl->slice_alpha_c0_offset, sl->slice_beta_offset,
1569 sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
1570 sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
1576 int ff_h264_get_slice_type(const H264SliceContext *sl)
1578 switch (sl->slice_type) {
1579 case AV_PICTURE_TYPE_P:
1581 case AV_PICTURE_TYPE_B:
1583 case AV_PICTURE_TYPE_I:
1585 case AV_PICTURE_TYPE_SP:
1587 case AV_PICTURE_TYPE_SI:
1590 return AVERROR_INVALIDDATA;
1594 static av_always_inline void fill_filter_caches_inter(const H264Context *h,
1595 H264SliceContext *sl,
1596 int mb_type, int top_xy,
1597 int left_xy[LEFT_MBS],
1599 int left_type[LEFT_MBS],
1600 int mb_xy, int list)
1602 int b_stride = h->b_stride;
1603 int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
1604 int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
1605 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
1606 if (USES_LIST(top_type, list)) {
1607 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
1608 const int b8_xy = 4 * top_xy + 2;
1609 int (*ref2frm)[64] = sl->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
1610 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
1611 ref_cache[0 - 1 * 8] =
1612 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
1613 ref_cache[2 - 1 * 8] =
1614 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
1616 AV_ZERO128(mv_dst - 1 * 8);
1617 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1620 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
1621 if (USES_LIST(left_type[LTOP], list)) {
1622 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
1623 const int b8_xy = 4 * left_xy[LTOP] + 1;
1624 int (*ref2frm)[64] = sl->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
1625 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
1626 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
1627 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
1628 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
1630 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
1631 ref_cache[-1 + 16] =
1632 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
1634 AV_ZERO32(mv_dst - 1 + 0);
1635 AV_ZERO32(mv_dst - 1 + 8);
1636 AV_ZERO32(mv_dst - 1 + 16);
1637 AV_ZERO32(mv_dst - 1 + 24);
1640 ref_cache[-1 + 16] =
1641 ref_cache[-1 + 24] = LIST_NOT_USED;
1646 if (!USES_LIST(mb_type, list)) {
1647 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
1648 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1649 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1650 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1651 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1656 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
1657 int (*ref2frm)[64] = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
1658 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
1659 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
1660 AV_WN32A(&ref_cache[0 * 8], ref01);
1661 AV_WN32A(&ref_cache[1 * 8], ref01);
1662 AV_WN32A(&ref_cache[2 * 8], ref23);
1663 AV_WN32A(&ref_cache[3 * 8], ref23);
1667 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
1668 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
1669 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
1670 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
1671 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
1676 * @return non zero if the loop filter can be skipped
1678 static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
1680 const int mb_xy = sl->mb_xy;
1681 int top_xy, left_xy[LEFT_MBS];
1682 int top_type, left_type[LEFT_MBS];
1686 top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
1688 /* Wow, what a mess, why didn't they simplify the interlacing & intra
1689 * stuff, I can't imagine that these complex rules are worth it. */
1691 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
1692 if (FRAME_MBAFF(h)) {
1693 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
1694 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
1696 if (left_mb_field_flag != curr_mb_field_flag)
1697 left_xy[LTOP] -= h->mb_stride;
1699 if (curr_mb_field_flag)
1700 top_xy += h->mb_stride &
1701 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
1702 if (left_mb_field_flag != curr_mb_field_flag)
1703 left_xy[LBOT] += h->mb_stride;
1707 sl->top_mb_xy = top_xy;
1708 sl->left_mb_xy[LTOP] = left_xy[LTOP];
1709 sl->left_mb_xy[LBOT] = left_xy[LBOT];
1711 /* For sufficiently low qp, filtering wouldn't do anything.
1712 * This is a conservative estimate: could also check beta_offset
1713 * and more accurate chroma_qp. */
1714 int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
1715 int qp = h->cur_pic.qscale_table[mb_xy];
1716 if (qp <= qp_thresh &&
1717 (left_xy[LTOP] < 0 ||
1718 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
1720 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
1721 if (!FRAME_MBAFF(h))
1723 if ((left_xy[LTOP] < 0 ||
1724 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
1725 (top_xy < h->mb_stride ||
1726 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
1731 top_type = h->cur_pic.mb_type[top_xy];
1732 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
1733 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
1734 if (sl->deblocking_filter == 2) {
1735 if (h->slice_table[top_xy] != sl->slice_num)
1737 if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
1738 left_type[LTOP] = left_type[LBOT] = 0;
1740 if (h->slice_table[top_xy] == 0xFFFF)
1742 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
1743 left_type[LTOP] = left_type[LBOT] = 0;
1745 sl->top_type = top_type;
1746 sl->left_type[LTOP] = left_type[LTOP];
1747 sl->left_type[LBOT] = left_type[LBOT];
1749 if (IS_INTRA(mb_type))
1752 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
1753 top_type, left_type, mb_xy, 0);
1754 if (sl->list_count == 2)
1755 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
1756 top_type, left_type, mb_xy, 1);
1758 nnz = h->non_zero_count[mb_xy];
1759 nnz_cache = sl->non_zero_count_cache;
1760 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
1761 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
1762 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
1763 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
1764 sl->cbp = h->cbp_table[mb_xy];
1767 nnz = h->non_zero_count[top_xy];
1768 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
1771 if (left_type[LTOP]) {
1772 nnz = h->non_zero_count[left_xy[LTOP]];
1773 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
1774 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
1775 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
1776 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
1779 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
1780 * from what the loop filter needs */
1781 if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
1782 if (IS_8x8DCT(top_type)) {
1783 nnz_cache[4 + 8 * 0] =
1784 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
1785 nnz_cache[6 + 8 * 0] =
1786 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
1788 if (IS_8x8DCT(left_type[LTOP])) {
1789 nnz_cache[3 + 8 * 1] =
1790 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
1792 if (IS_8x8DCT(left_type[LBOT])) {
1793 nnz_cache[3 + 8 * 3] =
1794 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
1797 if (IS_8x8DCT(mb_type)) {
1798 nnz_cache[scan8[0]] =
1799 nnz_cache[scan8[1]] =
1800 nnz_cache[scan8[2]] =
1801 nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
1803 nnz_cache[scan8[0 + 4]] =
1804 nnz_cache[scan8[1 + 4]] =
1805 nnz_cache[scan8[2 + 4]] =
1806 nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
1808 nnz_cache[scan8[0 + 8]] =
1809 nnz_cache[scan8[1 + 8]] =
1810 nnz_cache[scan8[2 + 8]] =
1811 nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
1813 nnz_cache[scan8[0 + 12]] =
1814 nnz_cache[scan8[1 + 12]] =
1815 nnz_cache[scan8[2 + 12]] =
1816 nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
1823 static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
1825 uint8_t *dest_y, *dest_cb, *dest_cr;
1826 int linesize, uvlinesize, mb_x, mb_y;
1827 const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
1828 const int old_slice_type = sl->slice_type;
1829 const int pixel_shift = h->pixel_shift;
1830 const int block_h = 16 >> h->chroma_y_shift;
1832 if (sl->deblocking_filter) {
1833 for (mb_x = start_x; mb_x < end_x; mb_x++)
1834 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
1836 mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
1837 sl->slice_num = h->slice_table[mb_xy];
1838 mb_type = h->cur_pic.mb_type[mb_xy];
1839 sl->list_count = h->list_counts[mb_xy];
1843 sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
1847 dest_y = h->cur_pic.f->data[0] +
1848 ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
1849 dest_cb = h->cur_pic.f->data[1] +
1850 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
1851 mb_y * sl->uvlinesize * block_h;
1852 dest_cr = h->cur_pic.f->data[2] +
1853 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
1854 mb_y * sl->uvlinesize * block_h;
1855 // FIXME simplify above
1858 linesize = sl->mb_linesize = sl->linesize * 2;
1859 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
1860 if (mb_y & 1) { // FIXME move out of this function?
1861 dest_y -= sl->linesize * 15;
1862 dest_cb -= sl->uvlinesize * (block_h - 1);
1863 dest_cr -= sl->uvlinesize * (block_h - 1);
1866 linesize = sl->mb_linesize = sl->linesize;
1867 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
1869 backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
1871 if (fill_filter_caches(h, sl, mb_type))
1873 sl->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
1874 sl->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
1876 if (FRAME_MBAFF(h)) {
1877 ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
1878 linesize, uvlinesize);
1880 ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
1881 dest_cr, linesize, uvlinesize);
1885 sl->slice_type = old_slice_type;
1887 sl->mb_y = end_mb_y - FRAME_MBAFF(h);
1888 sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);
1889 sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);
1892 static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
1894 const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
1895 int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
1896 h->cur_pic.mb_type[mb_xy - 1] :
1897 (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
1898 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
1899 sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
1903 * Draw edges and report progress for the last MB row.
1905 static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
1907 int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
1908 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
1909 int height = 16 << FRAME_MBAFF(h);
1910 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
1912 if (sl->deblocking_filter) {
1913 if ((top + height) >= pic_height)
1914 height += deblock_border;
1915 top -= deblock_border;
1918 if (top >= pic_height || (top + height) < 0)
1921 height = FFMIN(height, pic_height - top);
1923 height = top + height;
1927 ff_h264_draw_horiz_band(h, sl, top, height);
1932 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
1933 h->picture_structure == PICT_BOTTOM_FIELD);
1936 static void er_add_slice(H264SliceContext *sl,
1937 int startx, int starty,
1938 int endx, int endy, int status)
1940 #if CONFIG_ERROR_RESILIENCE
1941 ERContext *er = &sl->er;
1943 if (!sl->h264->enable_er)
1946 er->ref_count = sl->ref_count[0];
1947 ff_er_add_slice(er, startx, starty, endx, endy, status);
1951 static int decode_slice(struct AVCodecContext *avctx, void *arg)
1953 H264SliceContext *sl = arg;
1954 const H264Context *h = sl->h264;
1955 int lf_x_start = sl->mb_x;
1958 sl->linesize = h->cur_pic_ptr->f->linesize[0];
1959 sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
1961 ret = alloc_scratch_buffers(sl, sl->linesize);
1965 sl->mb_skip_run = -1;
1967 sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
1968 avctx->codec_id != AV_CODEC_ID_H264 ||
1969 (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
1971 if (h->ps.pps->cabac) {
1973 align_get_bits(&sl->gb);
1976 ff_init_cabac_decoder(&sl->cabac,
1977 sl->gb.buffer + get_bits_count(&sl->gb) / 8,
1978 (get_bits_left(&sl->gb) + 7) / 8);
1980 ff_h264_init_cabac_states(h, sl);
1986 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
1987 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
1988 sl->next_slice_idx);
1989 return AVERROR_INVALIDDATA;
1992 ret = ff_h264_decode_mb_cabac(h, sl);
1993 // STOP_TIMER("decode_mb_cabac")
1996 ff_h264_hl_decode_mb(h, sl);
1998 // FIXME optimal? or let mb_decode decode 16x32 ?
1999 if (ret >= 0 && FRAME_MBAFF(h)) {
2002 ret = ff_h264_decode_mb_cabac(h, sl);
2005 ff_h264_hl_decode_mb(h, sl);
2008 eos = get_cabac_terminate(&sl->cabac);
2010 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
2011 sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2012 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2013 sl->mb_y, ER_MB_END);
2014 if (sl->mb_x >= lf_x_start)
2015 loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
2018 if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2019 av_log(h->avctx, AV_LOG_ERROR,
2020 "error while decoding MB %d %d, bytestream %td\n",
2022 sl->cabac.bytestream_end - sl->cabac.bytestream);
2023 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2024 sl->mb_y, ER_MB_ERROR);
2025 return AVERROR_INVALIDDATA;
2028 if (++sl->mb_x >= h->mb_width) {
2029 loop_filter(h, sl, lf_x_start, sl->mb_x);
2030 sl->mb_x = lf_x_start = 0;
2031 decode_finish_row(h, sl);
2033 if (FIELD_OR_MBAFF_PICTURE(h)) {
2035 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2036 predict_field_decoding_flag(h, sl);
2040 if (eos || sl->mb_y >= h->mb_height) {
2041 ff_tlog(h->avctx, "slice end %d %d\n",
2042 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2043 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2044 sl->mb_y, ER_MB_END);
2045 if (sl->mb_x > lf_x_start)
2046 loop_filter(h, sl, lf_x_start, sl->mb_x);
2054 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2055 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2056 sl->next_slice_idx);
2057 return AVERROR_INVALIDDATA;
2060 ret = ff_h264_decode_mb_cavlc(h, sl);
2063 ff_h264_hl_decode_mb(h, sl);
2065 // FIXME optimal? or let mb_decode decode 16x32 ?
2066 if (ret >= 0 && FRAME_MBAFF(h)) {
2068 ret = ff_h264_decode_mb_cavlc(h, sl);
2071 ff_h264_hl_decode_mb(h, sl);
2076 av_log(h->avctx, AV_LOG_ERROR,
2077 "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
2078 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2079 sl->mb_y, ER_MB_ERROR);
2083 if (++sl->mb_x >= h->mb_width) {
2084 loop_filter(h, sl, lf_x_start, sl->mb_x);
2085 sl->mb_x = lf_x_start = 0;
2086 decode_finish_row(h, sl);
2088 if (FIELD_OR_MBAFF_PICTURE(h)) {
2090 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2091 predict_field_decoding_flag(h, sl);
2093 if (sl->mb_y >= h->mb_height) {
2094 ff_tlog(h->avctx, "slice end %d %d\n",
2095 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2097 if (get_bits_left(&sl->gb) == 0) {
2098 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2099 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2103 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2104 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2106 return AVERROR_INVALIDDATA;
2111 if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
2112 ff_tlog(h->avctx, "slice end %d %d\n",
2113 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2115 if (get_bits_left(&sl->gb) == 0) {
2116 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2117 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2118 if (sl->mb_x > lf_x_start)
2119 loop_filter(h, sl, lf_x_start, sl->mb_x);
2123 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2124 sl->mb_y, ER_MB_ERROR);
2126 return AVERROR_INVALIDDATA;
2134 * Call decode_slice() for each context.
2136 * @param h h264 master context
2137 * @param context_count number of contexts to execute
2139 int ff_h264_execute_decode_slices(H264Context *h, unsigned context_count)
2141 AVCodecContext *const avctx = h->avctx;
2142 H264SliceContext *sl;
2145 if (h->avctx->hwaccel)
2147 if (context_count == 1) {
2150 h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2152 ret = decode_slice(avctx, &h->slice_ctx[0]);
2153 h->mb_y = h->slice_ctx[0].mb_y;
2156 for (i = 0; i < context_count; i++) {
2157 int next_slice_idx = h->mb_width * h->mb_height;
2160 sl = &h->slice_ctx[i];
2161 sl->er.error_count = 0;
2163 /* make sure none of those slices overlap */
2164 slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2165 for (j = 0; j < context_count; j++) {
2166 H264SliceContext *sl2 = &h->slice_ctx[j];
2167 int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2169 if (i == j || slice_idx2 < slice_idx)
2171 next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2173 sl->next_slice_idx = next_slice_idx;
2176 avctx->execute(avctx, decode_slice, h->slice_ctx,
2177 NULL, context_count, sizeof(h->slice_ctx[0]));
2179 /* pull back stuff from slices to master context */
2180 sl = &h->slice_ctx[context_count - 1];
2182 for (i = 1; i < context_count; i++)
2183 h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;