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 h->avctx->coded_width = h->width;
807 h->avctx->coded_height = h->height;
808 h->avctx->width = width;
809 h->avctx->height = height;
814 static int h264_slice_header_init(H264Context *h)
816 const SPS *sps = h->ps.sps;
819 ff_set_sar(h->avctx, sps->sar);
820 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
821 &h->chroma_x_shift, &h->chroma_y_shift);
823 if (sps->timing_info_present_flag) {
824 int64_t den = sps->time_scale;
825 if (h->sei.unregistered.x264_build < 44U)
827 av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
828 sps->num_units_in_tick, den, 1 << 30);
831 ff_h264_free_tables(h);
834 h->prev_interlaced_frame = 1;
837 ret = ff_h264_alloc_tables(h);
839 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
843 if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 10) {
844 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
845 sps->bit_depth_luma);
846 return AVERROR_INVALIDDATA;
849 h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
850 h->pixel_shift = sps->bit_depth_luma > 8;
851 h->chroma_format_idc = sps->chroma_format_idc;
852 h->bit_depth_luma = sps->bit_depth_luma;
854 ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
855 sps->chroma_format_idc);
856 ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
857 ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
858 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
859 sps->chroma_format_idc);
860 ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
862 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
863 ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
865 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
869 for (i = 0; i < h->nb_slice_ctx; i++) {
870 H264SliceContext *sl = &h->slice_ctx[i];
873 sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
874 sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
875 sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
877 if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
878 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
884 h->context_initialized = 1;
889 static int h264_init_ps(H264Context *h, const H264SliceContext *sl)
892 int needs_reinit = 0, ret;
894 h->ps.pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
895 if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
896 h->ps.sps = (SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data;
898 if (h->bit_depth_luma != h->ps.sps->bit_depth_luma ||
899 h->chroma_format_idc != h->ps.sps->chroma_format_idc)
904 h->avctx->profile = ff_h264_get_profile(sps);
905 h->avctx->level = sps->level_idc;
906 h->avctx->refs = sps->ref_frame_count;
908 if (h->mb_width != sps->mb_width ||
909 h->mb_height != sps->mb_height)
912 h->mb_width = sps->mb_width;
913 h->mb_height = sps->mb_height;
914 h->mb_num = h->mb_width * h->mb_height;
915 h->mb_stride = h->mb_width + 1;
917 h->b_stride = h->mb_width * 4;
919 h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
921 h->width = 16 * h->mb_width;
922 h->height = 16 * h->mb_height;
924 ret = init_dimensions(h);
928 if (sps->video_signal_type_present_flag) {
929 h->avctx->color_range = sps->full_range ? AVCOL_RANGE_JPEG
931 if (sps->colour_description_present_flag) {
932 if (h->avctx->colorspace != sps->colorspace)
934 h->avctx->color_primaries = sps->color_primaries;
935 h->avctx->color_trc = sps->color_trc;
936 h->avctx->colorspace = sps->colorspace;
940 if (!h->context_initialized || needs_reinit) {
941 h->context_initialized = 0;
942 if (sl != h->slice_ctx) {
943 av_log(h->avctx, AV_LOG_ERROR,
944 "changing width %d -> %d / height %d -> %d on "
946 h->width, h->avctx->coded_width,
947 h->height, h->avctx->coded_height,
948 h->current_slice + 1);
949 return AVERROR_INVALIDDATA;
952 ff_h264_flush_change(h);
954 if ((ret = get_pixel_format(h)) < 0)
956 h->avctx->pix_fmt = ret;
958 av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
959 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
961 if ((ret = h264_slice_header_init(h)) < 0) {
962 av_log(h->avctx, AV_LOG_ERROR,
963 "h264_slice_header_init() failed\n");
971 static int h264_export_frame_props(H264Context *h)
973 const SPS *sps = h->ps.sps;
974 H264Picture *cur = h->cur_pic_ptr;
976 cur->f->interlaced_frame = 0;
977 cur->f->repeat_pict = 0;
979 /* Signal interlacing information externally. */
980 /* Prioritize picture timing SEI information over used
981 * decoding process if it exists. */
983 if (sps->pic_struct_present_flag) {
984 H264SEIPictureTiming *pt = &h->sei.picture_timing;
985 switch (pt->pic_struct) {
986 case SEI_PIC_STRUCT_FRAME:
988 case SEI_PIC_STRUCT_TOP_FIELD:
989 case SEI_PIC_STRUCT_BOTTOM_FIELD:
990 cur->f->interlaced_frame = 1;
992 case SEI_PIC_STRUCT_TOP_BOTTOM:
993 case SEI_PIC_STRUCT_BOTTOM_TOP:
994 if (FIELD_OR_MBAFF_PICTURE(h))
995 cur->f->interlaced_frame = 1;
997 // try to flag soft telecine progressive
998 cur->f->interlaced_frame = h->prev_interlaced_frame;
1000 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1001 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1002 /* Signal the possibility of telecined film externally
1003 * (pic_struct 5,6). From these hints, let the applications
1004 * decide if they apply deinterlacing. */
1005 cur->f->repeat_pict = 1;
1007 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1008 cur->f->repeat_pict = 2;
1010 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1011 cur->f->repeat_pict = 4;
1015 if ((pt->ct_type & 3) &&
1016 pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1017 cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
1019 /* Derive interlacing flag from used decoding process. */
1020 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
1022 h->prev_interlaced_frame = cur->f->interlaced_frame;
1024 if (cur->field_poc[0] != cur->field_poc[1]) {
1025 /* Derive top_field_first from field pocs. */
1026 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1028 if (cur->f->interlaced_frame || sps->pic_struct_present_flag) {
1029 /* Use picture timing SEI information. Even if it is a
1030 * information of a past frame, better than nothing. */
1031 if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1032 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1033 cur->f->top_field_first = 1;
1035 cur->f->top_field_first = 0;
1037 /* Most likely progressive */
1038 cur->f->top_field_first = 0;
1042 if (h->sei.frame_packing.present &&
1043 h->sei.frame_packing.arrangement_type >= 0 &&
1044 h->sei.frame_packing.arrangement_type <= 6 &&
1045 h->sei.frame_packing.content_interpretation_type > 0 &&
1046 h->sei.frame_packing.content_interpretation_type < 3) {
1047 H264SEIFramePacking *fp = &h->sei.frame_packing;
1048 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
1050 return AVERROR(ENOMEM);
1052 switch (fp->arrangement_type) {
1054 stereo->type = AV_STEREO3D_CHECKERBOARD;
1057 stereo->type = AV_STEREO3D_COLUMNS;
1060 stereo->type = AV_STEREO3D_LINES;
1063 if (fp->quincunx_subsampling)
1064 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
1066 stereo->type = AV_STEREO3D_SIDEBYSIDE;
1069 stereo->type = AV_STEREO3D_TOPBOTTOM;
1072 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
1075 stereo->type = AV_STEREO3D_2D;
1079 if (fp->content_interpretation_type == 2)
1080 stereo->flags = AV_STEREO3D_FLAG_INVERT;
1083 if (h->sei.display_orientation.present &&
1084 (h->sei.display_orientation.anticlockwise_rotation ||
1085 h->sei.display_orientation.hflip ||
1086 h->sei.display_orientation.vflip)) {
1087 H264SEIDisplayOrientation *o = &h->sei.display_orientation;
1088 double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
1089 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
1090 AV_FRAME_DATA_DISPLAYMATRIX,
1091 sizeof(int32_t) * 9);
1093 return AVERROR(ENOMEM);
1095 av_display_rotation_set((int32_t *)rotation->data, angle);
1096 av_display_matrix_flip((int32_t *)rotation->data,
1097 o->hflip, o->vflip);
1100 if (h->sei.afd.present) {
1101 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
1104 return AVERROR(ENOMEM);
1106 *sd->data = h->sei.afd.active_format_description;
1107 h->sei.afd.present = 0;
1110 if (h->sei.a53_caption.a53_caption) {
1111 H264SEIA53Caption *a53 = &h->sei.a53_caption;
1112 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
1113 AV_FRAME_DATA_A53_CC,
1114 a53->a53_caption_size);
1116 return AVERROR(ENOMEM);
1118 memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
1119 av_freep(&a53->a53_caption);
1120 a53->a53_caption_size = 0;
1126 static int h264_select_output_frame(H264Context *h)
1128 const SPS *sps = h->ps.sps;
1129 H264Picture *out = h->cur_pic_ptr;
1130 H264Picture *cur = h->cur_pic_ptr;
1131 int i, pics, out_of_order, out_idx;
1132 int invalid = 0, cnt = 0;
1135 if (sps->bitstream_restriction_flag ||
1136 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
1137 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
1141 while (h->delayed_pic[pics])
1144 assert(pics <= MAX_DELAYED_PIC_COUNT);
1146 h->delayed_pic[pics++] = cur;
1147 if (cur->reference == 0)
1148 cur->reference = DELAYED_PIC_REF;
1150 /* Frame reordering. This code takes pictures from coding order and sorts
1151 * them by their incremental POC value into display order. It supports POC
1152 * gaps, MMCO reset codes and random resets.
1153 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1154 * and/or can be closed down with a MMCO reset code. In sequences where
1155 * there is no delay, we can't detect that (since the frame was already
1156 * output to the user), so we also set h->mmco_reset to detect the MMCO
1158 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
1159 * we increase the delay between input and output. All frames affected by
1160 * the lag (e.g. those that should have been output before another frame
1161 * that we already returned to the user) will be dropped. This is a bug
1162 * that we will fix later. */
1163 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1164 cnt += out->poc < h->last_pocs[i];
1165 invalid += out->poc == INT_MIN;
1167 if (!h->mmco_reset && !cur->f->key_frame &&
1168 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1171 h->delayed_pic[pics - 2]->mmco_reset = 2;
1173 if (h->mmco_reset || cur->f->key_frame) {
1174 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1175 h->last_pocs[i] = INT_MIN;
1177 invalid = MAX_DELAYED_PIC_COUNT;
1179 out = h->delayed_pic[0];
1181 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1182 h->delayed_pic[i] &&
1183 !h->delayed_pic[i - 1]->mmco_reset &&
1184 !h->delayed_pic[i]->f->key_frame;
1186 if (h->delayed_pic[i]->poc < out->poc) {
1187 out = h->delayed_pic[i];
1190 if (h->avctx->has_b_frames == 0 &&
1191 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
1192 h->next_outputed_poc = INT_MIN;
1193 out_of_order = !out->f->key_frame && !h->mmco_reset &&
1194 (out->poc < h->next_outputed_poc);
1196 if (sps->bitstream_restriction_flag &&
1197 h->avctx->has_b_frames >= sps->num_reorder_frames) {
1198 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1199 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1200 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1201 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
1203 } else if (!h->avctx->has_b_frames &&
1204 ((h->next_outputed_poc != INT_MIN &&
1205 out->poc > h->next_outputed_poc + 2) ||
1206 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
1207 h->avctx->has_b_frames++;
1210 if (pics > h->avctx->has_b_frames) {
1211 out->reference &= ~DELAYED_PIC_REF;
1212 for (i = out_idx; h->delayed_pic[i]; i++)
1213 h->delayed_pic[i] = h->delayed_pic[i + 1];
1215 memmove(h->last_pocs, &h->last_pocs[1],
1216 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1217 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1218 if (!out_of_order && pics > h->avctx->has_b_frames) {
1219 av_frame_unref(h->output_frame);
1220 ret = av_frame_ref(h->output_frame, out->f);
1224 if (out->recovered) {
1225 // We have reached an recovery point and all frames after it in
1226 // display order are "recovered".
1227 h->frame_recovered |= FRAME_RECOVERED_SEI;
1229 out->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
1231 if (!out->recovered) {
1232 if (!(h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT))
1233 av_frame_unref(h->output_frame);
1235 h->output_frame->flags |= AV_FRAME_FLAG_CORRUPT;
1238 if (out->mmco_reset) {
1240 h->next_outputed_poc = out->poc;
1241 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1243 h->next_outputed_poc = INT_MIN;
1246 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
1247 h->next_outputed_poc = INT_MIN;
1249 h->next_outputed_poc = out->poc;
1254 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
1260 /* This function is called right after decoding the slice header for a first
1261 * slice in a field (or a frame). It decides whether we are decoding a new frame
1262 * or a second field in a pair and does the necessary setup.
1264 static int h264_field_start(H264Context *h, const H264SliceContext *sl,
1265 const H2645NAL *nal)
1269 int last_pic_structure, last_pic_droppable, ret;
1271 ret = h264_init_ps(h, sl);
1277 last_pic_droppable = h->droppable;
1278 last_pic_structure = h->picture_structure;
1279 h->droppable = (nal->ref_idc == 0);
1280 h->picture_structure = sl->picture_structure;
1282 h->poc.frame_num = sl->frame_num;
1283 h->poc.poc_lsb = sl->poc_lsb;
1284 h->poc.delta_poc_bottom = sl->delta_poc_bottom;
1285 h->poc.delta_poc[0] = sl->delta_poc[0];
1286 h->poc.delta_poc[1] = sl->delta_poc[1];
1288 /* Shorten frame num gaps so we don't have to allocate reference
1289 * frames just to throw them away */
1290 if (h->poc.frame_num != h->poc.prev_frame_num) {
1291 int unwrap_prev_frame_num = h->poc.prev_frame_num;
1292 int max_frame_num = 1 << sps->log2_max_frame_num;
1294 if (unwrap_prev_frame_num > h->poc.frame_num)
1295 unwrap_prev_frame_num -= max_frame_num;
1297 if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
1298 unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
1299 if (unwrap_prev_frame_num < 0)
1300 unwrap_prev_frame_num += max_frame_num;
1302 h->poc.prev_frame_num = unwrap_prev_frame_num;
1306 /* See if we have a decoded first field looking for a pair...
1307 * Here, we're using that to see if we should mark previously
1308 * decode frames as "finished".
1309 * We have to do that before the "dummy" in-between frame allocation,
1310 * since that can modify s->current_picture_ptr. */
1311 if (h->first_field) {
1312 assert(h->cur_pic_ptr);
1313 assert(h->cur_pic_ptr->f->buf[0]);
1314 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1316 /* figure out if we have a complementary field pair */
1317 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1318 /* Previous field is unmatched. Don't display it, but let it
1319 * remain for reference if marked as such. */
1320 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1321 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1322 last_pic_structure == PICT_TOP_FIELD);
1325 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1326 /* This and previous field were reference, but had
1327 * different frame_nums. Consider this field first in
1328 * pair. Throw away previous field except for reference
1330 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1331 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1332 last_pic_structure == PICT_TOP_FIELD);
1335 /* Second field in complementary pair */
1336 if (!((last_pic_structure == PICT_TOP_FIELD &&
1337 h->picture_structure == PICT_BOTTOM_FIELD) ||
1338 (last_pic_structure == PICT_BOTTOM_FIELD &&
1339 h->picture_structure == PICT_TOP_FIELD))) {
1340 av_log(h->avctx, AV_LOG_ERROR,
1341 "Invalid field mode combination %d/%d\n",
1342 last_pic_structure, h->picture_structure);
1343 h->picture_structure = last_pic_structure;
1344 h->droppable = last_pic_droppable;
1345 return AVERROR_INVALIDDATA;
1346 } else if (last_pic_droppable != h->droppable) {
1347 avpriv_request_sample(h->avctx,
1348 "Found reference and non-reference fields in the same frame, which");
1349 h->picture_structure = last_pic_structure;
1350 h->droppable = last_pic_droppable;
1351 return AVERROR_PATCHWELCOME;
1357 while (h->poc.frame_num != h->poc.prev_frame_num &&
1358 h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
1359 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1360 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1361 h->poc.frame_num, h->poc.prev_frame_num);
1362 ret = initialize_cur_frame(h);
1368 h->poc.prev_frame_num++;
1369 h->poc.prev_frame_num %= 1 << sps->log2_max_frame_num;
1370 h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
1371 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1372 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1374 h->explicit_ref_marking = 0;
1375 ret = ff_h264_execute_ref_pic_marking(h);
1376 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1378 /* Error concealment: If a ref is missing, copy the previous ref
1380 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1381 * many assumptions about there being no actual duplicates.
1382 * FIXME: This does not copy padding for out-of-frame motion
1383 * vectors. Given we are concealing a lost frame, this probably
1384 * is not noticeable by comparison, but it should be fixed. */
1385 if (h->short_ref_count) {
1387 h->short_ref[0]->f->width == prev->f->width &&
1388 h->short_ref[0]->f->height == prev->f->height &&
1389 h->short_ref[0]->f->format == prev->f->format) {
1390 ff_thread_await_progress(&prev->tf, INT_MAX, 0);
1391 if (prev->field_picture)
1392 ff_thread_await_progress(&prev->tf, INT_MAX, 1);
1393 av_image_copy(h->short_ref[0]->f->data,
1394 h->short_ref[0]->f->linesize,
1395 (const uint8_t **)prev->f->data,
1400 h->short_ref[0]->poc = prev->poc + 2;
1402 h->short_ref[0]->frame_num = h->poc.prev_frame_num;
1406 /* See if we have a decoded first field looking for a pair...
1407 * We're using that to see whether to continue decoding in that
1408 * frame, or to allocate a new one. */
1409 if (h->first_field) {
1410 assert(h->cur_pic_ptr);
1411 assert(h->cur_pic_ptr->f->buf[0]);
1412 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1414 /* figure out if we have a complementary field pair */
1415 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1416 /* Previous field is unmatched. Don't display it, but let it
1417 * remain for reference if marked as such. */
1418 h->cur_pic_ptr = NULL;
1419 h->first_field = FIELD_PICTURE(h);
1421 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1422 /* This and the previous field had different frame_nums.
1423 * Consider this field first in pair. Throw away previous
1424 * one except for reference purposes. */
1426 h->cur_pic_ptr = NULL;
1428 /* Second field in complementary pair */
1433 /* Frame or first field in a potentially complementary pair */
1434 h->first_field = FIELD_PICTURE(h);
1437 if (!FIELD_PICTURE(h) || h->first_field) {
1438 if (h264_frame_start(h) < 0) {
1440 return AVERROR_INVALIDDATA;
1443 release_unused_pictures(h, 0);
1446 ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
1447 h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
1449 memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
1450 h->nb_mmco = sl->nb_mmco;
1451 h->explicit_ref_marking = sl->explicit_ref_marking;
1453 h->picture_idr = nal->type == H264_NAL_IDR_SLICE;
1455 if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1456 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
1457 ((1 << h->ps.sps->log2_max_frame_num) - 1);
1460 h->cur_pic_ptr->f->key_frame |= (nal->type == H264_NAL_IDR_SLICE) ||
1461 (h->sei.recovery_point.recovery_frame_cnt >= 0);
1463 if (nal->type == H264_NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
1464 h->recovery_frame = -1;
1465 h->cur_pic_ptr->recovered = 1;
1467 // If we have an IDR, all frames after it in decoded order are
1469 if (nal->type == H264_NAL_IDR_SLICE)
1470 h->frame_recovered |= FRAME_RECOVERED_IDR;
1471 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1473 /* Set the frame properties/side data. Only done for the second field in
1474 * field coded frames, since some SEI information is present for each field
1475 * and is merged by the SEI parsing code. */
1476 if (!FIELD_PICTURE(h) || !h->first_field) {
1477 ret = h264_export_frame_props(h);
1481 ret = h264_select_output_frame(h);
1486 if (h->avctx->hwaccel) {
1487 ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0);
1495 static int h264_slice_header_parse(H264SliceContext *sl, const H2645NAL *nal,
1496 const H264ParamSets *ps, AVCodecContext *avctx)
1501 unsigned int slice_type, tmp, i;
1502 int field_pic_flag, bottom_field_flag, picture_structure;
1504 sl->first_mb_addr = get_ue_golomb(&sl->gb);
1506 slice_type = get_ue_golomb_31(&sl->gb);
1507 if (slice_type > 9) {
1508 av_log(avctx, AV_LOG_ERROR,
1509 "slice type %d too large at %d\n",
1510 slice_type, sl->first_mb_addr);
1511 return AVERROR_INVALIDDATA;
1513 if (slice_type > 4) {
1515 sl->slice_type_fixed = 1;
1517 sl->slice_type_fixed = 0;
1519 slice_type = ff_h264_golomb_to_pict_type[slice_type];
1520 sl->slice_type = slice_type;
1521 sl->slice_type_nos = slice_type & 3;
1523 if (nal->type == H264_NAL_IDR_SLICE &&
1524 sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1525 av_log(avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
1526 return AVERROR_INVALIDDATA;
1529 sl->pps_id = get_ue_golomb(&sl->gb);
1530 if (sl->pps_id >= MAX_PPS_COUNT) {
1531 av_log(avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
1532 return AVERROR_INVALIDDATA;
1534 if (!ps->pps_list[sl->pps_id]) {
1535 av_log(avctx, AV_LOG_ERROR,
1536 "non-existing PPS %u referenced\n",
1538 return AVERROR_INVALIDDATA;
1540 pps = (const PPS*)ps->pps_list[sl->pps_id]->data;
1542 if (!ps->sps_list[pps->sps_id]) {
1543 av_log(avctx, AV_LOG_ERROR,
1544 "non-existing SPS %u referenced\n", pps->sps_id);
1545 return AVERROR_INVALIDDATA;
1547 sps = (const SPS*)ps->sps_list[pps->sps_id]->data;
1549 sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
1553 if (sps->frame_mbs_only_flag) {
1554 picture_structure = PICT_FRAME;
1556 field_pic_flag = get_bits1(&sl->gb);
1557 if (field_pic_flag) {
1558 bottom_field_flag = get_bits1(&sl->gb);
1559 picture_structure = PICT_TOP_FIELD + bottom_field_flag;
1561 picture_structure = PICT_FRAME;
1564 sl->picture_structure = picture_structure;
1565 sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
1567 if (picture_structure == PICT_FRAME) {
1568 sl->curr_pic_num = sl->frame_num;
1569 sl->max_pic_num = 1 << sps->log2_max_frame_num;
1571 sl->curr_pic_num = 2 * sl->frame_num + 1;
1572 sl->max_pic_num = 1 << (sps->log2_max_frame_num + 1);
1575 if (nal->type == H264_NAL_IDR_SLICE)
1576 get_ue_golomb(&sl->gb); /* idr_pic_id */
1578 if (sps->poc_type == 0) {
1579 sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
1581 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1582 sl->delta_poc_bottom = get_se_golomb(&sl->gb);
1585 if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
1586 sl->delta_poc[0] = get_se_golomb(&sl->gb);
1588 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1589 sl->delta_poc[1] = get_se_golomb(&sl->gb);
1592 sl->redundant_pic_count = 0;
1593 if (pps->redundant_pic_cnt_present)
1594 sl->redundant_pic_count = get_ue_golomb(&sl->gb);
1596 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1597 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1599 ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
1600 &sl->gb, pps, sl->slice_type_nos,
1605 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1606 ret = ff_h264_decode_ref_pic_list_reordering(sl, avctx);
1608 sl->ref_count[1] = sl->ref_count[0] = 0;
1613 sl->pwt.use_weight = 0;
1614 for (i = 0; i < 2; i++) {
1615 sl->pwt.luma_weight_flag[i] = 0;
1616 sl->pwt.chroma_weight_flag[i] = 0;
1618 if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
1619 (pps->weighted_bipred_idc == 1 &&
1620 sl->slice_type_nos == AV_PICTURE_TYPE_B))
1621 ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
1622 sl->slice_type_nos, &sl->pwt);
1624 sl->explicit_ref_marking = 0;
1626 ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, avctx);
1627 if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
1628 return AVERROR_INVALIDDATA;
1631 if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1632 tmp = get_ue_golomb_31(&sl->gb);
1634 av_log(avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1635 return AVERROR_INVALIDDATA;
1637 sl->cabac_init_idc = tmp;
1640 sl->last_qscale_diff = 0;
1641 tmp = pps->init_qp + get_se_golomb(&sl->gb);
1642 if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
1643 av_log(avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1644 return AVERROR_INVALIDDATA;
1647 sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
1648 sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
1649 // FIXME qscale / qp ... stuff
1650 if (sl->slice_type == AV_PICTURE_TYPE_SP)
1651 get_bits1(&sl->gb); /* sp_for_switch_flag */
1652 if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1653 sl->slice_type == AV_PICTURE_TYPE_SI)
1654 get_se_golomb(&sl->gb); /* slice_qs_delta */
1656 sl->deblocking_filter = 1;
1657 sl->slice_alpha_c0_offset = 0;
1658 sl->slice_beta_offset = 0;
1659 if (pps->deblocking_filter_parameters_present) {
1660 tmp = get_ue_golomb_31(&sl->gb);
1662 av_log(avctx, AV_LOG_ERROR,
1663 "deblocking_filter_idc %u out of range\n", tmp);
1664 return AVERROR_INVALIDDATA;
1666 sl->deblocking_filter = tmp;
1667 if (sl->deblocking_filter < 2)
1668 sl->deblocking_filter ^= 1; // 1<->0
1670 if (sl->deblocking_filter) {
1671 sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
1672 sl->slice_beta_offset = get_se_golomb(&sl->gb) * 2;
1673 if (sl->slice_alpha_c0_offset > 12 ||
1674 sl->slice_alpha_c0_offset < -12 ||
1675 sl->slice_beta_offset > 12 ||
1676 sl->slice_beta_offset < -12) {
1677 av_log(avctx, AV_LOG_ERROR,
1678 "deblocking filter parameters %d %d out of range\n",
1679 sl->slice_alpha_c0_offset, sl->slice_beta_offset);
1680 return AVERROR_INVALIDDATA;
1688 /* do all the per-slice initialization needed before we can start decoding the
1690 static int h264_slice_init(H264Context *h, H264SliceContext *sl,
1691 const H2645NAL *nal)
1695 if (h->current_slice > 0) {
1696 if (h->ps.pps != (const PPS*)h->ps.pps_list[sl->pps_id]->data) {
1697 av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
1698 return AVERROR_INVALIDDATA;
1701 if (h->picture_structure != sl->picture_structure ||
1702 h->droppable != (nal->ref_idc == 0)) {
1703 av_log(h->avctx, AV_LOG_ERROR,
1704 "Changing field mode (%d -> %d) between slices is not allowed\n",
1705 h->picture_structure, sl->picture_structure);
1706 return AVERROR_INVALIDDATA;
1707 } else if (!h->cur_pic_ptr) {
1708 av_log(h->avctx, AV_LOG_ERROR,
1709 "unset cur_pic_ptr on slice %d\n",
1710 h->current_slice + 1);
1711 return AVERROR_INVALIDDATA;
1715 if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {
1716 av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");
1717 return AVERROR_INVALIDDATA;
1720 assert(h->mb_num == h->mb_width * h->mb_height);
1721 if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1722 sl->first_mb_addr >= h->mb_num) {
1723 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1724 return AVERROR_INVALIDDATA;
1726 sl->resync_mb_x = sl->mb_x = sl->first_mb_addr % h->mb_width;
1727 sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
1728 FIELD_OR_MBAFF_PICTURE(h);
1729 if (h->picture_structure == PICT_BOTTOM_FIELD)
1730 sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
1731 assert(sl->mb_y < h->mb_height);
1733 ret = ff_h264_build_ref_list(h, sl);
1737 if (h->ps.pps->weighted_bipred_idc == 2 &&
1738 sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1739 implicit_weight_table(h, sl, -1);
1740 if (FRAME_MBAFF(h)) {
1741 implicit_weight_table(h, sl, 0);
1742 implicit_weight_table(h, sl, 1);
1746 if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
1747 ff_h264_direct_dist_scale_factor(h, sl);
1748 ff_h264_direct_ref_list_init(h, sl);
1750 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1751 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
1752 sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
1753 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
1754 sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
1755 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1757 sl->deblocking_filter = 0;
1759 if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
1760 if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
1761 /* Cheat slightly for speed:
1762 * Do not bother to deblock across slices. */
1763 sl->deblocking_filter = 2;
1765 h->postpone_filter = 1;
1768 sl->qp_thresh = 15 -
1769 FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
1771 h->ps.pps->chroma_qp_index_offset[0],
1772 h->ps.pps->chroma_qp_index_offset[1]) +
1773 6 * (h->ps.sps->bit_depth_luma - 8);
1775 sl->slice_num = ++h->current_slice;
1776 if (sl->slice_num >= MAX_SLICES) {
1777 av_log(h->avctx, AV_LOG_ERROR,
1778 "Too many slices, increase MAX_SLICES and recompile\n");
1781 for (j = 0; j < 2; j++) {
1783 int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
1784 for (i = 0; i < 16; i++) {
1786 if (j < sl->list_count && i < sl->ref_count[j] &&
1787 sl->ref_list[j][i].parent->f->buf[0]) {
1789 AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
1790 for (k = 0; k < h->short_ref_count; k++)
1791 if (h->short_ref[k]->f->buf[0]->buffer == buf) {
1795 for (k = 0; k < h->long_ref_count; k++)
1796 if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
1797 id_list[i] = h->short_ref_count + k;
1805 for (i = 0; i < 16; i++)
1806 ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
1808 ref2frm[18 + 1] = -1;
1809 for (i = 16; i < 48; i++)
1810 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
1811 (sl->ref_list[j][i].reference & 3);
1814 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
1815 av_log(h->avctx, AV_LOG_DEBUG,
1816 "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",
1818 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
1819 sl->mb_y * h->mb_width + sl->mb_x,
1820 av_get_picture_type_char(sl->slice_type),
1821 sl->slice_type_fixed ? " fix" : "",
1822 nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",
1824 h->cur_pic_ptr->field_poc[0],
1825 h->cur_pic_ptr->field_poc[1],
1826 sl->ref_count[0], sl->ref_count[1],
1828 sl->deblocking_filter,
1829 sl->slice_alpha_c0_offset, sl->slice_beta_offset,
1831 sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
1832 sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
1838 int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)
1840 H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
1845 ret = h264_slice_header_parse(sl, nal, &h->ps, h->avctx);
1849 // discard redundant pictures
1850 if (sl->redundant_pic_count > 0)
1853 if (!h->setup_finished) {
1854 if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
1855 // this slice starts a new field
1856 // first decode any pending queued slices
1857 if (h->nb_slice_ctx_queued) {
1858 H264SliceContext tmp_ctx;
1860 ret = ff_h264_execute_decode_slices(h);
1861 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1864 memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));
1865 memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));
1866 memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));
1870 if (h->field_started)
1871 ff_h264_field_end(h, sl, 1);
1873 h->current_slice = 0;
1874 if (!h->first_field) {
1875 if (h->cur_pic_ptr && !h->droppable) {
1876 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1877 h->picture_structure == PICT_BOTTOM_FIELD);
1879 h->cur_pic_ptr = NULL;
1883 if (h->current_slice == 0) {
1884 ret = h264_field_start(h, sl, nal);
1887 h->field_started = 1;
1891 ret = h264_slice_init(h, sl, nal);
1895 if ((h->avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1896 (h->avctx->skip_frame < AVDISCARD_BIDIR ||
1897 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1898 (h->avctx->skip_frame < AVDISCARD_NONKEY ||
1899 h->cur_pic_ptr->f->key_frame) &&
1900 h->avctx->skip_frame < AVDISCARD_ALL) {
1901 h->nb_slice_ctx_queued++;
1907 int ff_h264_get_slice_type(const H264SliceContext *sl)
1909 switch (sl->slice_type) {
1910 case AV_PICTURE_TYPE_P:
1912 case AV_PICTURE_TYPE_B:
1914 case AV_PICTURE_TYPE_I:
1916 case AV_PICTURE_TYPE_SP:
1918 case AV_PICTURE_TYPE_SI:
1921 return AVERROR_INVALIDDATA;
1925 static av_always_inline void fill_filter_caches_inter(const H264Context *h,
1926 H264SliceContext *sl,
1927 int mb_type, int top_xy,
1928 int left_xy[LEFT_MBS],
1930 int left_type[LEFT_MBS],
1931 int mb_xy, int list)
1933 int b_stride = h->b_stride;
1934 int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
1935 int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
1936 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
1937 if (USES_LIST(top_type, list)) {
1938 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
1939 const int b8_xy = 4 * top_xy + 2;
1940 const int *ref2frm = &h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1941 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
1942 ref_cache[0 - 1 * 8] =
1943 ref_cache[1 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 0]];
1944 ref_cache[2 - 1 * 8] =
1945 ref_cache[3 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 1]];
1947 AV_ZERO128(mv_dst - 1 * 8);
1948 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1951 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
1952 if (USES_LIST(left_type[LTOP], list)) {
1953 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
1954 const int b8_xy = 4 * left_xy[LTOP] + 1;
1955 const int *ref2frm = &h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1956 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
1957 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
1958 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
1959 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
1961 ref_cache[-1 + 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
1962 ref_cache[-1 + 16] =
1963 ref_cache[-1 + 24] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
1965 AV_ZERO32(mv_dst - 1 + 0);
1966 AV_ZERO32(mv_dst - 1 + 8);
1967 AV_ZERO32(mv_dst - 1 + 16);
1968 AV_ZERO32(mv_dst - 1 + 24);
1971 ref_cache[-1 + 16] =
1972 ref_cache[-1 + 24] = LIST_NOT_USED;
1977 if (!USES_LIST(mb_type, list)) {
1978 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
1979 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1980 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1981 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1982 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1987 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
1988 const int *ref2frm = &h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1989 uint32_t ref01 = (pack16to32(ref2frm[ref[0]], ref2frm[ref[1]]) & 0x00FF00FF) * 0x0101;
1990 uint32_t ref23 = (pack16to32(ref2frm[ref[2]], ref2frm[ref[3]]) & 0x00FF00FF) * 0x0101;
1991 AV_WN32A(&ref_cache[0 * 8], ref01);
1992 AV_WN32A(&ref_cache[1 * 8], ref01);
1993 AV_WN32A(&ref_cache[2 * 8], ref23);
1994 AV_WN32A(&ref_cache[3 * 8], ref23);
1998 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
1999 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
2000 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
2001 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
2002 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
2007 * @return non zero if the loop filter can be skipped
2009 static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
2011 const int mb_xy = sl->mb_xy;
2012 int top_xy, left_xy[LEFT_MBS];
2013 int top_type, left_type[LEFT_MBS];
2017 top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
2019 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
2020 if (FRAME_MBAFF(h)) {
2021 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
2022 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
2024 if (left_mb_field_flag != curr_mb_field_flag)
2025 left_xy[LTOP] -= h->mb_stride;
2027 if (curr_mb_field_flag)
2028 top_xy += h->mb_stride &
2029 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
2030 if (left_mb_field_flag != curr_mb_field_flag)
2031 left_xy[LBOT] += h->mb_stride;
2035 sl->top_mb_xy = top_xy;
2036 sl->left_mb_xy[LTOP] = left_xy[LTOP];
2037 sl->left_mb_xy[LBOT] = left_xy[LBOT];
2039 /* For sufficiently low qp, filtering wouldn't do anything.
2040 * This is a conservative estimate: could also check beta_offset
2041 * and more accurate chroma_qp. */
2042 int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
2043 int qp = h->cur_pic.qscale_table[mb_xy];
2044 if (qp <= qp_thresh &&
2045 (left_xy[LTOP] < 0 ||
2046 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
2048 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
2049 if (!FRAME_MBAFF(h))
2051 if ((left_xy[LTOP] < 0 ||
2052 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
2053 (top_xy < h->mb_stride ||
2054 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
2059 top_type = h->cur_pic.mb_type[top_xy];
2060 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
2061 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
2062 if (sl->deblocking_filter == 2) {
2063 if (h->slice_table[top_xy] != sl->slice_num)
2065 if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
2066 left_type[LTOP] = left_type[LBOT] = 0;
2068 if (h->slice_table[top_xy] == 0xFFFF)
2070 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
2071 left_type[LTOP] = left_type[LBOT] = 0;
2073 sl->top_type = top_type;
2074 sl->left_type[LTOP] = left_type[LTOP];
2075 sl->left_type[LBOT] = left_type[LBOT];
2077 if (IS_INTRA(mb_type))
2080 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2081 top_type, left_type, mb_xy, 0);
2082 if (sl->list_count == 2)
2083 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2084 top_type, left_type, mb_xy, 1);
2086 nnz = h->non_zero_count[mb_xy];
2087 nnz_cache = sl->non_zero_count_cache;
2088 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
2089 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
2090 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
2091 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
2092 sl->cbp = h->cbp_table[mb_xy];
2095 nnz = h->non_zero_count[top_xy];
2096 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
2099 if (left_type[LTOP]) {
2100 nnz = h->non_zero_count[left_xy[LTOP]];
2101 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
2102 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
2103 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
2104 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
2107 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
2108 * from what the loop filter needs */
2109 if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
2110 if (IS_8x8DCT(top_type)) {
2111 nnz_cache[4 + 8 * 0] =
2112 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
2113 nnz_cache[6 + 8 * 0] =
2114 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
2116 if (IS_8x8DCT(left_type[LTOP])) {
2117 nnz_cache[3 + 8 * 1] =
2118 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
2120 if (IS_8x8DCT(left_type[LBOT])) {
2121 nnz_cache[3 + 8 * 3] =
2122 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
2125 if (IS_8x8DCT(mb_type)) {
2126 nnz_cache[scan8[0]] =
2127 nnz_cache[scan8[1]] =
2128 nnz_cache[scan8[2]] =
2129 nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
2131 nnz_cache[scan8[0 + 4]] =
2132 nnz_cache[scan8[1 + 4]] =
2133 nnz_cache[scan8[2 + 4]] =
2134 nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
2136 nnz_cache[scan8[0 + 8]] =
2137 nnz_cache[scan8[1 + 8]] =
2138 nnz_cache[scan8[2 + 8]] =
2139 nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
2141 nnz_cache[scan8[0 + 12]] =
2142 nnz_cache[scan8[1 + 12]] =
2143 nnz_cache[scan8[2 + 12]] =
2144 nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
2151 static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
2153 uint8_t *dest_y, *dest_cb, *dest_cr;
2154 int linesize, uvlinesize, mb_x, mb_y;
2155 const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
2156 const int old_slice_type = sl->slice_type;
2157 const int pixel_shift = h->pixel_shift;
2158 const int block_h = 16 >> h->chroma_y_shift;
2160 if (h->postpone_filter)
2163 if (sl->deblocking_filter) {
2164 for (mb_x = start_x; mb_x < end_x; mb_x++)
2165 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
2167 mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
2168 mb_type = h->cur_pic.mb_type[mb_xy];
2172 sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2176 dest_y = h->cur_pic.f->data[0] +
2177 ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
2178 dest_cb = h->cur_pic.f->data[1] +
2179 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2180 mb_y * sl->uvlinesize * block_h;
2181 dest_cr = h->cur_pic.f->data[2] +
2182 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2183 mb_y * sl->uvlinesize * block_h;
2184 // FIXME simplify above
2187 linesize = sl->mb_linesize = sl->linesize * 2;
2188 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
2189 if (mb_y & 1) { // FIXME move out of this function?
2190 dest_y -= sl->linesize * 15;
2191 dest_cb -= sl->uvlinesize * (block_h - 1);
2192 dest_cr -= sl->uvlinesize * (block_h - 1);
2195 linesize = sl->mb_linesize = sl->linesize;
2196 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
2198 backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
2200 if (fill_filter_caches(h, sl, mb_type))
2202 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
2203 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
2205 if (FRAME_MBAFF(h)) {
2206 ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
2207 linesize, uvlinesize);
2209 ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
2210 dest_cr, linesize, uvlinesize);
2214 sl->slice_type = old_slice_type;
2216 sl->mb_y = end_mb_y - FRAME_MBAFF(h);
2217 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
2218 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
2221 static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
2223 const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
2224 int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
2225 h->cur_pic.mb_type[mb_xy - 1] :
2226 (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
2227 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
2228 sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2232 * Draw edges and report progress for the last MB row.
2234 static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
2236 int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
2237 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
2238 int height = 16 << FRAME_MBAFF(h);
2239 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
2241 if (sl->deblocking_filter) {
2242 if ((top + height) >= pic_height)
2243 height += deblock_border;
2244 top -= deblock_border;
2247 if (top >= pic_height || (top + height) < 0)
2250 height = FFMIN(height, pic_height - top);
2252 height = top + height;
2256 ff_h264_draw_horiz_band(h, sl, top, height);
2261 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
2262 h->picture_structure == PICT_BOTTOM_FIELD);
2265 static void er_add_slice(H264SliceContext *sl,
2266 int startx, int starty,
2267 int endx, int endy, int status)
2269 #if CONFIG_ERROR_RESILIENCE
2270 ERContext *er = &sl->er;
2272 if (!sl->h264->enable_er)
2275 er->ref_count = sl->ref_count[0];
2276 ff_er_add_slice(er, startx, starty, endx, endy, status);
2280 static int decode_slice(struct AVCodecContext *avctx, void *arg)
2282 H264SliceContext *sl = arg;
2283 const H264Context *h = sl->h264;
2284 int lf_x_start = sl->mb_x;
2285 int orig_deblock = sl->deblocking_filter;
2288 sl->linesize = h->cur_pic_ptr->f->linesize[0];
2289 sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
2291 ret = alloc_scratch_buffers(sl, sl->linesize);
2295 sl->mb_skip_run = -1;
2297 if (h->postpone_filter)
2298 sl->deblocking_filter = 0;
2300 sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
2301 (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
2303 if (h->ps.pps->cabac) {
2305 align_get_bits(&sl->gb);
2308 ff_init_cabac_decoder(&sl->cabac,
2309 sl->gb.buffer + get_bits_count(&sl->gb) / 8,
2310 (get_bits_left(&sl->gb) + 7) / 8);
2312 ff_h264_init_cabac_states(h, sl);
2318 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2319 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2320 sl->next_slice_idx);
2321 return AVERROR_INVALIDDATA;
2324 ret = ff_h264_decode_mb_cabac(h, sl);
2325 // STOP_TIMER("decode_mb_cabac")
2328 ff_h264_hl_decode_mb(h, sl);
2330 // FIXME optimal? or let mb_decode decode 16x32 ?
2331 if (ret >= 0 && FRAME_MBAFF(h)) {
2334 ret = ff_h264_decode_mb_cabac(h, sl);
2337 ff_h264_hl_decode_mb(h, sl);
2340 eos = get_cabac_terminate(&sl->cabac);
2342 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
2343 sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2344 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2345 sl->mb_y, ER_MB_END);
2346 if (sl->mb_x >= lf_x_start)
2347 loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
2350 if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2351 av_log(h->avctx, AV_LOG_ERROR,
2352 "error while decoding MB %d %d, bytestream %td\n",
2354 sl->cabac.bytestream_end - sl->cabac.bytestream);
2355 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2356 sl->mb_y, ER_MB_ERROR);
2357 return AVERROR_INVALIDDATA;
2360 if (++sl->mb_x >= h->mb_width) {
2361 loop_filter(h, sl, lf_x_start, sl->mb_x);
2362 sl->mb_x = lf_x_start = 0;
2363 decode_finish_row(h, sl);
2365 if (FIELD_OR_MBAFF_PICTURE(h)) {
2367 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2368 predict_field_decoding_flag(h, sl);
2372 if (eos || sl->mb_y >= h->mb_height) {
2373 ff_tlog(h->avctx, "slice end %d %d\n",
2374 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2375 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2376 sl->mb_y, ER_MB_END);
2377 if (sl->mb_x > lf_x_start)
2378 loop_filter(h, sl, lf_x_start, sl->mb_x);
2386 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2387 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2388 sl->next_slice_idx);
2389 return AVERROR_INVALIDDATA;
2392 ret = ff_h264_decode_mb_cavlc(h, sl);
2395 ff_h264_hl_decode_mb(h, sl);
2397 // FIXME optimal? or let mb_decode decode 16x32 ?
2398 if (ret >= 0 && FRAME_MBAFF(h)) {
2400 ret = ff_h264_decode_mb_cavlc(h, sl);
2403 ff_h264_hl_decode_mb(h, sl);
2408 av_log(h->avctx, AV_LOG_ERROR,
2409 "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
2410 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2411 sl->mb_y, ER_MB_ERROR);
2415 if (++sl->mb_x >= h->mb_width) {
2416 loop_filter(h, sl, lf_x_start, sl->mb_x);
2417 sl->mb_x = lf_x_start = 0;
2418 decode_finish_row(h, sl);
2420 if (FIELD_OR_MBAFF_PICTURE(h)) {
2422 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2423 predict_field_decoding_flag(h, sl);
2425 if (sl->mb_y >= h->mb_height) {
2426 ff_tlog(h->avctx, "slice end %d %d\n",
2427 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2429 if (get_bits_left(&sl->gb) == 0) {
2430 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2431 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2435 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2436 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2438 return AVERROR_INVALIDDATA;
2443 if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
2444 ff_tlog(h->avctx, "slice end %d %d\n",
2445 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2447 if (get_bits_left(&sl->gb) == 0) {
2448 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2449 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2450 if (sl->mb_x > lf_x_start)
2451 loop_filter(h, sl, lf_x_start, sl->mb_x);
2455 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2456 sl->mb_y, ER_MB_ERROR);
2458 return AVERROR_INVALIDDATA;
2465 sl->deblocking_filter = orig_deblock;
2470 * Call decode_slice() for each context.
2472 * @param h h264 master context
2474 int ff_h264_execute_decode_slices(H264Context *h)
2476 AVCodecContext *const avctx = h->avctx;
2477 H264SliceContext *sl;
2478 int context_count = h->nb_slice_ctx_queued;
2482 if (h->avctx->hwaccel || context_count < 1)
2484 if (context_count == 1) {
2486 h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2487 h->postpone_filter = 0;
2489 ret = decode_slice(avctx, &h->slice_ctx[0]);
2490 h->mb_y = h->slice_ctx[0].mb_y;
2494 for (i = 0; i < context_count; i++) {
2495 int next_slice_idx = h->mb_width * h->mb_height;
2498 sl = &h->slice_ctx[i];
2499 sl->er.error_count = 0;
2501 /* make sure none of those slices overlap */
2502 slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2503 for (j = 0; j < context_count; j++) {
2504 H264SliceContext *sl2 = &h->slice_ctx[j];
2505 int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2507 if (i == j || slice_idx2 < slice_idx)
2509 next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2511 sl->next_slice_idx = next_slice_idx;
2514 avctx->execute(avctx, decode_slice, h->slice_ctx,
2515 NULL, context_count, sizeof(h->slice_ctx[0]));
2517 /* pull back stuff from slices to master context */
2518 sl = &h->slice_ctx[context_count - 1];
2520 for (i = 1; i < context_count; i++)
2521 h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
2523 if (h->postpone_filter) {
2524 h->postpone_filter = 0;
2526 for (i = 0; i < context_count; i++) {
2529 sl = &h->slice_ctx[i];
2530 y_end = FFMIN(sl->mb_y + 1, h->mb_height);
2531 x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
2533 for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
2535 loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
2536 j == y_end - 1 ? x_end : h->mb_width);
2543 h->nb_slice_ctx_queued = 0;