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 / MPEG-4 part10 codec.
25 * @author Michael Niedermayer <michaelni@gmx.at>
28 #include "libavutil/avassert.h"
29 #include "libavutil/display.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/stereo3d.h"
32 #include "libavutil/timer.h"
35 #include "cabac_functions.h"
36 #include "error_resilience.h"
41 #include "h264chroma.h"
42 #include "h264_mvpred.h"
46 #include "mpegutils.h"
47 #include "rectangle.h"
50 static const uint8_t field_scan[16] = {
51 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
52 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
53 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
54 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
57 static const uint8_t field_scan8x8[64] = {
58 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
59 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
60 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
61 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
62 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
63 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
64 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
65 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
66 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
67 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
68 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
69 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
70 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
71 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
72 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
73 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
76 static const uint8_t field_scan8x8_cavlc[64] = {
77 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
78 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
79 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
80 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
81 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
82 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
83 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
84 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
85 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
86 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
87 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
88 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
89 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
90 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
91 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
92 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
95 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
96 static const uint8_t zigzag_scan8x8_cavlc[64] = {
97 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
98 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
99 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
100 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
101 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
102 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
103 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
104 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
105 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
106 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
107 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
108 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
109 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
110 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
111 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
112 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
115 static void release_unused_pictures(H264Context *h, int remove_current)
119 /* release non reference frames */
120 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
121 if (h->DPB[i].f->buf[0] && !h->DPB[i].reference &&
122 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
123 ff_h264_unref_picture(h, &h->DPB[i]);
128 static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
130 const H264Context *h = sl->h264;
131 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
133 av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
134 // edge emu needs blocksize + filter length - 1
135 // (= 21x21 for H.264)
136 av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
138 av_fast_malloc(&sl->top_borders[0], &sl->top_borders_allocated[0],
139 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
140 av_fast_malloc(&sl->top_borders[1], &sl->top_borders_allocated[1],
141 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
143 if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
144 !sl->top_borders[0] || !sl->top_borders[1]) {
145 av_freep(&sl->bipred_scratchpad);
146 av_freep(&sl->edge_emu_buffer);
147 av_freep(&sl->top_borders[0]);
148 av_freep(&sl->top_borders[1]);
150 sl->bipred_scratchpad_allocated = 0;
151 sl->edge_emu_buffer_allocated = 0;
152 sl->top_borders_allocated[0] = 0;
153 sl->top_borders_allocated[1] = 0;
154 return AVERROR(ENOMEM);
160 static int init_table_pools(H264Context *h)
162 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
163 const int mb_array_size = h->mb_stride * h->mb_height;
164 const int b4_stride = h->mb_width * 4 + 1;
165 const int b4_array_size = b4_stride * h->mb_height * 4;
167 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
169 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
170 sizeof(uint32_t), av_buffer_allocz);
171 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
172 sizeof(int16_t), av_buffer_allocz);
173 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
175 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
176 !h->ref_index_pool) {
177 av_buffer_pool_uninit(&h->qscale_table_pool);
178 av_buffer_pool_uninit(&h->mb_type_pool);
179 av_buffer_pool_uninit(&h->motion_val_pool);
180 av_buffer_pool_uninit(&h->ref_index_pool);
181 return AVERROR(ENOMEM);
187 static int alloc_picture(H264Context *h, H264Picture *pic)
191 av_assert0(!pic->f->data[0]);
194 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
195 AV_GET_BUFFER_FLAG_REF : 0);
199 if (h->avctx->hwaccel) {
200 const AVHWAccel *hwaccel = h->avctx->hwaccel;
201 av_assert0(!pic->hwaccel_picture_private);
202 if (hwaccel->frame_priv_data_size) {
203 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
204 if (!pic->hwaccel_priv_buf)
205 return AVERROR(ENOMEM);
206 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
210 if (!h->qscale_table_pool) {
211 ret = init_table_pools(h);
216 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
217 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
218 if (!pic->qscale_table_buf || !pic->mb_type_buf)
221 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
222 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
224 for (i = 0; i < 2; i++) {
225 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
226 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
227 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
230 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
231 pic->ref_index[i] = pic->ref_index_buf[i]->data;
236 ff_h264_unref_picture(h, pic);
237 return (ret < 0) ? ret : AVERROR(ENOMEM);
240 static inline int pic_is_unused(H264Context *h, H264Picture *pic)
247 static int find_unused_picture(H264Context *h)
251 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
252 if (pic_is_unused(h, &h->DPB[i]))
255 if (i == H264_MAX_PICTURE_COUNT)
256 return AVERROR_INVALIDDATA;
261 static int initialize_cur_frame(H264Context *h)
266 release_unused_pictures(h, 1);
267 ff_h264_unref_picture(h, &h->cur_pic);
268 h->cur_pic_ptr = NULL;
270 ret = find_unused_picture(h);
272 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
277 ret = alloc_picture(h, cur);
281 ret = ff_h264_ref_picture(h, &h->cur_pic, cur);
284 h->cur_pic_ptr = cur;
289 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
291 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
292 ((pic && pic >= old_ctx->DPB && \
293 pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
294 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
296 static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
297 H264Context *new_base,
298 H264Context *old_base)
302 for (i = 0; i < count; i++) {
303 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
304 IN_RANGE(from[i], old_base->DPB,
305 sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
307 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
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->mb_aff_frame = h1->mb_aff_frame;
385 h->droppable = h1->droppable;
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->droppable = h1->droppable;
406 // extradata/NAL handling
407 h->is_avc = h1->is_avc;
408 h->nal_length_size = h1->nal_length_size;
410 memcpy(&h->poc, &h1->poc, sizeof(h->poc));
412 memcpy(h->short_ref, h1->short_ref, sizeof(h->short_ref));
413 memcpy(h->long_ref, h1->long_ref, sizeof(h->long_ref));
414 memcpy(h->delayed_pic, h1->delayed_pic, sizeof(h->delayed_pic));
415 memcpy(h->last_pocs, h1->last_pocs, sizeof(h->last_pocs));
417 h->next_outputed_poc = h1->next_outputed_poc;
419 memcpy(h->mmco, h1->mmco, sizeof(h->mmco));
420 h->nb_mmco = h1->nb_mmco;
421 h->mmco_reset = h1->mmco_reset;
422 h->explicit_ref_marking = h1->explicit_ref_marking;
423 h->long_ref_count = h1->long_ref_count;
424 h->short_ref_count = h1->short_ref_count;
426 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
427 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
428 copy_picture_range(h->delayed_pic, h1->delayed_pic,
429 MAX_DELAYED_PIC_COUNT + 2, h, h1);
435 err = ff_h264_execute_ref_pic_marking(h);
436 h->poc.prev_poc_msb = h->poc.poc_msb;
437 h->poc.prev_poc_lsb = h->poc.poc_lsb;
439 h->poc.prev_frame_num_offset = h->poc.frame_num_offset;
440 h->poc.prev_frame_num = h->poc.frame_num;
442 h->recovery_frame = h1->recovery_frame;
443 h->frame_recovered = h1->frame_recovered;
448 static int h264_frame_start(H264Context *h)
452 const int pixel_shift = h->pixel_shift;
454 ret = initialize_cur_frame(h);
458 pic = h->cur_pic_ptr;
459 pic->reference = h->droppable ? 0 : h->picture_structure;
460 pic->f->coded_picture_number = h->coded_picture_number++;
461 pic->field_picture = h->picture_structure != PICT_FRAME;
462 pic->frame_num = h->poc.frame_num;
464 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
466 * See decode_nal_units().
468 pic->f->key_frame = 0;
472 pic->f->pict_type = h->slice_ctx[0].slice_type;
474 if (CONFIG_ERROR_RESILIENCE && h->enable_er)
475 ff_er_frame_start(&h->slice_ctx[0].er);
477 for (i = 0; i < 16; i++) {
478 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
479 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
481 for (i = 0; i < 16; i++) {
482 h->block_offset[16 + i] =
483 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
484 h->block_offset[48 + 16 + i] =
485 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
488 /* Some macroblocks can be accessed before they're available in case
489 * of lost slices, MBAFF or threading. */
490 memset(h->slice_table, -1,
491 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
493 /* We mark the current picture as non-reference after allocating it, so
494 * that if we break out due to an error it can be released automatically
495 * in the next ff_mpv_frame_start().
497 h->cur_pic_ptr->reference = 0;
499 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
501 h->postpone_filter = 0;
503 h->mb_aff_frame = h->ps.sps->mb_aff && (h->picture_structure == PICT_FRAME);
505 assert(h->cur_pic_ptr->long_ref == 0);
510 static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
512 uint8_t *src_cb, uint8_t *src_cr,
513 int linesize, int uvlinesize,
518 const int pixel_shift = h->pixel_shift;
519 int chroma444 = CHROMA444(h);
520 int chroma422 = CHROMA422(h);
523 src_cb -= uvlinesize;
524 src_cr -= uvlinesize;
526 if (!simple && FRAME_MBAFF(h)) {
529 top_border = sl->top_borders[0][sl->mb_x];
530 AV_COPY128(top_border, src_y + 15 * linesize);
532 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
533 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
536 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
537 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
538 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
539 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
541 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
542 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
544 } else if (chroma422) {
546 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
547 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
549 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
550 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
554 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
555 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
557 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
558 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
563 } else if (MB_MBAFF(sl)) {
569 top_border = sl->top_borders[top_idx][sl->mb_x];
570 /* There are two lines saved, the line above the top macroblock
571 * of a pair, and the line above the bottom macroblock. */
572 AV_COPY128(top_border, src_y + 16 * linesize);
574 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
576 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
579 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
580 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
581 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
582 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
584 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
585 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
587 } else if (chroma422) {
589 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
590 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
592 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
593 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
597 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
598 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
600 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
601 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
608 * Initialize implicit_weight table.
609 * @param field 0/1 initialize the weight for interlaced MBAFF
610 * -1 initializes the rest
612 static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
614 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
616 for (i = 0; i < 2; i++) {
617 sl->pwt.luma_weight_flag[i] = 0;
618 sl->pwt.chroma_weight_flag[i] = 0;
622 if (h->picture_structure == PICT_FRAME) {
623 cur_poc = h->cur_pic_ptr->poc;
625 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
627 if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
628 sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {
629 sl->pwt.use_weight = 0;
630 sl->pwt.use_weight_chroma = 0;
634 ref_count0 = sl->ref_count[0];
635 ref_count1 = sl->ref_count[1];
637 cur_poc = h->cur_pic_ptr->field_poc[field];
639 ref_count0 = 16 + 2 * sl->ref_count[0];
640 ref_count1 = 16 + 2 * sl->ref_count[1];
643 sl->pwt.use_weight = 2;
644 sl->pwt.use_weight_chroma = 2;
645 sl->pwt.luma_log2_weight_denom = 5;
646 sl->pwt.chroma_log2_weight_denom = 5;
648 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
649 int poc0 = sl->ref_list[0][ref0].poc;
650 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
652 if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
653 int poc1 = sl->ref_list[1][ref1].poc;
654 int td = av_clip_int8(poc1 - poc0);
656 int tb = av_clip_int8(cur_poc - poc0);
657 int tx = (16384 + (FFABS(td) >> 1)) / td;
658 int dist_scale_factor = (tb * tx + 32) >> 8;
659 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
660 w = 64 - dist_scale_factor;
664 sl->pwt.implicit_weight[ref0][ref1][0] =
665 sl->pwt.implicit_weight[ref0][ref1][1] = w;
667 sl->pwt.implicit_weight[ref0][ref1][field] = w;
674 * initialize scan tables
676 static void init_scan_tables(H264Context *h)
679 for (i = 0; i < 16; i++) {
680 #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
681 h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
682 h->field_scan[i] = TRANSPOSE(field_scan[i]);
685 for (i = 0; i < 64; i++) {
686 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
687 h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
688 h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
689 h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
690 h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
693 if (h->ps.sps->transform_bypass) { // FIXME same ugly
694 h->zigzag_scan_q0 = ff_zigzag_scan;
695 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
696 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
697 h->field_scan_q0 = field_scan;
698 h->field_scan8x8_q0 = field_scan8x8;
699 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
701 h->zigzag_scan_q0 = h->zigzag_scan;
702 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
703 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
704 h->field_scan_q0 = h->field_scan;
705 h->field_scan8x8_q0 = h->field_scan8x8;
706 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
710 static enum AVPixelFormat get_pixel_format(H264Context *h)
712 #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
713 CONFIG_H264_D3D11VA_HWACCEL + \
714 CONFIG_H264_VAAPI_HWACCEL + \
715 (CONFIG_H264_VDA_HWACCEL * 2) + \
716 CONFIG_H264_VDPAU_HWACCEL)
717 enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
718 const enum AVPixelFormat *choices = pix_fmts;
720 switch (h->ps.sps->bit_depth_luma) {
723 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
724 *fmt++ = AV_PIX_FMT_GBRP9;
726 *fmt++ = AV_PIX_FMT_YUV444P9;
727 } else if (CHROMA422(h))
728 *fmt++ = AV_PIX_FMT_YUV422P9;
730 *fmt++ = AV_PIX_FMT_YUV420P9;
734 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
735 *fmt++ = AV_PIX_FMT_GBRP10;
737 *fmt++ = AV_PIX_FMT_YUV444P10;
738 } else if (CHROMA422(h))
739 *fmt++ = AV_PIX_FMT_YUV422P10;
741 *fmt++ = AV_PIX_FMT_YUV420P10;
744 #if CONFIG_H264_VDPAU_HWACCEL
745 *fmt++ = AV_PIX_FMT_VDPAU;
748 if (h->avctx->colorspace == AVCOL_SPC_RGB)
749 *fmt++ = AV_PIX_FMT_GBRP;
750 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
751 *fmt++ = AV_PIX_FMT_YUVJ444P;
753 *fmt++ = AV_PIX_FMT_YUV444P;
754 } else if (CHROMA422(h)) {
755 if (h->avctx->color_range == AVCOL_RANGE_JPEG)
756 *fmt++ = AV_PIX_FMT_YUVJ422P;
758 *fmt++ = AV_PIX_FMT_YUV422P;
760 #if CONFIG_H264_DXVA2_HWACCEL
761 *fmt++ = AV_PIX_FMT_DXVA2_VLD;
763 #if CONFIG_H264_D3D11VA_HWACCEL
764 *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
766 #if CONFIG_H264_VAAPI_HWACCEL
767 *fmt++ = AV_PIX_FMT_VAAPI;
769 #if CONFIG_H264_VDA_HWACCEL
770 *fmt++ = AV_PIX_FMT_VDA_VLD;
771 *fmt++ = AV_PIX_FMT_VDA;
773 if (h->avctx->codec->pix_fmts)
774 choices = h->avctx->codec->pix_fmts;
775 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
776 *fmt++ = AV_PIX_FMT_YUVJ420P;
778 *fmt++ = AV_PIX_FMT_YUV420P;
782 av_log(h->avctx, AV_LOG_ERROR,
783 "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);
784 return AVERROR_INVALIDDATA;
787 *fmt = AV_PIX_FMT_NONE;
789 return ff_get_format(h->avctx, choices);
792 /* export coded and cropped frame dimensions to AVCodecContext */
793 static int init_dimensions(H264Context *h)
795 SPS *sps = h->ps.sps;
796 int width = h->width - (sps->crop_right + sps->crop_left);
797 int height = h->height - (sps->crop_top + sps->crop_bottom);
799 /* handle container cropping */
800 if (FFALIGN(h->avctx->width, 16) == FFALIGN(width, 16) &&
801 FFALIGN(h->avctx->height, 16) == FFALIGN(height, 16)) {
802 width = h->avctx->width;
803 height = h->avctx->height;
806 if (width <= 0 || height <= 0) {
807 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
809 if (h->avctx->err_recognition & AV_EF_EXPLODE)
810 return AVERROR_INVALIDDATA;
812 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
823 h->avctx->coded_width = h->width;
824 h->avctx->coded_height = h->height;
825 h->avctx->width = width;
826 h->avctx->height = height;
831 static int h264_slice_header_init(H264Context *h)
833 const SPS *sps = h->ps.sps;
836 ff_set_sar(h->avctx, sps->sar);
837 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
838 &h->chroma_x_shift, &h->chroma_y_shift);
840 if (sps->timing_info_present_flag) {
841 int64_t den = sps->time_scale;
842 if (h->sei.unregistered.x264_build < 44U)
844 av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
845 sps->num_units_in_tick, den, 1 << 30);
848 ff_h264_free_tables(h);
851 h->prev_interlaced_frame = 1;
854 ret = ff_h264_alloc_tables(h);
856 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
860 if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 10) {
861 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
862 sps->bit_depth_luma);
863 return AVERROR_INVALIDDATA;
866 h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
867 h->pixel_shift = sps->bit_depth_luma > 8;
868 h->chroma_format_idc = sps->chroma_format_idc;
869 h->bit_depth_luma = sps->bit_depth_luma;
871 ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
872 sps->chroma_format_idc);
873 ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
874 ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
875 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
876 sps->chroma_format_idc);
877 ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
879 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
880 ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
882 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
886 for (i = 0; i < h->nb_slice_ctx; i++) {
887 H264SliceContext *sl = &h->slice_ctx[i];
890 sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
891 sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
892 sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
894 if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
895 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
901 h->context_initialized = 1;
906 static int h264_init_ps(H264Context *h, const H264SliceContext *sl)
909 int needs_reinit = 0, ret;
911 h->ps.pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
912 if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
913 h->ps.sps = (SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data;
915 if (h->bit_depth_luma != h->ps.sps->bit_depth_luma ||
916 h->chroma_format_idc != h->ps.sps->chroma_format_idc)
921 h->avctx->profile = ff_h264_get_profile(sps);
922 h->avctx->level = sps->level_idc;
923 h->avctx->refs = sps->ref_frame_count;
925 if (h->mb_width != sps->mb_width ||
926 h->mb_height != sps->mb_height)
929 h->mb_width = sps->mb_width;
930 h->mb_height = sps->mb_height;
931 h->mb_num = h->mb_width * h->mb_height;
932 h->mb_stride = h->mb_width + 1;
934 h->b_stride = h->mb_width * 4;
936 h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
938 h->width = 16 * h->mb_width;
939 h->height = 16 * h->mb_height;
941 ret = init_dimensions(h);
945 if (sps->video_signal_type_present_flag) {
946 h->avctx->color_range = sps->full_range ? AVCOL_RANGE_JPEG
948 if (sps->colour_description_present_flag) {
949 if (h->avctx->colorspace != sps->colorspace)
951 h->avctx->color_primaries = sps->color_primaries;
952 h->avctx->color_trc = sps->color_trc;
953 h->avctx->colorspace = sps->colorspace;
957 if (!h->context_initialized || needs_reinit) {
958 h->context_initialized = 0;
959 if (sl != h->slice_ctx) {
960 av_log(h->avctx, AV_LOG_ERROR,
961 "changing width %d -> %d / height %d -> %d on "
963 h->width, h->avctx->coded_width,
964 h->height, h->avctx->coded_height,
965 h->current_slice + 1);
966 return AVERROR_INVALIDDATA;
969 ff_h264_flush_change(h);
971 if ((ret = get_pixel_format(h)) < 0)
973 h->avctx->pix_fmt = ret;
975 av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
976 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
978 if ((ret = h264_slice_header_init(h)) < 0) {
979 av_log(h->avctx, AV_LOG_ERROR,
980 "h264_slice_header_init() failed\n");
988 static int h264_export_frame_props(H264Context *h)
990 const SPS *sps = h->ps.sps;
991 H264Picture *cur = h->cur_pic_ptr;
993 cur->f->interlaced_frame = 0;
994 cur->f->repeat_pict = 0;
996 /* Signal interlacing information externally. */
997 /* Prioritize picture timing SEI information over used
998 * decoding process if it exists. */
1000 if (sps->pic_struct_present_flag) {
1001 H264SEIPictureTiming *pt = &h->sei.picture_timing;
1002 switch (pt->pic_struct) {
1003 case SEI_PIC_STRUCT_FRAME:
1005 case SEI_PIC_STRUCT_TOP_FIELD:
1006 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1007 cur->f->interlaced_frame = 1;
1009 case SEI_PIC_STRUCT_TOP_BOTTOM:
1010 case SEI_PIC_STRUCT_BOTTOM_TOP:
1011 if (FIELD_OR_MBAFF_PICTURE(h))
1012 cur->f->interlaced_frame = 1;
1014 // try to flag soft telecine progressive
1015 cur->f->interlaced_frame = h->prev_interlaced_frame;
1017 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1018 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1019 /* Signal the possibility of telecined film externally
1020 * (pic_struct 5,6). From these hints, let the applications
1021 * decide if they apply deinterlacing. */
1022 cur->f->repeat_pict = 1;
1024 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1025 cur->f->repeat_pict = 2;
1027 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1028 cur->f->repeat_pict = 4;
1032 if ((pt->ct_type & 3) &&
1033 pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1034 cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
1036 /* Derive interlacing flag from used decoding process. */
1037 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
1039 h->prev_interlaced_frame = cur->f->interlaced_frame;
1041 if (cur->field_poc[0] != cur->field_poc[1]) {
1042 /* Derive top_field_first from field pocs. */
1043 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1045 if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
1046 /* Use picture timing SEI information. Even if it is a
1047 * information of a past frame, better than nothing. */
1048 if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1049 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1050 cur->f->top_field_first = 1;
1052 cur->f->top_field_first = 0;
1054 /* Most likely progressive */
1055 cur->f->top_field_first = 0;
1059 if (h->sei.frame_packing.present &&
1060 h->sei.frame_packing.arrangement_type >= 0 &&
1061 h->sei.frame_packing.arrangement_type <= 6 &&
1062 h->sei.frame_packing.content_interpretation_type > 0 &&
1063 h->sei.frame_packing.content_interpretation_type < 3) {
1064 H264SEIFramePacking *fp = &h->sei.frame_packing;
1065 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
1067 return AVERROR(ENOMEM);
1069 switch (fp->arrangement_type) {
1071 stereo->type = AV_STEREO3D_CHECKERBOARD;
1074 stereo->type = AV_STEREO3D_COLUMNS;
1077 stereo->type = AV_STEREO3D_LINES;
1080 if (fp->quincunx_subsampling)
1081 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
1083 stereo->type = AV_STEREO3D_SIDEBYSIDE;
1086 stereo->type = AV_STEREO3D_TOPBOTTOM;
1089 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
1092 stereo->type = AV_STEREO3D_2D;
1096 if (fp->content_interpretation_type == 2)
1097 stereo->flags = AV_STEREO3D_FLAG_INVERT;
1100 if (h->sei.display_orientation.present &&
1101 (h->sei.display_orientation.anticlockwise_rotation ||
1102 h->sei.display_orientation.hflip ||
1103 h->sei.display_orientation.vflip)) {
1104 H264SEIDisplayOrientation *o = &h->sei.display_orientation;
1105 double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
1106 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
1107 AV_FRAME_DATA_DISPLAYMATRIX,
1108 sizeof(int32_t) * 9);
1110 return AVERROR(ENOMEM);
1112 av_display_rotation_set((int32_t *)rotation->data, angle);
1113 av_display_matrix_flip((int32_t *)rotation->data,
1114 o->hflip, o->vflip);
1117 if (h->sei.afd.present) {
1118 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
1121 return AVERROR(ENOMEM);
1123 *sd->data = h->sei.afd.active_format_description;
1124 h->sei.afd.present = 0;
1127 if (h->sei.a53_caption.a53_caption) {
1128 H264SEIA53Caption *a53 = &h->sei.a53_caption;
1129 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
1130 AV_FRAME_DATA_A53_CC,
1131 a53->a53_caption_size);
1133 return AVERROR(ENOMEM);
1135 memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
1136 av_freep(&a53->a53_caption);
1137 a53->a53_caption_size = 0;
1143 static int h264_select_output_frame(H264Context *h)
1145 const SPS *sps = h->ps.sps;
1146 H264Picture *out = h->cur_pic_ptr;
1147 H264Picture *cur = h->cur_pic_ptr;
1148 int i, pics, out_of_order, out_idx;
1149 int invalid = 0, cnt = 0;
1152 if (sps->bitstream_restriction_flag ||
1153 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
1154 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
1158 while (h->delayed_pic[pics])
1161 assert(pics <= MAX_DELAYED_PIC_COUNT);
1163 h->delayed_pic[pics++] = cur;
1164 if (cur->reference == 0)
1165 cur->reference = DELAYED_PIC_REF;
1167 /* Frame reordering. This code takes pictures from coding order and sorts
1168 * them by their incremental POC value into display order. It supports POC
1169 * gaps, MMCO reset codes and random resets.
1170 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1171 * and/or can be closed down with a MMCO reset code. In sequences where
1172 * there is no delay, we can't detect that (since the frame was already
1173 * output to the user), so we also set h->mmco_reset to detect the MMCO
1175 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
1176 * we increase the delay between input and output. All frames affected by
1177 * the lag (e.g. those that should have been output before another frame
1178 * that we already returned to the user) will be dropped. This is a bug
1179 * that we will fix later. */
1180 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1181 cnt += out->poc < h->last_pocs[i];
1182 invalid += out->poc == INT_MIN;
1184 if (!h->mmco_reset && !cur->f->key_frame &&
1185 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1188 h->delayed_pic[pics - 2]->mmco_reset = 2;
1190 if (h->mmco_reset || cur->f->key_frame) {
1191 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1192 h->last_pocs[i] = INT_MIN;
1194 invalid = MAX_DELAYED_PIC_COUNT;
1196 out = h->delayed_pic[0];
1198 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1199 h->delayed_pic[i] &&
1200 !h->delayed_pic[i - 1]->mmco_reset &&
1201 !h->delayed_pic[i]->f->key_frame;
1203 if (h->delayed_pic[i]->poc < out->poc) {
1204 out = h->delayed_pic[i];
1207 if (h->avctx->has_b_frames == 0 &&
1208 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
1209 h->next_outputed_poc = INT_MIN;
1210 out_of_order = !out->f->key_frame && !h->mmco_reset &&
1211 (out->poc < h->next_outputed_poc);
1213 if (sps->bitstream_restriction_flag &&
1214 h->avctx->has_b_frames >= sps->num_reorder_frames) {
1215 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1216 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1217 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1218 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
1220 } else if (!h->avctx->has_b_frames &&
1221 ((h->next_outputed_poc != INT_MIN &&
1222 out->poc > h->next_outputed_poc + 2) ||
1223 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
1224 h->avctx->has_b_frames++;
1227 if (pics > h->avctx->has_b_frames) {
1228 out->reference &= ~DELAYED_PIC_REF;
1229 for (i = out_idx; h->delayed_pic[i]; i++)
1230 h->delayed_pic[i] = h->delayed_pic[i + 1];
1232 memmove(h->last_pocs, &h->last_pocs[1],
1233 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1234 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1235 if (!out_of_order && pics > h->avctx->has_b_frames) {
1236 av_frame_unref(h->output_frame);
1237 ret = av_frame_ref(h->output_frame, out->f);
1241 if (out->recovered) {
1242 // We have reached an recovery point and all frames after it in
1243 // display order are "recovered".
1244 h->frame_recovered |= FRAME_RECOVERED_SEI;
1246 out->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
1248 if (!out->recovered) {
1249 if (!(h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT))
1250 av_frame_unref(h->output_frame);
1252 h->output_frame->flags |= AV_FRAME_FLAG_CORRUPT;
1255 if (out->mmco_reset) {
1257 h->next_outputed_poc = out->poc;
1258 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1260 h->next_outputed_poc = INT_MIN;
1263 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
1264 h->next_outputed_poc = INT_MIN;
1266 h->next_outputed_poc = out->poc;
1271 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
1277 /* This function is called right after decoding the slice header for a first
1278 * slice in a field (or a frame). It decides whether we are decoding a new frame
1279 * or a second field in a pair and does the necessary setup.
1281 static int h264_field_start(H264Context *h, const H264SliceContext *sl,
1282 const H2645NAL *nal)
1286 int last_pic_structure, last_pic_droppable, ret;
1288 ret = h264_init_ps(h, sl);
1294 last_pic_droppable = h->droppable;
1295 last_pic_structure = h->picture_structure;
1296 h->droppable = (nal->ref_idc == 0);
1297 h->picture_structure = sl->picture_structure;
1299 h->poc.frame_num = sl->frame_num;
1300 h->poc.poc_lsb = sl->poc_lsb;
1301 h->poc.delta_poc_bottom = sl->delta_poc_bottom;
1302 h->poc.delta_poc[0] = sl->delta_poc[0];
1303 h->poc.delta_poc[1] = sl->delta_poc[1];
1305 /* Shorten frame num gaps so we don't have to allocate reference
1306 * frames just to throw them away */
1307 if (h->poc.frame_num != h->poc.prev_frame_num) {
1308 int unwrap_prev_frame_num = h->poc.prev_frame_num;
1309 int max_frame_num = 1 << sps->log2_max_frame_num;
1311 if (unwrap_prev_frame_num > h->poc.frame_num)
1312 unwrap_prev_frame_num -= max_frame_num;
1314 if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
1315 unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
1316 if (unwrap_prev_frame_num < 0)
1317 unwrap_prev_frame_num += max_frame_num;
1319 h->poc.prev_frame_num = unwrap_prev_frame_num;
1323 /* See if we have a decoded first field looking for a pair...
1324 * Here, we're using that to see if we should mark previously
1325 * decode frames as "finished".
1326 * We have to do that before the "dummy" in-between frame allocation,
1327 * since that can modify s->current_picture_ptr. */
1328 if (h->first_field) {
1329 assert(h->cur_pic_ptr);
1330 assert(h->cur_pic_ptr->f->buf[0]);
1331 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1333 /* figure out if we have a complementary field pair */
1334 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1335 /* Previous field is unmatched. Don't display it, but let it
1336 * remain for reference if marked as such. */
1337 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1338 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1339 last_pic_structure == PICT_TOP_FIELD);
1342 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1343 /* This and previous field were reference, but had
1344 * different frame_nums. Consider this field first in
1345 * pair. Throw away previous field except for reference
1347 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1348 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1349 last_pic_structure == PICT_TOP_FIELD);
1352 /* Second field in complementary pair */
1353 if (!((last_pic_structure == PICT_TOP_FIELD &&
1354 h->picture_structure == PICT_BOTTOM_FIELD) ||
1355 (last_pic_structure == PICT_BOTTOM_FIELD &&
1356 h->picture_structure == PICT_TOP_FIELD))) {
1357 av_log(h->avctx, AV_LOG_ERROR,
1358 "Invalid field mode combination %d/%d\n",
1359 last_pic_structure, h->picture_structure);
1360 h->picture_structure = last_pic_structure;
1361 h->droppable = last_pic_droppable;
1362 return AVERROR_INVALIDDATA;
1363 } else if (last_pic_droppable != h->droppable) {
1364 avpriv_request_sample(h->avctx,
1365 "Found reference and non-reference fields in the same frame, which");
1366 h->picture_structure = last_pic_structure;
1367 h->droppable = last_pic_droppable;
1368 return AVERROR_PATCHWELCOME;
1374 while (h->poc.frame_num != h->poc.prev_frame_num &&
1375 h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
1376 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1377 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1378 h->poc.frame_num, h->poc.prev_frame_num);
1379 ret = initialize_cur_frame(h);
1385 h->poc.prev_frame_num++;
1386 h->poc.prev_frame_num %= 1 << sps->log2_max_frame_num;
1387 h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
1388 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1389 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1391 h->explicit_ref_marking = 0;
1392 ret = ff_h264_execute_ref_pic_marking(h);
1393 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1395 /* Error concealment: If a ref is missing, copy the previous ref
1397 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1398 * many assumptions about there being no actual duplicates.
1399 * FIXME: This does not copy padding for out-of-frame motion
1400 * vectors. Given we are concealing a lost frame, this probably
1401 * is not noticeable by comparison, but it should be fixed. */
1402 if (h->short_ref_count) {
1404 h->short_ref[0]->f->width == prev->f->width &&
1405 h->short_ref[0]->f->height == prev->f->height &&
1406 h->short_ref[0]->f->format == prev->f->format) {
1407 av_image_copy(h->short_ref[0]->f->data,
1408 h->short_ref[0]->f->linesize,
1409 (const uint8_t **)prev->f->data,
1414 h->short_ref[0]->poc = prev->poc + 2;
1416 h->short_ref[0]->frame_num = h->poc.prev_frame_num;
1420 /* See if we have a decoded first field looking for a pair...
1421 * We're using that to see whether to continue decoding in that
1422 * frame, or to allocate a new one. */
1423 if (h->first_field) {
1424 assert(h->cur_pic_ptr);
1425 assert(h->cur_pic_ptr->f->buf[0]);
1426 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1428 /* figure out if we have a complementary field pair */
1429 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1430 /* Previous field is unmatched. Don't display it, but let it
1431 * remain for reference if marked as such. */
1432 h->cur_pic_ptr = NULL;
1433 h->first_field = FIELD_PICTURE(h);
1435 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1436 /* This and the previous field had different frame_nums.
1437 * Consider this field first in pair. Throw away previous
1438 * one except for reference purposes. */
1440 h->cur_pic_ptr = NULL;
1442 /* Second field in complementary pair */
1447 /* Frame or first field in a potentially complementary pair */
1448 h->first_field = FIELD_PICTURE(h);
1451 if (!FIELD_PICTURE(h) || h->first_field) {
1452 if (h264_frame_start(h) < 0) {
1454 return AVERROR_INVALIDDATA;
1457 release_unused_pictures(h, 0);
1460 ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
1461 h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
1463 memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
1464 h->nb_mmco = sl->nb_mmco;
1465 h->explicit_ref_marking = sl->explicit_ref_marking;
1467 h->picture_idr = nal->type == H264_NAL_IDR_SLICE;
1469 if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1470 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
1471 ((1 << h->ps.sps->log2_max_frame_num) - 1);
1474 h->cur_pic_ptr->f->key_frame |= (nal->type == H264_NAL_IDR_SLICE) ||
1475 (h->sei.recovery_point.recovery_frame_cnt >= 0);
1477 if (nal->type == H264_NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
1478 h->recovery_frame = -1;
1479 h->cur_pic_ptr->recovered = 1;
1481 // If we have an IDR, all frames after it in decoded order are
1483 if (nal->type == H264_NAL_IDR_SLICE)
1484 h->frame_recovered |= FRAME_RECOVERED_IDR;
1485 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1487 /* Set the frame properties/side data. Only done for the second field in
1488 * field coded frames, since some SEI information is present for each field
1489 * and is merged by the SEI parsing code. */
1490 if (!FIELD_PICTURE(h) || !h->first_field) {
1491 ret = h264_export_frame_props(h);
1495 ret = h264_select_output_frame(h);
1500 if (h->avctx->hwaccel) {
1501 ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0);
1509 static int h264_slice_header_parse(H264SliceContext *sl, const H2645NAL *nal,
1510 const H264ParamSets *ps, AVCodecContext *avctx)
1515 unsigned int slice_type, tmp, i;
1516 int field_pic_flag, bottom_field_flag, picture_structure;
1518 sl->first_mb_addr = get_ue_golomb(&sl->gb);
1520 slice_type = get_ue_golomb_31(&sl->gb);
1521 if (slice_type > 9) {
1522 av_log(avctx, AV_LOG_ERROR,
1523 "slice type %d too large at %d\n",
1524 slice_type, sl->first_mb_addr);
1525 return AVERROR_INVALIDDATA;
1527 if (slice_type > 4) {
1529 sl->slice_type_fixed = 1;
1531 sl->slice_type_fixed = 0;
1533 slice_type = ff_h264_golomb_to_pict_type[slice_type];
1534 sl->slice_type = slice_type;
1535 sl->slice_type_nos = slice_type & 3;
1537 if (nal->type == H264_NAL_IDR_SLICE &&
1538 sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1539 av_log(avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
1540 return AVERROR_INVALIDDATA;
1543 sl->pps_id = get_ue_golomb(&sl->gb);
1544 if (sl->pps_id >= MAX_PPS_COUNT) {
1545 av_log(avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
1546 return AVERROR_INVALIDDATA;
1548 if (!ps->pps_list[sl->pps_id]) {
1549 av_log(avctx, AV_LOG_ERROR,
1550 "non-existing PPS %u referenced\n",
1552 return AVERROR_INVALIDDATA;
1554 pps = (const PPS*)ps->pps_list[sl->pps_id]->data;
1556 if (!ps->sps_list[pps->sps_id]) {
1557 av_log(avctx, AV_LOG_ERROR,
1558 "non-existing SPS %u referenced\n", pps->sps_id);
1559 return AVERROR_INVALIDDATA;
1561 sps = (const SPS*)ps->sps_list[pps->sps_id]->data;
1563 sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
1567 if (sps->frame_mbs_only_flag) {
1568 picture_structure = PICT_FRAME;
1570 field_pic_flag = get_bits1(&sl->gb);
1571 if (field_pic_flag) {
1572 bottom_field_flag = get_bits1(&sl->gb);
1573 picture_structure = PICT_TOP_FIELD + bottom_field_flag;
1575 picture_structure = PICT_FRAME;
1578 sl->picture_structure = picture_structure;
1579 sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
1581 if (picture_structure == PICT_FRAME) {
1582 sl->curr_pic_num = sl->frame_num;
1583 sl->max_pic_num = 1 << sps->log2_max_frame_num;
1585 sl->curr_pic_num = 2 * sl->frame_num + 1;
1586 sl->max_pic_num = 1 << (sps->log2_max_frame_num + 1);
1589 if (nal->type == H264_NAL_IDR_SLICE)
1590 get_ue_golomb(&sl->gb); /* idr_pic_id */
1592 if (sps->poc_type == 0) {
1593 sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
1595 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1596 sl->delta_poc_bottom = get_se_golomb(&sl->gb);
1599 if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
1600 sl->delta_poc[0] = get_se_golomb(&sl->gb);
1602 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1603 sl->delta_poc[1] = get_se_golomb(&sl->gb);
1606 sl->redundant_pic_count = 0;
1607 if (pps->redundant_pic_cnt_present)
1608 sl->redundant_pic_count = get_ue_golomb(&sl->gb);
1610 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1611 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1613 ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
1614 &sl->gb, pps, sl->slice_type_nos,
1619 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1620 ret = ff_h264_decode_ref_pic_list_reordering(sl, avctx);
1622 sl->ref_count[1] = sl->ref_count[0] = 0;
1627 sl->pwt.use_weight = 0;
1628 for (i = 0; i < 2; i++) {
1629 sl->pwt.luma_weight_flag[i] = 0;
1630 sl->pwt.chroma_weight_flag[i] = 0;
1632 if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
1633 (pps->weighted_bipred_idc == 1 &&
1634 sl->slice_type_nos == AV_PICTURE_TYPE_B))
1635 ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
1636 sl->slice_type_nos, &sl->pwt);
1638 sl->explicit_ref_marking = 0;
1640 ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, avctx);
1641 if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
1642 return AVERROR_INVALIDDATA;
1645 if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1646 tmp = get_ue_golomb_31(&sl->gb);
1648 av_log(avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1649 return AVERROR_INVALIDDATA;
1651 sl->cabac_init_idc = tmp;
1654 sl->last_qscale_diff = 0;
1655 tmp = pps->init_qp + get_se_golomb(&sl->gb);
1656 if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
1657 av_log(avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1658 return AVERROR_INVALIDDATA;
1661 sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
1662 sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
1663 // FIXME qscale / qp ... stuff
1664 if (sl->slice_type == AV_PICTURE_TYPE_SP)
1665 get_bits1(&sl->gb); /* sp_for_switch_flag */
1666 if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1667 sl->slice_type == AV_PICTURE_TYPE_SI)
1668 get_se_golomb(&sl->gb); /* slice_qs_delta */
1670 sl->deblocking_filter = 1;
1671 sl->slice_alpha_c0_offset = 0;
1672 sl->slice_beta_offset = 0;
1673 if (pps->deblocking_filter_parameters_present) {
1674 tmp = get_ue_golomb_31(&sl->gb);
1676 av_log(avctx, AV_LOG_ERROR,
1677 "deblocking_filter_idc %u out of range\n", tmp);
1678 return AVERROR_INVALIDDATA;
1680 sl->deblocking_filter = tmp;
1681 if (sl->deblocking_filter < 2)
1682 sl->deblocking_filter ^= 1; // 1<->0
1684 if (sl->deblocking_filter) {
1685 sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
1686 sl->slice_beta_offset = get_se_golomb(&sl->gb) * 2;
1687 if (sl->slice_alpha_c0_offset > 12 ||
1688 sl->slice_alpha_c0_offset < -12 ||
1689 sl->slice_beta_offset > 12 ||
1690 sl->slice_beta_offset < -12) {
1691 av_log(avctx, AV_LOG_ERROR,
1692 "deblocking filter parameters %d %d out of range\n",
1693 sl->slice_alpha_c0_offset, sl->slice_beta_offset);
1694 return AVERROR_INVALIDDATA;
1702 /* do all the per-slice initialization needed before we can start decoding the
1704 static int h264_slice_init(H264Context *h, H264SliceContext *sl,
1705 const H2645NAL *nal)
1709 if (h->current_slice > 0) {
1710 if (h->ps.pps != (const PPS*)h->ps.pps_list[sl->pps_id]->data) {
1711 av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
1712 return AVERROR_INVALIDDATA;
1715 if (h->picture_structure != sl->picture_structure ||
1716 h->droppable != (nal->ref_idc == 0)) {
1717 av_log(h->avctx, AV_LOG_ERROR,
1718 "Changing field mode (%d -> %d) between slices is not allowed\n",
1719 h->picture_structure, sl->picture_structure);
1720 return AVERROR_INVALIDDATA;
1721 } else if (!h->cur_pic_ptr) {
1722 av_log(h->avctx, AV_LOG_ERROR,
1723 "unset cur_pic_ptr on slice %d\n",
1724 h->current_slice + 1);
1725 return AVERROR_INVALIDDATA;
1729 if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {
1730 av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");
1731 return AVERROR_INVALIDDATA;
1734 assert(h->mb_num == h->mb_width * h->mb_height);
1735 if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1736 sl->first_mb_addr >= h->mb_num) {
1737 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1738 return AVERROR_INVALIDDATA;
1740 sl->resync_mb_x = sl->mb_x = sl->first_mb_addr % h->mb_width;
1741 sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
1742 FIELD_OR_MBAFF_PICTURE(h);
1743 if (h->picture_structure == PICT_BOTTOM_FIELD)
1744 sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
1745 assert(sl->mb_y < h->mb_height);
1747 ret = ff_h264_build_ref_list(h, sl);
1751 if (h->ps.pps->weighted_bipred_idc == 2 &&
1752 sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1753 implicit_weight_table(h, sl, -1);
1754 if (FRAME_MBAFF(h)) {
1755 implicit_weight_table(h, sl, 0);
1756 implicit_weight_table(h, sl, 1);
1760 if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
1761 ff_h264_direct_dist_scale_factor(h, sl);
1762 ff_h264_direct_ref_list_init(h, sl);
1764 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1765 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
1766 sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
1767 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
1768 sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
1769 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1771 sl->deblocking_filter = 0;
1773 if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
1774 if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
1775 /* Cheat slightly for speed:
1776 * Do not bother to deblock across slices. */
1777 sl->deblocking_filter = 2;
1779 h->postpone_filter = 1;
1782 sl->qp_thresh = 15 -
1783 FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
1785 h->ps.pps->chroma_qp_index_offset[0],
1786 h->ps.pps->chroma_qp_index_offset[1]) +
1787 6 * (h->ps.sps->bit_depth_luma - 8);
1789 sl->slice_num = ++h->current_slice;
1790 if (sl->slice_num >= MAX_SLICES) {
1791 av_log(h->avctx, AV_LOG_ERROR,
1792 "Too many slices, increase MAX_SLICES and recompile\n");
1795 for (j = 0; j < 2; j++) {
1797 int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
1798 for (i = 0; i < 16; i++) {
1800 if (j < sl->list_count && i < sl->ref_count[j] &&
1801 sl->ref_list[j][i].parent->f->buf[0]) {
1803 AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
1804 for (k = 0; k < h->short_ref_count; k++)
1805 if (h->short_ref[k]->f->buf[0]->buffer == buf) {
1809 for (k = 0; k < h->long_ref_count; k++)
1810 if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
1811 id_list[i] = h->short_ref_count + k;
1819 for (i = 0; i < 16; i++)
1820 ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
1822 ref2frm[18 + 1] = -1;
1823 for (i = 16; i < 48; i++)
1824 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
1825 (sl->ref_list[j][i].reference & 3);
1828 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
1829 av_log(h->avctx, AV_LOG_DEBUG,
1830 "slice:%d %s mb:%d %c%s%s frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
1832 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
1833 sl->mb_y * h->mb_width + sl->mb_x,
1834 av_get_picture_type_char(sl->slice_type),
1835 sl->slice_type_fixed ? " fix" : "",
1836 nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",
1838 h->cur_pic_ptr->field_poc[0],
1839 h->cur_pic_ptr->field_poc[1],
1840 sl->ref_count[0], sl->ref_count[1],
1842 sl->deblocking_filter,
1843 sl->slice_alpha_c0_offset, sl->slice_beta_offset,
1845 sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
1846 sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
1852 int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)
1854 H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
1859 ret = h264_slice_header_parse(sl, nal, &h->ps, h->avctx);
1863 // discard redundant pictures
1864 if (sl->redundant_pic_count > 0)
1867 if (!h->setup_finished) {
1868 if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
1869 // this slice starts a new field
1870 // first decode any pending queued slices
1871 if (h->nb_slice_ctx_queued) {
1872 H264SliceContext tmp_ctx;
1874 ret = ff_h264_execute_decode_slices(h);
1875 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1878 memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));
1879 memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));
1880 memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));
1884 if (h->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
1885 ff_h264_field_end(h, sl, 1);
1888 h->current_slice = 0;
1889 if (!h->first_field) {
1890 if (h->cur_pic_ptr && !h->droppable) {
1891 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1892 h->picture_structure == PICT_BOTTOM_FIELD);
1894 h->cur_pic_ptr = NULL;
1898 if (h->current_slice == 0) {
1899 ret = h264_field_start(h, sl, nal);
1905 ret = h264_slice_init(h, sl, nal);
1909 if ((h->avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1910 (h->avctx->skip_frame < AVDISCARD_BIDIR ||
1911 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1912 (h->avctx->skip_frame < AVDISCARD_NONKEY ||
1913 h->cur_pic_ptr->f->key_frame) &&
1914 h->avctx->skip_frame < AVDISCARD_ALL) {
1915 h->nb_slice_ctx_queued++;
1921 int ff_h264_get_slice_type(const H264SliceContext *sl)
1923 switch (sl->slice_type) {
1924 case AV_PICTURE_TYPE_P:
1926 case AV_PICTURE_TYPE_B:
1928 case AV_PICTURE_TYPE_I:
1930 case AV_PICTURE_TYPE_SP:
1932 case AV_PICTURE_TYPE_SI:
1935 return AVERROR_INVALIDDATA;
1939 static av_always_inline void fill_filter_caches_inter(const H264Context *h,
1940 H264SliceContext *sl,
1941 int mb_type, int top_xy,
1942 int left_xy[LEFT_MBS],
1944 int left_type[LEFT_MBS],
1945 int mb_xy, int list)
1947 int b_stride = h->b_stride;
1948 int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
1949 int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
1950 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
1951 if (USES_LIST(top_type, list)) {
1952 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
1953 const int b8_xy = 4 * top_xy + 2;
1954 const int *ref2frm = &h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1955 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
1956 ref_cache[0 - 1 * 8] =
1957 ref_cache[1 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 0]];
1958 ref_cache[2 - 1 * 8] =
1959 ref_cache[3 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 1]];
1961 AV_ZERO128(mv_dst - 1 * 8);
1962 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1965 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
1966 if (USES_LIST(left_type[LTOP], list)) {
1967 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
1968 const int b8_xy = 4 * left_xy[LTOP] + 1;
1969 const int *ref2frm = &h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1970 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
1971 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
1972 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
1973 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
1975 ref_cache[-1 + 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
1976 ref_cache[-1 + 16] =
1977 ref_cache[-1 + 24] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
1979 AV_ZERO32(mv_dst - 1 + 0);
1980 AV_ZERO32(mv_dst - 1 + 8);
1981 AV_ZERO32(mv_dst - 1 + 16);
1982 AV_ZERO32(mv_dst - 1 + 24);
1985 ref_cache[-1 + 16] =
1986 ref_cache[-1 + 24] = LIST_NOT_USED;
1991 if (!USES_LIST(mb_type, list)) {
1992 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
1993 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1994 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1995 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1996 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2001 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
2002 const int *ref2frm = &h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
2003 uint32_t ref01 = (pack16to32(ref2frm[ref[0]], ref2frm[ref[1]]) & 0x00FF00FF) * 0x0101;
2004 uint32_t ref23 = (pack16to32(ref2frm[ref[2]], ref2frm[ref[3]]) & 0x00FF00FF) * 0x0101;
2005 AV_WN32A(&ref_cache[0 * 8], ref01);
2006 AV_WN32A(&ref_cache[1 * 8], ref01);
2007 AV_WN32A(&ref_cache[2 * 8], ref23);
2008 AV_WN32A(&ref_cache[3 * 8], ref23);
2012 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
2013 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
2014 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
2015 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
2016 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
2021 * @return non zero if the loop filter can be skipped
2023 static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
2025 const int mb_xy = sl->mb_xy;
2026 int top_xy, left_xy[LEFT_MBS];
2027 int top_type, left_type[LEFT_MBS];
2031 top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
2033 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
2034 if (FRAME_MBAFF(h)) {
2035 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
2036 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
2038 if (left_mb_field_flag != curr_mb_field_flag)
2039 left_xy[LTOP] -= h->mb_stride;
2041 if (curr_mb_field_flag)
2042 top_xy += h->mb_stride &
2043 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
2044 if (left_mb_field_flag != curr_mb_field_flag)
2045 left_xy[LBOT] += h->mb_stride;
2049 sl->top_mb_xy = top_xy;
2050 sl->left_mb_xy[LTOP] = left_xy[LTOP];
2051 sl->left_mb_xy[LBOT] = left_xy[LBOT];
2053 /* For sufficiently low qp, filtering wouldn't do anything.
2054 * This is a conservative estimate: could also check beta_offset
2055 * and more accurate chroma_qp. */
2056 int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
2057 int qp = h->cur_pic.qscale_table[mb_xy];
2058 if (qp <= qp_thresh &&
2059 (left_xy[LTOP] < 0 ||
2060 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
2062 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
2063 if (!FRAME_MBAFF(h))
2065 if ((left_xy[LTOP] < 0 ||
2066 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
2067 (top_xy < h->mb_stride ||
2068 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
2073 top_type = h->cur_pic.mb_type[top_xy];
2074 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
2075 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
2076 if (sl->deblocking_filter == 2) {
2077 if (h->slice_table[top_xy] != sl->slice_num)
2079 if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
2080 left_type[LTOP] = left_type[LBOT] = 0;
2082 if (h->slice_table[top_xy] == 0xFFFF)
2084 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
2085 left_type[LTOP] = left_type[LBOT] = 0;
2087 sl->top_type = top_type;
2088 sl->left_type[LTOP] = left_type[LTOP];
2089 sl->left_type[LBOT] = left_type[LBOT];
2091 if (IS_INTRA(mb_type))
2094 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2095 top_type, left_type, mb_xy, 0);
2096 if (sl->list_count == 2)
2097 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2098 top_type, left_type, mb_xy, 1);
2100 nnz = h->non_zero_count[mb_xy];
2101 nnz_cache = sl->non_zero_count_cache;
2102 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
2103 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
2104 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
2105 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
2106 sl->cbp = h->cbp_table[mb_xy];
2109 nnz = h->non_zero_count[top_xy];
2110 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
2113 if (left_type[LTOP]) {
2114 nnz = h->non_zero_count[left_xy[LTOP]];
2115 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
2116 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
2117 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
2118 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
2121 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
2122 * from what the loop filter needs */
2123 if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
2124 if (IS_8x8DCT(top_type)) {
2125 nnz_cache[4 + 8 * 0] =
2126 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
2127 nnz_cache[6 + 8 * 0] =
2128 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
2130 if (IS_8x8DCT(left_type[LTOP])) {
2131 nnz_cache[3 + 8 * 1] =
2132 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
2134 if (IS_8x8DCT(left_type[LBOT])) {
2135 nnz_cache[3 + 8 * 3] =
2136 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
2139 if (IS_8x8DCT(mb_type)) {
2140 nnz_cache[scan8[0]] =
2141 nnz_cache[scan8[1]] =
2142 nnz_cache[scan8[2]] =
2143 nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
2145 nnz_cache[scan8[0 + 4]] =
2146 nnz_cache[scan8[1 + 4]] =
2147 nnz_cache[scan8[2 + 4]] =
2148 nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
2150 nnz_cache[scan8[0 + 8]] =
2151 nnz_cache[scan8[1 + 8]] =
2152 nnz_cache[scan8[2 + 8]] =
2153 nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
2155 nnz_cache[scan8[0 + 12]] =
2156 nnz_cache[scan8[1 + 12]] =
2157 nnz_cache[scan8[2 + 12]] =
2158 nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
2165 static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
2167 uint8_t *dest_y, *dest_cb, *dest_cr;
2168 int linesize, uvlinesize, mb_x, mb_y;
2169 const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
2170 const int old_slice_type = sl->slice_type;
2171 const int pixel_shift = h->pixel_shift;
2172 const int block_h = 16 >> h->chroma_y_shift;
2174 if (h->postpone_filter)
2177 if (sl->deblocking_filter) {
2178 for (mb_x = start_x; mb_x < end_x; mb_x++)
2179 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
2181 mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
2182 mb_type = h->cur_pic.mb_type[mb_xy];
2186 sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2190 dest_y = h->cur_pic.f->data[0] +
2191 ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
2192 dest_cb = h->cur_pic.f->data[1] +
2193 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2194 mb_y * sl->uvlinesize * block_h;
2195 dest_cr = h->cur_pic.f->data[2] +
2196 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2197 mb_y * sl->uvlinesize * block_h;
2198 // FIXME simplify above
2201 linesize = sl->mb_linesize = sl->linesize * 2;
2202 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
2203 if (mb_y & 1) { // FIXME move out of this function?
2204 dest_y -= sl->linesize * 15;
2205 dest_cb -= sl->uvlinesize * (block_h - 1);
2206 dest_cr -= sl->uvlinesize * (block_h - 1);
2209 linesize = sl->mb_linesize = sl->linesize;
2210 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
2212 backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
2214 if (fill_filter_caches(h, sl, mb_type))
2216 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
2217 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
2219 if (FRAME_MBAFF(h)) {
2220 ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
2221 linesize, uvlinesize);
2223 ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
2224 dest_cr, linesize, uvlinesize);
2228 sl->slice_type = old_slice_type;
2230 sl->mb_y = end_mb_y - FRAME_MBAFF(h);
2231 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
2232 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
2235 static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
2237 const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
2238 int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
2239 h->cur_pic.mb_type[mb_xy - 1] :
2240 (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
2241 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
2242 sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2246 * Draw edges and report progress for the last MB row.
2248 static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
2250 int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
2251 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
2252 int height = 16 << FRAME_MBAFF(h);
2253 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
2255 if (sl->deblocking_filter) {
2256 if ((top + height) >= pic_height)
2257 height += deblock_border;
2258 top -= deblock_border;
2261 if (top >= pic_height || (top + height) < 0)
2264 height = FFMIN(height, pic_height - top);
2266 height = top + height;
2270 ff_h264_draw_horiz_band(h, sl, top, height);
2275 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
2276 h->picture_structure == PICT_BOTTOM_FIELD);
2279 static void er_add_slice(H264SliceContext *sl,
2280 int startx, int starty,
2281 int endx, int endy, int status)
2283 #if CONFIG_ERROR_RESILIENCE
2284 ERContext *er = &sl->er;
2286 if (!sl->h264->enable_er)
2289 er->ref_count = sl->ref_count[0];
2290 ff_er_add_slice(er, startx, starty, endx, endy, status);
2294 static int decode_slice(struct AVCodecContext *avctx, void *arg)
2296 H264SliceContext *sl = arg;
2297 const H264Context *h = sl->h264;
2298 int lf_x_start = sl->mb_x;
2299 int orig_deblock = sl->deblocking_filter;
2302 sl->linesize = h->cur_pic_ptr->f->linesize[0];
2303 sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
2305 ret = alloc_scratch_buffers(sl, sl->linesize);
2309 sl->mb_skip_run = -1;
2311 if (h->postpone_filter)
2312 sl->deblocking_filter = 0;
2314 sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
2315 (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
2317 if (h->ps.pps->cabac) {
2319 align_get_bits(&sl->gb);
2322 ff_init_cabac_decoder(&sl->cabac,
2323 sl->gb.buffer + get_bits_count(&sl->gb) / 8,
2324 (get_bits_left(&sl->gb) + 7) / 8);
2326 ff_h264_init_cabac_states(h, sl);
2332 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2333 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2334 sl->next_slice_idx);
2335 return AVERROR_INVALIDDATA;
2338 ret = ff_h264_decode_mb_cabac(h, sl);
2339 // STOP_TIMER("decode_mb_cabac")
2342 ff_h264_hl_decode_mb(h, sl);
2344 // FIXME optimal? or let mb_decode decode 16x32 ?
2345 if (ret >= 0 && FRAME_MBAFF(h)) {
2348 ret = ff_h264_decode_mb_cabac(h, sl);
2351 ff_h264_hl_decode_mb(h, sl);
2354 eos = get_cabac_terminate(&sl->cabac);
2356 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
2357 sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2358 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2359 sl->mb_y, ER_MB_END);
2360 if (sl->mb_x >= lf_x_start)
2361 loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
2364 if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2365 av_log(h->avctx, AV_LOG_ERROR,
2366 "error while decoding MB %d %d, bytestream %td\n",
2368 sl->cabac.bytestream_end - sl->cabac.bytestream);
2369 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2370 sl->mb_y, ER_MB_ERROR);
2371 return AVERROR_INVALIDDATA;
2374 if (++sl->mb_x >= h->mb_width) {
2375 loop_filter(h, sl, lf_x_start, sl->mb_x);
2376 sl->mb_x = lf_x_start = 0;
2377 decode_finish_row(h, sl);
2379 if (FIELD_OR_MBAFF_PICTURE(h)) {
2381 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2382 predict_field_decoding_flag(h, sl);
2386 if (eos || sl->mb_y >= h->mb_height) {
2387 ff_tlog(h->avctx, "slice end %d %d\n",
2388 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2389 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2390 sl->mb_y, ER_MB_END);
2391 if (sl->mb_x > lf_x_start)
2392 loop_filter(h, sl, lf_x_start, sl->mb_x);
2400 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2401 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2402 sl->next_slice_idx);
2403 return AVERROR_INVALIDDATA;
2406 ret = ff_h264_decode_mb_cavlc(h, sl);
2409 ff_h264_hl_decode_mb(h, sl);
2411 // FIXME optimal? or let mb_decode decode 16x32 ?
2412 if (ret >= 0 && FRAME_MBAFF(h)) {
2414 ret = ff_h264_decode_mb_cavlc(h, sl);
2417 ff_h264_hl_decode_mb(h, sl);
2422 av_log(h->avctx, AV_LOG_ERROR,
2423 "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
2424 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2425 sl->mb_y, ER_MB_ERROR);
2429 if (++sl->mb_x >= h->mb_width) {
2430 loop_filter(h, sl, lf_x_start, sl->mb_x);
2431 sl->mb_x = lf_x_start = 0;
2432 decode_finish_row(h, sl);
2434 if (FIELD_OR_MBAFF_PICTURE(h)) {
2436 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2437 predict_field_decoding_flag(h, sl);
2439 if (sl->mb_y >= h->mb_height) {
2440 ff_tlog(h->avctx, "slice end %d %d\n",
2441 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2443 if (get_bits_left(&sl->gb) == 0) {
2444 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2445 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2449 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2450 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2452 return AVERROR_INVALIDDATA;
2457 if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
2458 ff_tlog(h->avctx, "slice end %d %d\n",
2459 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2461 if (get_bits_left(&sl->gb) == 0) {
2462 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2463 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2464 if (sl->mb_x > lf_x_start)
2465 loop_filter(h, sl, lf_x_start, sl->mb_x);
2469 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2470 sl->mb_y, ER_MB_ERROR);
2472 return AVERROR_INVALIDDATA;
2479 sl->deblocking_filter = orig_deblock;
2484 * Call decode_slice() for each context.
2486 * @param h h264 master context
2488 int ff_h264_execute_decode_slices(H264Context *h)
2490 AVCodecContext *const avctx = h->avctx;
2491 H264SliceContext *sl;
2492 int context_count = h->nb_slice_ctx_queued;
2496 if (h->avctx->hwaccel || context_count < 1)
2498 if (context_count == 1) {
2500 h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2501 h->postpone_filter = 0;
2503 ret = decode_slice(avctx, &h->slice_ctx[0]);
2504 h->mb_y = h->slice_ctx[0].mb_y;
2508 for (i = 0; i < context_count; i++) {
2509 int next_slice_idx = h->mb_width * h->mb_height;
2512 sl = &h->slice_ctx[i];
2513 sl->er.error_count = 0;
2515 /* make sure none of those slices overlap */
2516 slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2517 for (j = 0; j < context_count; j++) {
2518 H264SliceContext *sl2 = &h->slice_ctx[j];
2519 int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2521 if (i == j || slice_idx2 < slice_idx)
2523 next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2525 sl->next_slice_idx = next_slice_idx;
2528 avctx->execute(avctx, decode_slice, h->slice_ctx,
2529 NULL, context_count, sizeof(h->slice_ctx[0]));
2531 /* pull back stuff from slices to master context */
2532 sl = &h->slice_ctx[context_count - 1];
2534 for (i = 1; i < context_count; i++)
2535 h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
2537 if (h->postpone_filter) {
2538 h->postpone_filter = 0;
2540 for (i = 0; i < context_count; i++) {
2543 sl = &h->slice_ctx[i];
2544 y_end = FFMIN(sl->mb_y + 1, h->mb_height);
2545 x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
2547 for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
2549 loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
2550 j == y_end - 1 ? x_end : h->mb_width);
2557 h->nb_slice_ctx_queued = 0;