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"
37 #include "golomb_legacy.h"
42 #include "h264chroma.h"
43 #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->width_from_caller = h1->width_from_caller;
382 h->height_from_caller = h1->height_from_caller;
383 h->coded_picture_number = h1->coded_picture_number;
384 h->first_field = h1->first_field;
385 h->picture_structure = h1->picture_structure;
386 h->mb_aff_frame = h1->mb_aff_frame;
387 h->droppable = h1->droppable;
389 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
390 ff_h264_unref_picture(h, &h->DPB[i]);
391 if (h1->DPB[i].f->buf[0] &&
392 (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
396 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
397 ff_h264_unref_picture(h, &h->cur_pic);
398 if (h1->cur_pic.f->buf[0]) {
399 ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
404 h->enable_er = h1->enable_er;
405 h->workaround_bugs = h1->workaround_bugs;
406 h->droppable = h1->droppable;
408 // extradata/NAL handling
409 h->is_avc = h1->is_avc;
410 h->nal_length_size = h1->nal_length_size;
412 memcpy(&h->poc, &h1->poc, sizeof(h->poc));
414 memcpy(h->short_ref, h1->short_ref, sizeof(h->short_ref));
415 memcpy(h->long_ref, h1->long_ref, sizeof(h->long_ref));
416 memcpy(h->delayed_pic, h1->delayed_pic, sizeof(h->delayed_pic));
417 memcpy(h->last_pocs, h1->last_pocs, sizeof(h->last_pocs));
419 h->next_outputed_poc = h1->next_outputed_poc;
421 memcpy(h->mmco, h1->mmco, sizeof(h->mmco));
422 h->nb_mmco = h1->nb_mmco;
423 h->mmco_reset = h1->mmco_reset;
424 h->explicit_ref_marking = h1->explicit_ref_marking;
425 h->long_ref_count = h1->long_ref_count;
426 h->short_ref_count = h1->short_ref_count;
428 copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
429 copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
430 copy_picture_range(h->delayed_pic, h1->delayed_pic,
431 MAX_DELAYED_PIC_COUNT + 2, h, h1);
437 err = ff_h264_execute_ref_pic_marking(h);
438 h->poc.prev_poc_msb = h->poc.poc_msb;
439 h->poc.prev_poc_lsb = h->poc.poc_lsb;
441 h->poc.prev_frame_num_offset = h->poc.frame_num_offset;
442 h->poc.prev_frame_num = h->poc.frame_num;
444 h->recovery_frame = h1->recovery_frame;
445 h->frame_recovered = h1->frame_recovered;
450 static int h264_frame_start(H264Context *h)
454 const int pixel_shift = h->pixel_shift;
456 ret = initialize_cur_frame(h);
460 pic = h->cur_pic_ptr;
461 pic->reference = h->droppable ? 0 : h->picture_structure;
462 pic->f->coded_picture_number = h->coded_picture_number++;
463 pic->field_picture = h->picture_structure != PICT_FRAME;
464 pic->frame_num = h->poc.frame_num;
466 * Zero key_frame here; IDR markings per slice in frame or fields are ORed
468 * See decode_nal_units().
470 pic->f->key_frame = 0;
474 pic->f->pict_type = h->slice_ctx[0].slice_type;
476 pic->f->crop_left = h->crop_left;
477 pic->f->crop_right = h->crop_right;
478 pic->f->crop_top = h->crop_top;
479 pic->f->crop_bottom = h->crop_bottom;
481 if (CONFIG_ERROR_RESILIENCE && h->enable_er)
482 ff_er_frame_start(&h->slice_ctx[0].er);
484 for (i = 0; i < 16; i++) {
485 h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
486 h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
488 for (i = 0; i < 16; i++) {
489 h->block_offset[16 + i] =
490 h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
491 h->block_offset[48 + 16 + i] =
492 h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
495 /* Some macroblocks can be accessed before they're available in case
496 * of lost slices, MBAFF or threading. */
497 memset(h->slice_table, -1,
498 (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
500 /* We mark the current picture as non-reference after allocating it, so
501 * that if we break out due to an error it can be released automatically
502 * in the next ff_mpv_frame_start().
504 h->cur_pic_ptr->reference = 0;
506 h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
508 h->postpone_filter = 0;
510 h->mb_aff_frame = h->ps.sps->mb_aff && (h->picture_structure == PICT_FRAME);
512 assert(h->cur_pic_ptr->long_ref == 0);
517 static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
519 uint8_t *src_cb, uint8_t *src_cr,
520 int linesize, int uvlinesize,
525 const int pixel_shift = h->pixel_shift;
526 int chroma444 = CHROMA444(h);
527 int chroma422 = CHROMA422(h);
530 src_cb -= uvlinesize;
531 src_cr -= uvlinesize;
533 if (!simple && FRAME_MBAFF(h)) {
536 top_border = sl->top_borders[0][sl->mb_x];
537 AV_COPY128(top_border, src_y + 15 * linesize);
539 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
540 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
543 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
544 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
545 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
546 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
548 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
549 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
551 } else if (chroma422) {
553 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
554 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
556 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
557 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
561 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
562 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
564 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
565 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
570 } else if (MB_MBAFF(sl)) {
576 top_border = sl->top_borders[top_idx][sl->mb_x];
577 /* There are two lines saved, the line above the top macroblock
578 * of a pair, and the line above the bottom macroblock. */
579 AV_COPY128(top_border, src_y + 16 * linesize);
581 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
583 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
586 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
587 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
588 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
589 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
591 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
592 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
594 } else if (chroma422) {
596 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
597 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
599 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
600 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
604 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
605 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
607 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
608 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
615 * Initialize implicit_weight table.
616 * @param field 0/1 initialize the weight for interlaced MBAFF
617 * -1 initializes the rest
619 static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
621 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
623 for (i = 0; i < 2; i++) {
624 sl->pwt.luma_weight_flag[i] = 0;
625 sl->pwt.chroma_weight_flag[i] = 0;
629 if (h->picture_structure == PICT_FRAME) {
630 cur_poc = h->cur_pic_ptr->poc;
632 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
634 if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
635 sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {
636 sl->pwt.use_weight = 0;
637 sl->pwt.use_weight_chroma = 0;
641 ref_count0 = sl->ref_count[0];
642 ref_count1 = sl->ref_count[1];
644 cur_poc = h->cur_pic_ptr->field_poc[field];
646 ref_count0 = 16 + 2 * sl->ref_count[0];
647 ref_count1 = 16 + 2 * sl->ref_count[1];
650 sl->pwt.use_weight = 2;
651 sl->pwt.use_weight_chroma = 2;
652 sl->pwt.luma_log2_weight_denom = 5;
653 sl->pwt.chroma_log2_weight_denom = 5;
655 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
656 int poc0 = sl->ref_list[0][ref0].poc;
657 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
659 if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
660 int poc1 = sl->ref_list[1][ref1].poc;
661 int td = av_clip_int8(poc1 - poc0);
663 int tb = av_clip_int8(cur_poc - poc0);
664 int tx = (16384 + (FFABS(td) >> 1)) / td;
665 int dist_scale_factor = (tb * tx + 32) >> 8;
666 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
667 w = 64 - dist_scale_factor;
671 sl->pwt.implicit_weight[ref0][ref1][0] =
672 sl->pwt.implicit_weight[ref0][ref1][1] = w;
674 sl->pwt.implicit_weight[ref0][ref1][field] = w;
681 * initialize scan tables
683 static void init_scan_tables(H264Context *h)
686 for (i = 0; i < 16; i++) {
687 #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
688 h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
689 h->field_scan[i] = TRANSPOSE(field_scan[i]);
692 for (i = 0; i < 64; i++) {
693 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
694 h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
695 h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
696 h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
697 h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
700 if (h->ps.sps->transform_bypass) { // FIXME same ugly
701 h->zigzag_scan_q0 = ff_zigzag_scan;
702 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
703 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
704 h->field_scan_q0 = field_scan;
705 h->field_scan8x8_q0 = field_scan8x8;
706 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
708 h->zigzag_scan_q0 = h->zigzag_scan;
709 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
710 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
711 h->field_scan_q0 = h->field_scan;
712 h->field_scan8x8_q0 = h->field_scan8x8;
713 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
717 static enum AVPixelFormat get_pixel_format(H264Context *h)
719 #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
720 CONFIG_H264_D3D11VA_HWACCEL + \
721 CONFIG_H264_VAAPI_HWACCEL + \
722 (CONFIG_H264_VDA_HWACCEL * 2) + \
723 CONFIG_H264_VDPAU_HWACCEL)
724 enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
725 const enum AVPixelFormat *choices = pix_fmts;
727 switch (h->ps.sps->bit_depth_luma) {
730 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
731 *fmt++ = AV_PIX_FMT_GBRP9;
733 *fmt++ = AV_PIX_FMT_YUV444P9;
734 } else if (CHROMA422(h))
735 *fmt++ = AV_PIX_FMT_YUV422P9;
737 *fmt++ = AV_PIX_FMT_YUV420P9;
741 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
742 *fmt++ = AV_PIX_FMT_GBRP10;
744 *fmt++ = AV_PIX_FMT_YUV444P10;
745 } else if (CHROMA422(h))
746 *fmt++ = AV_PIX_FMT_YUV422P10;
748 *fmt++ = AV_PIX_FMT_YUV420P10;
751 #if CONFIG_H264_VDPAU_HWACCEL
752 *fmt++ = AV_PIX_FMT_VDPAU;
755 if (h->avctx->colorspace == AVCOL_SPC_RGB)
756 *fmt++ = AV_PIX_FMT_GBRP;
757 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
758 *fmt++ = AV_PIX_FMT_YUVJ444P;
760 *fmt++ = AV_PIX_FMT_YUV444P;
761 } else if (CHROMA422(h)) {
762 if (h->avctx->color_range == AVCOL_RANGE_JPEG)
763 *fmt++ = AV_PIX_FMT_YUVJ422P;
765 *fmt++ = AV_PIX_FMT_YUV422P;
767 #if CONFIG_H264_DXVA2_HWACCEL
768 *fmt++ = AV_PIX_FMT_DXVA2_VLD;
770 #if CONFIG_H264_D3D11VA_HWACCEL
771 *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
773 #if CONFIG_H264_VAAPI_HWACCEL
774 *fmt++ = AV_PIX_FMT_VAAPI;
776 #if CONFIG_H264_VDA_HWACCEL
777 *fmt++ = AV_PIX_FMT_VDA_VLD;
778 *fmt++ = AV_PIX_FMT_VDA;
780 if (h->avctx->codec->pix_fmts)
781 choices = h->avctx->codec->pix_fmts;
782 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
783 *fmt++ = AV_PIX_FMT_YUVJ420P;
785 *fmt++ = AV_PIX_FMT_YUV420P;
789 av_log(h->avctx, AV_LOG_ERROR,
790 "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);
791 return AVERROR_INVALIDDATA;
794 *fmt = AV_PIX_FMT_NONE;
796 return ff_get_format(h->avctx, choices);
799 /* export coded and cropped frame dimensions to AVCodecContext */
800 static int init_dimensions(H264Context *h)
802 SPS *sps = h->ps.sps;
803 int cr = sps->crop_right;
804 int cl = sps->crop_left;
805 int ct = sps->crop_top;
806 int cb = sps->crop_bottom;
807 int width = h->width - (cr + cl);
808 int height = h->height - (ct + cb);
810 /* handle container cropping */
811 if (h->width_from_caller > 0 && h->height_from_caller > 0 &&
812 !sps->crop_top && !sps->crop_left &&
813 FFALIGN(h->width_from_caller, 16) == FFALIGN(width, 16) &&
814 FFALIGN(h->height_from_caller, 16) == FFALIGN(height, 16)) {
815 width = h->width_from_caller;
816 height = h->height_from_caller;
819 cr = h->width - width;
820 cb = h->height - height;
822 h->width_from_caller = 0;
823 h->height_from_caller = 0;
826 h->avctx->coded_width = h->width;
827 h->avctx->coded_height = h->height;
828 h->avctx->width = width;
829 h->avctx->height = height;
838 static int h264_slice_header_init(H264Context *h)
840 const SPS *sps = h->ps.sps;
843 ff_set_sar(h->avctx, sps->sar);
844 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
845 &h->chroma_x_shift, &h->chroma_y_shift);
847 if (sps->timing_info_present_flag) {
848 int64_t den = sps->time_scale;
849 if (h->sei.unregistered.x264_build < 44U)
851 av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
852 sps->num_units_in_tick, den, 1 << 30);
855 ff_h264_free_tables(h);
858 h->prev_interlaced_frame = 1;
861 ret = ff_h264_alloc_tables(h);
863 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
867 if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 10) {
868 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
869 sps->bit_depth_luma);
870 return AVERROR_INVALIDDATA;
873 h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
874 h->pixel_shift = sps->bit_depth_luma > 8;
875 h->chroma_format_idc = sps->chroma_format_idc;
876 h->bit_depth_luma = sps->bit_depth_luma;
878 ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
879 sps->chroma_format_idc);
880 ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
881 ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
882 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
883 sps->chroma_format_idc);
884 ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
886 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
887 ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
889 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
893 for (i = 0; i < h->nb_slice_ctx; i++) {
894 H264SliceContext *sl = &h->slice_ctx[i];
897 sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
898 sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
899 sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
901 if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
902 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
908 h->context_initialized = 1;
913 static int h264_init_ps(H264Context *h, const H264SliceContext *sl)
916 int needs_reinit = 0, ret;
918 h->ps.pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
919 if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
920 h->ps.sps = (SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data;
922 if (h->bit_depth_luma != h->ps.sps->bit_depth_luma ||
923 h->chroma_format_idc != h->ps.sps->chroma_format_idc)
928 h->avctx->profile = ff_h264_get_profile(sps);
929 h->avctx->level = sps->level_idc;
930 h->avctx->refs = sps->ref_frame_count;
932 if (h->mb_width != sps->mb_width ||
933 h->mb_height != sps->mb_height)
936 h->mb_width = sps->mb_width;
937 h->mb_height = sps->mb_height;
938 h->mb_num = h->mb_width * h->mb_height;
939 h->mb_stride = h->mb_width + 1;
941 h->b_stride = h->mb_width * 4;
943 h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
945 h->width = 16 * h->mb_width;
946 h->height = 16 * h->mb_height;
948 ret = init_dimensions(h);
952 if (sps->video_signal_type_present_flag) {
953 h->avctx->color_range = sps->full_range ? AVCOL_RANGE_JPEG
955 if (sps->colour_description_present_flag) {
956 if (h->avctx->colorspace != sps->colorspace)
958 h->avctx->color_primaries = sps->color_primaries;
959 h->avctx->color_trc = sps->color_trc;
960 h->avctx->colorspace = sps->colorspace;
964 if (!h->context_initialized || needs_reinit) {
965 h->context_initialized = 0;
966 if (sl != h->slice_ctx) {
967 av_log(h->avctx, AV_LOG_ERROR,
968 "changing width %d -> %d / height %d -> %d on "
970 h->width, h->avctx->coded_width,
971 h->height, h->avctx->coded_height,
972 h->current_slice + 1);
973 return AVERROR_INVALIDDATA;
976 ff_h264_flush_change(h);
978 if ((ret = get_pixel_format(h)) < 0)
980 h->avctx->pix_fmt = ret;
982 av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
983 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
985 if ((ret = h264_slice_header_init(h)) < 0) {
986 av_log(h->avctx, AV_LOG_ERROR,
987 "h264_slice_header_init() failed\n");
995 static int h264_export_frame_props(H264Context *h)
997 const SPS *sps = h->ps.sps;
998 H264Picture *cur = h->cur_pic_ptr;
1000 cur->f->interlaced_frame = 0;
1001 cur->f->repeat_pict = 0;
1003 /* Signal interlacing information externally. */
1004 /* Prioritize picture timing SEI information over used
1005 * decoding process if it exists. */
1007 if (sps->pic_struct_present_flag && h->sei.picture_timing.present) {
1008 H264SEIPictureTiming *pt = &h->sei.picture_timing;
1009 switch (pt->pic_struct) {
1010 case SEI_PIC_STRUCT_FRAME:
1012 case SEI_PIC_STRUCT_TOP_FIELD:
1013 case SEI_PIC_STRUCT_BOTTOM_FIELD:
1014 cur->f->interlaced_frame = 1;
1016 case SEI_PIC_STRUCT_TOP_BOTTOM:
1017 case SEI_PIC_STRUCT_BOTTOM_TOP:
1018 if (FIELD_OR_MBAFF_PICTURE(h))
1019 cur->f->interlaced_frame = 1;
1021 // try to flag soft telecine progressive
1022 cur->f->interlaced_frame = h->prev_interlaced_frame;
1024 case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1025 case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1026 /* Signal the possibility of telecined film externally
1027 * (pic_struct 5,6). From these hints, let the applications
1028 * decide if they apply deinterlacing. */
1029 cur->f->repeat_pict = 1;
1031 case SEI_PIC_STRUCT_FRAME_DOUBLING:
1032 cur->f->repeat_pict = 2;
1034 case SEI_PIC_STRUCT_FRAME_TRIPLING:
1035 cur->f->repeat_pict = 4;
1039 if ((pt->ct_type & 3) &&
1040 pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
1041 cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
1043 /* Derive interlacing flag from used decoding process. */
1044 cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
1046 h->prev_interlaced_frame = cur->f->interlaced_frame;
1048 if (cur->field_poc[0] != cur->field_poc[1]) {
1049 /* Derive top_field_first from field pocs. */
1050 cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
1052 if (cur->f->interlaced_frame ||
1053 (sps->pic_struct_present_flag && h->sei.picture_timing.present)) {
1054 /* Use picture timing SEI information. Even if it is a
1055 * information of a past frame, better than nothing. */
1056 if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
1057 h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1058 cur->f->top_field_first = 1;
1060 cur->f->top_field_first = 0;
1062 /* Most likely progressive */
1063 cur->f->top_field_first = 0;
1067 if (h->sei.frame_packing.present &&
1068 h->sei.frame_packing.arrangement_type >= 0 &&
1069 h->sei.frame_packing.arrangement_type <= 6 &&
1070 h->sei.frame_packing.content_interpretation_type > 0 &&
1071 h->sei.frame_packing.content_interpretation_type < 3) {
1072 H264SEIFramePacking *fp = &h->sei.frame_packing;
1073 AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
1075 return AVERROR(ENOMEM);
1077 switch (fp->arrangement_type) {
1079 stereo->type = AV_STEREO3D_CHECKERBOARD;
1082 stereo->type = AV_STEREO3D_COLUMNS;
1085 stereo->type = AV_STEREO3D_LINES;
1088 if (fp->quincunx_subsampling)
1089 stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
1091 stereo->type = AV_STEREO3D_SIDEBYSIDE;
1094 stereo->type = AV_STEREO3D_TOPBOTTOM;
1097 stereo->type = AV_STEREO3D_FRAMESEQUENCE;
1100 stereo->type = AV_STEREO3D_2D;
1104 if (fp->content_interpretation_type == 2)
1105 stereo->flags = AV_STEREO3D_FLAG_INVERT;
1108 if (h->sei.display_orientation.present &&
1109 (h->sei.display_orientation.anticlockwise_rotation ||
1110 h->sei.display_orientation.hflip ||
1111 h->sei.display_orientation.vflip)) {
1112 H264SEIDisplayOrientation *o = &h->sei.display_orientation;
1113 double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
1114 AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
1115 AV_FRAME_DATA_DISPLAYMATRIX,
1116 sizeof(int32_t) * 9);
1118 return AVERROR(ENOMEM);
1120 av_display_rotation_set((int32_t *)rotation->data, angle);
1121 av_display_matrix_flip((int32_t *)rotation->data,
1122 o->hflip, o->vflip);
1125 if (h->sei.afd.present) {
1126 AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
1129 return AVERROR(ENOMEM);
1131 *sd->data = h->sei.afd.active_format_description;
1132 h->sei.afd.present = 0;
1135 if (h->sei.a53_caption.a53_caption) {
1136 H264SEIA53Caption *a53 = &h->sei.a53_caption;
1137 AVFrameSideData *sd = av_frame_new_side_data(cur->f,
1138 AV_FRAME_DATA_A53_CC,
1139 a53->a53_caption_size);
1141 return AVERROR(ENOMEM);
1143 memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
1144 av_freep(&a53->a53_caption);
1145 a53->a53_caption_size = 0;
1151 static int h264_select_output_frame(H264Context *h)
1153 const SPS *sps = h->ps.sps;
1154 H264Picture *out = h->cur_pic_ptr;
1155 H264Picture *cur = h->cur_pic_ptr;
1156 int i, pics, out_of_order, out_idx;
1157 int invalid = 0, cnt = 0;
1160 if (sps->bitstream_restriction_flag ||
1161 h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
1162 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
1166 while (h->delayed_pic[pics])
1169 assert(pics <= MAX_DELAYED_PIC_COUNT);
1171 h->delayed_pic[pics++] = cur;
1172 if (cur->reference == 0)
1173 cur->reference = DELAYED_PIC_REF;
1175 /* Frame reordering. This code takes pictures from coding order and sorts
1176 * them by their incremental POC value into display order. It supports POC
1177 * gaps, MMCO reset codes and random resets.
1178 * A "display group" can start either with a IDR frame (f.key_frame = 1),
1179 * and/or can be closed down with a MMCO reset code. In sequences where
1180 * there is no delay, we can't detect that (since the frame was already
1181 * output to the user), so we also set h->mmco_reset to detect the MMCO
1183 * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
1184 * we increase the delay between input and output. All frames affected by
1185 * the lag (e.g. those that should have been output before another frame
1186 * that we already returned to the user) will be dropped. This is a bug
1187 * that we will fix later. */
1188 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
1189 cnt += out->poc < h->last_pocs[i];
1190 invalid += out->poc == INT_MIN;
1192 if (!h->mmco_reset && !cur->f->key_frame &&
1193 cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
1196 h->delayed_pic[pics - 2]->mmco_reset = 2;
1198 if (h->mmco_reset || cur->f->key_frame) {
1199 for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
1200 h->last_pocs[i] = INT_MIN;
1202 invalid = MAX_DELAYED_PIC_COUNT;
1204 out = h->delayed_pic[0];
1206 for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
1207 h->delayed_pic[i] &&
1208 !h->delayed_pic[i - 1]->mmco_reset &&
1209 !h->delayed_pic[i]->f->key_frame;
1211 if (h->delayed_pic[i]->poc < out->poc) {
1212 out = h->delayed_pic[i];
1215 if (h->avctx->has_b_frames == 0 &&
1216 (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
1217 h->next_outputed_poc = INT_MIN;
1218 out_of_order = !out->f->key_frame && !h->mmco_reset &&
1219 (out->poc < h->next_outputed_poc);
1221 if (sps->bitstream_restriction_flag &&
1222 h->avctx->has_b_frames >= sps->num_reorder_frames) {
1223 } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
1224 h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
1225 if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
1226 h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
1228 } else if (!h->avctx->has_b_frames &&
1229 ((h->next_outputed_poc != INT_MIN &&
1230 out->poc > h->next_outputed_poc + 2) ||
1231 cur->f->pict_type == AV_PICTURE_TYPE_B)) {
1232 h->avctx->has_b_frames++;
1235 if (pics > h->avctx->has_b_frames) {
1236 out->reference &= ~DELAYED_PIC_REF;
1237 for (i = out_idx; h->delayed_pic[i]; i++)
1238 h->delayed_pic[i] = h->delayed_pic[i + 1];
1240 memmove(h->last_pocs, &h->last_pocs[1],
1241 sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
1242 h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
1243 if (!out_of_order && pics > h->avctx->has_b_frames) {
1244 av_frame_unref(h->output_frame);
1245 ret = av_frame_ref(h->output_frame, out->f);
1249 if (out->recovered) {
1250 // We have reached an recovery point and all frames after it in
1251 // display order are "recovered".
1252 h->frame_recovered |= FRAME_RECOVERED_SEI;
1254 out->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
1256 if (!out->recovered) {
1257 if (!(h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT))
1258 av_frame_unref(h->output_frame);
1260 h->output_frame->flags |= AV_FRAME_FLAG_CORRUPT;
1263 if (out->mmco_reset) {
1265 h->next_outputed_poc = out->poc;
1266 h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
1268 h->next_outputed_poc = INT_MIN;
1271 if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
1272 h->next_outputed_poc = INT_MIN;
1274 h->next_outputed_poc = out->poc;
1279 av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
1285 /* This function is called right after decoding the slice header for a first
1286 * slice in a field (or a frame). It decides whether we are decoding a new frame
1287 * or a second field in a pair and does the necessary setup.
1289 static int h264_field_start(H264Context *h, const H264SliceContext *sl,
1290 const H2645NAL *nal)
1294 int last_pic_structure, last_pic_droppable, ret;
1296 ret = h264_init_ps(h, sl);
1302 last_pic_droppable = h->droppable;
1303 last_pic_structure = h->picture_structure;
1304 h->droppable = (nal->ref_idc == 0);
1305 h->picture_structure = sl->picture_structure;
1307 h->poc.frame_num = sl->frame_num;
1308 h->poc.poc_lsb = sl->poc_lsb;
1309 h->poc.delta_poc_bottom = sl->delta_poc_bottom;
1310 h->poc.delta_poc[0] = sl->delta_poc[0];
1311 h->poc.delta_poc[1] = sl->delta_poc[1];
1313 /* Shorten frame num gaps so we don't have to allocate reference
1314 * frames just to throw them away */
1315 if (h->poc.frame_num != h->poc.prev_frame_num) {
1316 int unwrap_prev_frame_num = h->poc.prev_frame_num;
1317 int max_frame_num = 1 << sps->log2_max_frame_num;
1319 if (unwrap_prev_frame_num > h->poc.frame_num)
1320 unwrap_prev_frame_num -= max_frame_num;
1322 if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
1323 unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
1324 if (unwrap_prev_frame_num < 0)
1325 unwrap_prev_frame_num += max_frame_num;
1327 h->poc.prev_frame_num = unwrap_prev_frame_num;
1331 /* See if we have a decoded first field looking for a pair...
1332 * Here, we're using that to see if we should mark previously
1333 * decode frames as "finished".
1334 * We have to do that before the "dummy" in-between frame allocation,
1335 * since that can modify s->current_picture_ptr. */
1336 if (h->first_field) {
1337 assert(h->cur_pic_ptr);
1338 assert(h->cur_pic_ptr->f->buf[0]);
1339 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1341 /* figure out if we have a complementary field pair */
1342 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1343 /* Previous field is unmatched. Don't display it, but let it
1344 * remain for reference if marked as such. */
1345 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1346 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1347 last_pic_structure == PICT_TOP_FIELD);
1350 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1351 /* This and previous field were reference, but had
1352 * different frame_nums. Consider this field first in
1353 * pair. Throw away previous field except for reference
1355 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1356 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1357 last_pic_structure == PICT_TOP_FIELD);
1360 /* Second field in complementary pair */
1361 if (!((last_pic_structure == PICT_TOP_FIELD &&
1362 h->picture_structure == PICT_BOTTOM_FIELD) ||
1363 (last_pic_structure == PICT_BOTTOM_FIELD &&
1364 h->picture_structure == PICT_TOP_FIELD))) {
1365 av_log(h->avctx, AV_LOG_ERROR,
1366 "Invalid field mode combination %d/%d\n",
1367 last_pic_structure, h->picture_structure);
1368 h->picture_structure = last_pic_structure;
1369 h->droppable = last_pic_droppable;
1370 return AVERROR_INVALIDDATA;
1371 } else if (last_pic_droppable != h->droppable) {
1372 avpriv_request_sample(h->avctx,
1373 "Found reference and non-reference fields in the same frame, which");
1374 h->picture_structure = last_pic_structure;
1375 h->droppable = last_pic_droppable;
1376 return AVERROR_PATCHWELCOME;
1382 while (h->poc.frame_num != h->poc.prev_frame_num &&
1383 h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
1384 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1385 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1386 h->poc.frame_num, h->poc.prev_frame_num);
1387 ret = initialize_cur_frame(h);
1393 h->poc.prev_frame_num++;
1394 h->poc.prev_frame_num %= 1 << sps->log2_max_frame_num;
1395 h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
1396 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1397 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1399 h->explicit_ref_marking = 0;
1400 ret = ff_h264_execute_ref_pic_marking(h);
1401 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1403 /* Error concealment: If a ref is missing, copy the previous ref
1405 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1406 * many assumptions about there being no actual duplicates.
1407 * FIXME: This does not copy padding for out-of-frame motion
1408 * vectors. Given we are concealing a lost frame, this probably
1409 * is not noticeable by comparison, but it should be fixed. */
1410 if (h->short_ref_count) {
1412 h->short_ref[0]->f->width == prev->f->width &&
1413 h->short_ref[0]->f->height == prev->f->height &&
1414 h->short_ref[0]->f->format == prev->f->format) {
1415 ff_thread_await_progress(&prev->tf, INT_MAX, 0);
1416 if (prev->field_picture)
1417 ff_thread_await_progress(&prev->tf, INT_MAX, 1);
1418 av_image_copy(h->short_ref[0]->f->data,
1419 h->short_ref[0]->f->linesize,
1420 (const uint8_t **)prev->f->data,
1425 h->short_ref[0]->poc = prev->poc + 2;
1427 h->short_ref[0]->frame_num = h->poc.prev_frame_num;
1431 /* See if we have a decoded first field looking for a pair...
1432 * We're using that to see whether to continue decoding in that
1433 * frame, or to allocate a new one. */
1434 if (h->first_field) {
1435 assert(h->cur_pic_ptr);
1436 assert(h->cur_pic_ptr->f->buf[0]);
1437 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1439 /* figure out if we have a complementary field pair */
1440 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1441 /* Previous field is unmatched. Don't display it, but let it
1442 * remain for reference if marked as such. */
1443 h->cur_pic_ptr = NULL;
1444 h->first_field = FIELD_PICTURE(h);
1446 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1447 /* This and the previous field had different frame_nums.
1448 * Consider this field first in pair. Throw away previous
1449 * one except for reference purposes. */
1451 h->cur_pic_ptr = NULL;
1453 /* Second field in complementary pair */
1458 /* Frame or first field in a potentially complementary pair */
1459 h->first_field = FIELD_PICTURE(h);
1462 if (!FIELD_PICTURE(h) || h->first_field) {
1463 if (h264_frame_start(h) < 0) {
1465 return AVERROR_INVALIDDATA;
1468 release_unused_pictures(h, 0);
1471 ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
1472 h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
1474 memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
1475 h->nb_mmco = sl->nb_mmco;
1476 h->explicit_ref_marking = sl->explicit_ref_marking;
1478 h->picture_idr = nal->type == H264_NAL_IDR_SLICE;
1480 if (h->sei.recovery_point.recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
1481 h->recovery_frame = (h->poc.frame_num + h->sei.recovery_point.recovery_frame_cnt) &
1482 ((1 << h->ps.sps->log2_max_frame_num) - 1);
1485 h->cur_pic_ptr->f->key_frame |= (nal->type == H264_NAL_IDR_SLICE) ||
1486 (h->sei.recovery_point.recovery_frame_cnt >= 0);
1488 if (nal->type == H264_NAL_IDR_SLICE || h->recovery_frame == h->poc.frame_num) {
1489 h->recovery_frame = -1;
1490 h->cur_pic_ptr->recovered = 1;
1492 // If we have an IDR, all frames after it in decoded order are
1494 if (nal->type == H264_NAL_IDR_SLICE)
1495 h->frame_recovered |= FRAME_RECOVERED_IDR;
1496 h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1498 /* Set the frame properties/side data. Only done for the second field in
1499 * field coded frames, since some SEI information is present for each field
1500 * and is merged by the SEI parsing code. */
1501 if (!FIELD_PICTURE(h) || !h->first_field) {
1502 ret = h264_export_frame_props(h);
1506 ret = h264_select_output_frame(h);
1511 if (h->avctx->hwaccel) {
1512 ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0);
1520 static int h264_slice_header_parse(H264SliceContext *sl, const H2645NAL *nal,
1521 const H264ParamSets *ps, AVCodecContext *avctx)
1526 unsigned int slice_type, tmp, i;
1527 int field_pic_flag, bottom_field_flag, picture_structure;
1529 sl->first_mb_addr = get_ue_golomb(&sl->gb);
1531 slice_type = get_ue_golomb_31(&sl->gb);
1532 if (slice_type > 9) {
1533 av_log(avctx, AV_LOG_ERROR,
1534 "slice type %d too large at %d\n",
1535 slice_type, sl->first_mb_addr);
1536 return AVERROR_INVALIDDATA;
1538 if (slice_type > 4) {
1540 sl->slice_type_fixed = 1;
1542 sl->slice_type_fixed = 0;
1544 slice_type = ff_h264_golomb_to_pict_type[slice_type];
1545 sl->slice_type = slice_type;
1546 sl->slice_type_nos = slice_type & 3;
1548 if (nal->type == H264_NAL_IDR_SLICE &&
1549 sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1550 av_log(avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
1551 return AVERROR_INVALIDDATA;
1554 sl->pps_id = get_ue_golomb(&sl->gb);
1555 if (sl->pps_id >= MAX_PPS_COUNT) {
1556 av_log(avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
1557 return AVERROR_INVALIDDATA;
1559 if (!ps->pps_list[sl->pps_id]) {
1560 av_log(avctx, AV_LOG_ERROR,
1561 "non-existing PPS %u referenced\n",
1563 return AVERROR_INVALIDDATA;
1565 pps = (const PPS*)ps->pps_list[sl->pps_id]->data;
1567 if (!ps->sps_list[pps->sps_id]) {
1568 av_log(avctx, AV_LOG_ERROR,
1569 "non-existing SPS %u referenced\n", pps->sps_id);
1570 return AVERROR_INVALIDDATA;
1572 sps = (const SPS*)ps->sps_list[pps->sps_id]->data;
1574 sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
1578 if (sps->frame_mbs_only_flag) {
1579 picture_structure = PICT_FRAME;
1581 field_pic_flag = get_bits1(&sl->gb);
1582 if (field_pic_flag) {
1583 bottom_field_flag = get_bits1(&sl->gb);
1584 picture_structure = PICT_TOP_FIELD + bottom_field_flag;
1586 picture_structure = PICT_FRAME;
1589 sl->picture_structure = picture_structure;
1590 sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
1592 if (picture_structure == PICT_FRAME) {
1593 sl->curr_pic_num = sl->frame_num;
1594 sl->max_pic_num = 1 << sps->log2_max_frame_num;
1596 sl->curr_pic_num = 2 * sl->frame_num + 1;
1597 sl->max_pic_num = 1 << (sps->log2_max_frame_num + 1);
1600 if (nal->type == H264_NAL_IDR_SLICE)
1601 get_ue_golomb(&sl->gb); /* idr_pic_id */
1603 if (sps->poc_type == 0) {
1604 sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
1606 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1607 sl->delta_poc_bottom = get_se_golomb(&sl->gb);
1610 if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
1611 sl->delta_poc[0] = get_se_golomb(&sl->gb);
1613 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1614 sl->delta_poc[1] = get_se_golomb(&sl->gb);
1617 sl->redundant_pic_count = 0;
1618 if (pps->redundant_pic_cnt_present)
1619 sl->redundant_pic_count = get_ue_golomb(&sl->gb);
1621 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1622 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1624 ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
1625 &sl->gb, pps, sl->slice_type_nos,
1630 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1631 ret = ff_h264_decode_ref_pic_list_reordering(sl, avctx);
1633 sl->ref_count[1] = sl->ref_count[0] = 0;
1638 sl->pwt.use_weight = 0;
1639 for (i = 0; i < 2; i++) {
1640 sl->pwt.luma_weight_flag[i] = 0;
1641 sl->pwt.chroma_weight_flag[i] = 0;
1643 if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
1644 (pps->weighted_bipred_idc == 1 &&
1645 sl->slice_type_nos == AV_PICTURE_TYPE_B))
1646 ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
1647 sl->slice_type_nos, &sl->pwt);
1649 sl->explicit_ref_marking = 0;
1651 ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, avctx);
1652 if (ret < 0 && (avctx->err_recognition & AV_EF_EXPLODE))
1653 return AVERROR_INVALIDDATA;
1656 if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1657 tmp = get_ue_golomb_31(&sl->gb);
1659 av_log(avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1660 return AVERROR_INVALIDDATA;
1662 sl->cabac_init_idc = tmp;
1665 sl->last_qscale_diff = 0;
1666 tmp = pps->init_qp + get_se_golomb(&sl->gb);
1667 if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
1668 av_log(avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1669 return AVERROR_INVALIDDATA;
1672 sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
1673 sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
1674 // FIXME qscale / qp ... stuff
1675 if (sl->slice_type == AV_PICTURE_TYPE_SP)
1676 get_bits1(&sl->gb); /* sp_for_switch_flag */
1677 if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1678 sl->slice_type == AV_PICTURE_TYPE_SI)
1679 get_se_golomb(&sl->gb); /* slice_qs_delta */
1681 sl->deblocking_filter = 1;
1682 sl->slice_alpha_c0_offset = 0;
1683 sl->slice_beta_offset = 0;
1684 if (pps->deblocking_filter_parameters_present) {
1685 tmp = get_ue_golomb_31(&sl->gb);
1687 av_log(avctx, AV_LOG_ERROR,
1688 "deblocking_filter_idc %u out of range\n", tmp);
1689 return AVERROR_INVALIDDATA;
1691 sl->deblocking_filter = tmp;
1692 if (sl->deblocking_filter < 2)
1693 sl->deblocking_filter ^= 1; // 1<->0
1695 if (sl->deblocking_filter) {
1696 sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
1697 sl->slice_beta_offset = get_se_golomb(&sl->gb) * 2;
1698 if (sl->slice_alpha_c0_offset > 12 ||
1699 sl->slice_alpha_c0_offset < -12 ||
1700 sl->slice_beta_offset > 12 ||
1701 sl->slice_beta_offset < -12) {
1702 av_log(avctx, AV_LOG_ERROR,
1703 "deblocking filter parameters %d %d out of range\n",
1704 sl->slice_alpha_c0_offset, sl->slice_beta_offset);
1705 return AVERROR_INVALIDDATA;
1713 /* do all the per-slice initialization needed before we can start decoding the
1715 static int h264_slice_init(H264Context *h, H264SliceContext *sl,
1716 const H2645NAL *nal)
1720 if (h->current_slice > 0) {
1721 if (h->ps.pps != (const PPS*)h->ps.pps_list[sl->pps_id]->data) {
1722 av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
1723 return AVERROR_INVALIDDATA;
1726 if (h->picture_structure != sl->picture_structure ||
1727 h->droppable != (nal->ref_idc == 0)) {
1728 av_log(h->avctx, AV_LOG_ERROR,
1729 "Changing field mode (%d -> %d) between slices is not allowed\n",
1730 h->picture_structure, sl->picture_structure);
1731 return AVERROR_INVALIDDATA;
1732 } else if (!h->cur_pic_ptr) {
1733 av_log(h->avctx, AV_LOG_ERROR,
1734 "unset cur_pic_ptr on slice %d\n",
1735 h->current_slice + 1);
1736 return AVERROR_INVALIDDATA;
1740 if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {
1741 av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");
1742 return AVERROR_INVALIDDATA;
1745 assert(h->mb_num == h->mb_width * h->mb_height);
1746 if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1747 sl->first_mb_addr >= h->mb_num) {
1748 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1749 return AVERROR_INVALIDDATA;
1751 sl->resync_mb_x = sl->mb_x = sl->first_mb_addr % h->mb_width;
1752 sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
1753 FIELD_OR_MBAFF_PICTURE(h);
1754 if (h->picture_structure == PICT_BOTTOM_FIELD)
1755 sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
1756 assert(sl->mb_y < h->mb_height);
1758 ret = ff_h264_build_ref_list(h, sl);
1762 if (h->ps.pps->weighted_bipred_idc == 2 &&
1763 sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1764 implicit_weight_table(h, sl, -1);
1765 if (FRAME_MBAFF(h)) {
1766 implicit_weight_table(h, sl, 0);
1767 implicit_weight_table(h, sl, 1);
1771 if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
1772 ff_h264_direct_dist_scale_factor(h, sl);
1773 ff_h264_direct_ref_list_init(h, sl);
1775 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1776 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
1777 sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
1778 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
1779 sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
1780 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1782 sl->deblocking_filter = 0;
1784 if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
1785 if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
1786 /* Cheat slightly for speed:
1787 * Do not bother to deblock across slices. */
1788 sl->deblocking_filter = 2;
1790 h->postpone_filter = 1;
1793 sl->qp_thresh = 15 -
1794 FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
1796 h->ps.pps->chroma_qp_index_offset[0],
1797 h->ps.pps->chroma_qp_index_offset[1]) +
1798 6 * (h->ps.sps->bit_depth_luma - 8);
1800 sl->slice_num = ++h->current_slice;
1801 if (sl->slice_num >= MAX_SLICES) {
1802 av_log(h->avctx, AV_LOG_ERROR,
1803 "Too many slices, increase MAX_SLICES and recompile\n");
1806 for (j = 0; j < 2; j++) {
1808 int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
1809 for (i = 0; i < 16; i++) {
1811 if (j < sl->list_count && i < sl->ref_count[j] &&
1812 sl->ref_list[j][i].parent->f->buf[0]) {
1814 AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
1815 for (k = 0; k < h->short_ref_count; k++)
1816 if (h->short_ref[k]->f->buf[0]->buffer == buf) {
1820 for (k = 0; k < h->long_ref_count; k++)
1821 if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
1822 id_list[i] = h->short_ref_count + k;
1830 for (i = 0; i < 16; i++)
1831 ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
1833 ref2frm[18 + 1] = -1;
1834 for (i = 16; i < 48; i++)
1835 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
1836 (sl->ref_list[j][i].reference & 3);
1839 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
1840 av_log(h->avctx, AV_LOG_DEBUG,
1841 "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",
1843 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
1844 sl->mb_y * h->mb_width + sl->mb_x,
1845 av_get_picture_type_char(sl->slice_type),
1846 sl->slice_type_fixed ? " fix" : "",
1847 nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",
1849 h->cur_pic_ptr->field_poc[0],
1850 h->cur_pic_ptr->field_poc[1],
1851 sl->ref_count[0], sl->ref_count[1],
1853 sl->deblocking_filter,
1854 sl->slice_alpha_c0_offset, sl->slice_beta_offset,
1856 sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
1857 sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
1863 int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)
1865 H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
1870 ret = h264_slice_header_parse(sl, nal, &h->ps, h->avctx);
1874 // discard redundant pictures
1875 if (sl->redundant_pic_count > 0)
1878 if (!h->setup_finished) {
1879 if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
1880 // this slice starts a new field
1881 // first decode any pending queued slices
1882 if (h->nb_slice_ctx_queued) {
1883 H264SliceContext tmp_ctx;
1885 ret = ff_h264_execute_decode_slices(h);
1886 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1889 memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));
1890 memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));
1891 memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));
1895 if (h->field_started)
1896 ff_h264_field_end(h, sl, 1);
1898 h->current_slice = 0;
1899 if (!h->first_field) {
1900 if (h->cur_pic_ptr && !h->droppable) {
1901 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1902 h->picture_structure == PICT_BOTTOM_FIELD);
1904 h->cur_pic_ptr = NULL;
1908 if (h->current_slice == 0) {
1909 ret = h264_field_start(h, sl, nal);
1912 h->field_started = 1;
1916 ret = h264_slice_init(h, sl, nal);
1920 if ((h->avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
1921 (h->avctx->skip_frame < AVDISCARD_BIDIR ||
1922 sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
1923 (h->avctx->skip_frame < AVDISCARD_NONKEY ||
1924 h->cur_pic_ptr->f->key_frame) &&
1925 h->avctx->skip_frame < AVDISCARD_ALL) {
1926 h->nb_slice_ctx_queued++;
1932 int ff_h264_get_slice_type(const H264SliceContext *sl)
1934 switch (sl->slice_type) {
1935 case AV_PICTURE_TYPE_P:
1937 case AV_PICTURE_TYPE_B:
1939 case AV_PICTURE_TYPE_I:
1941 case AV_PICTURE_TYPE_SP:
1943 case AV_PICTURE_TYPE_SI:
1946 return AVERROR_INVALIDDATA;
1950 static av_always_inline void fill_filter_caches_inter(const H264Context *h,
1951 H264SliceContext *sl,
1952 int mb_type, int top_xy,
1953 int left_xy[LEFT_MBS],
1955 int left_type[LEFT_MBS],
1956 int mb_xy, int list)
1958 int b_stride = h->b_stride;
1959 int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
1960 int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
1961 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
1962 if (USES_LIST(top_type, list)) {
1963 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
1964 const int b8_xy = 4 * top_xy + 2;
1965 const int *ref2frm = &h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1966 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
1967 ref_cache[0 - 1 * 8] =
1968 ref_cache[1 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 0]];
1969 ref_cache[2 - 1 * 8] =
1970 ref_cache[3 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 1]];
1972 AV_ZERO128(mv_dst - 1 * 8);
1973 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1976 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
1977 if (USES_LIST(left_type[LTOP], list)) {
1978 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
1979 const int b8_xy = 4 * left_xy[LTOP] + 1;
1980 const int *ref2frm = &h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
1981 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
1982 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
1983 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
1984 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
1986 ref_cache[-1 + 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
1987 ref_cache[-1 + 16] =
1988 ref_cache[-1 + 24] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
1990 AV_ZERO32(mv_dst - 1 + 0);
1991 AV_ZERO32(mv_dst - 1 + 8);
1992 AV_ZERO32(mv_dst - 1 + 16);
1993 AV_ZERO32(mv_dst - 1 + 24);
1996 ref_cache[-1 + 16] =
1997 ref_cache[-1 + 24] = LIST_NOT_USED;
2002 if (!USES_LIST(mb_type, list)) {
2003 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
2004 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2005 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2006 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2007 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2012 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
2013 const int *ref2frm = &h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
2014 uint32_t ref01 = (pack16to32(ref2frm[ref[0]], ref2frm[ref[1]]) & 0x00FF00FF) * 0x0101;
2015 uint32_t ref23 = (pack16to32(ref2frm[ref[2]], ref2frm[ref[3]]) & 0x00FF00FF) * 0x0101;
2016 AV_WN32A(&ref_cache[0 * 8], ref01);
2017 AV_WN32A(&ref_cache[1 * 8], ref01);
2018 AV_WN32A(&ref_cache[2 * 8], ref23);
2019 AV_WN32A(&ref_cache[3 * 8], ref23);
2023 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
2024 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
2025 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
2026 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
2027 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
2032 * @return non zero if the loop filter can be skipped
2034 static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
2036 const int mb_xy = sl->mb_xy;
2037 int top_xy, left_xy[LEFT_MBS];
2038 int top_type, left_type[LEFT_MBS];
2042 top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
2044 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
2045 if (FRAME_MBAFF(h)) {
2046 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
2047 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
2049 if (left_mb_field_flag != curr_mb_field_flag)
2050 left_xy[LTOP] -= h->mb_stride;
2052 if (curr_mb_field_flag)
2053 top_xy += h->mb_stride &
2054 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
2055 if (left_mb_field_flag != curr_mb_field_flag)
2056 left_xy[LBOT] += h->mb_stride;
2060 sl->top_mb_xy = top_xy;
2061 sl->left_mb_xy[LTOP] = left_xy[LTOP];
2062 sl->left_mb_xy[LBOT] = left_xy[LBOT];
2064 /* For sufficiently low qp, filtering wouldn't do anything.
2065 * This is a conservative estimate: could also check beta_offset
2066 * and more accurate chroma_qp. */
2067 int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
2068 int qp = h->cur_pic.qscale_table[mb_xy];
2069 if (qp <= qp_thresh &&
2070 (left_xy[LTOP] < 0 ||
2071 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
2073 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
2074 if (!FRAME_MBAFF(h))
2076 if ((left_xy[LTOP] < 0 ||
2077 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
2078 (top_xy < h->mb_stride ||
2079 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
2084 top_type = h->cur_pic.mb_type[top_xy];
2085 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
2086 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
2087 if (sl->deblocking_filter == 2) {
2088 if (h->slice_table[top_xy] != sl->slice_num)
2090 if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
2091 left_type[LTOP] = left_type[LBOT] = 0;
2093 if (h->slice_table[top_xy] == 0xFFFF)
2095 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
2096 left_type[LTOP] = left_type[LBOT] = 0;
2098 sl->top_type = top_type;
2099 sl->left_type[LTOP] = left_type[LTOP];
2100 sl->left_type[LBOT] = left_type[LBOT];
2102 if (IS_INTRA(mb_type))
2105 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2106 top_type, left_type, mb_xy, 0);
2107 if (sl->list_count == 2)
2108 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2109 top_type, left_type, mb_xy, 1);
2111 nnz = h->non_zero_count[mb_xy];
2112 nnz_cache = sl->non_zero_count_cache;
2113 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
2114 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
2115 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
2116 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
2117 sl->cbp = h->cbp_table[mb_xy];
2120 nnz = h->non_zero_count[top_xy];
2121 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
2124 if (left_type[LTOP]) {
2125 nnz = h->non_zero_count[left_xy[LTOP]];
2126 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
2127 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
2128 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
2129 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
2132 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
2133 * from what the loop filter needs */
2134 if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
2135 if (IS_8x8DCT(top_type)) {
2136 nnz_cache[4 + 8 * 0] =
2137 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
2138 nnz_cache[6 + 8 * 0] =
2139 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
2141 if (IS_8x8DCT(left_type[LTOP])) {
2142 nnz_cache[3 + 8 * 1] =
2143 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
2145 if (IS_8x8DCT(left_type[LBOT])) {
2146 nnz_cache[3 + 8 * 3] =
2147 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
2150 if (IS_8x8DCT(mb_type)) {
2151 nnz_cache[scan8[0]] =
2152 nnz_cache[scan8[1]] =
2153 nnz_cache[scan8[2]] =
2154 nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
2156 nnz_cache[scan8[0 + 4]] =
2157 nnz_cache[scan8[1 + 4]] =
2158 nnz_cache[scan8[2 + 4]] =
2159 nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
2161 nnz_cache[scan8[0 + 8]] =
2162 nnz_cache[scan8[1 + 8]] =
2163 nnz_cache[scan8[2 + 8]] =
2164 nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
2166 nnz_cache[scan8[0 + 12]] =
2167 nnz_cache[scan8[1 + 12]] =
2168 nnz_cache[scan8[2 + 12]] =
2169 nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
2176 static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
2178 uint8_t *dest_y, *dest_cb, *dest_cr;
2179 int linesize, uvlinesize, mb_x, mb_y;
2180 const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
2181 const int old_slice_type = sl->slice_type;
2182 const int pixel_shift = h->pixel_shift;
2183 const int block_h = 16 >> h->chroma_y_shift;
2185 if (h->postpone_filter)
2188 if (sl->deblocking_filter) {
2189 for (mb_x = start_x; mb_x < end_x; mb_x++)
2190 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
2192 mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
2193 mb_type = h->cur_pic.mb_type[mb_xy];
2197 sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2201 dest_y = h->cur_pic.f->data[0] +
2202 ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
2203 dest_cb = h->cur_pic.f->data[1] +
2204 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2205 mb_y * sl->uvlinesize * block_h;
2206 dest_cr = h->cur_pic.f->data[2] +
2207 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2208 mb_y * sl->uvlinesize * block_h;
2209 // FIXME simplify above
2212 linesize = sl->mb_linesize = sl->linesize * 2;
2213 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
2214 if (mb_y & 1) { // FIXME move out of this function?
2215 dest_y -= sl->linesize * 15;
2216 dest_cb -= sl->uvlinesize * (block_h - 1);
2217 dest_cr -= sl->uvlinesize * (block_h - 1);
2220 linesize = sl->mb_linesize = sl->linesize;
2221 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
2223 backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
2225 if (fill_filter_caches(h, sl, mb_type))
2227 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
2228 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
2230 if (FRAME_MBAFF(h)) {
2231 ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
2232 linesize, uvlinesize);
2234 ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
2235 dest_cr, linesize, uvlinesize);
2239 sl->slice_type = old_slice_type;
2241 sl->mb_y = end_mb_y - FRAME_MBAFF(h);
2242 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
2243 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
2246 static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
2248 const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
2249 int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
2250 h->cur_pic.mb_type[mb_xy - 1] :
2251 (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
2252 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
2253 sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2257 * Draw edges and report progress for the last MB row.
2259 static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
2261 int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
2262 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
2263 int height = 16 << FRAME_MBAFF(h);
2264 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
2266 if (sl->deblocking_filter) {
2267 if ((top + height) >= pic_height)
2268 height += deblock_border;
2269 top -= deblock_border;
2272 if (top >= pic_height || (top + height) < 0)
2275 height = FFMIN(height, pic_height - top);
2277 height = top + height;
2281 ff_h264_draw_horiz_band(h, sl, top, height);
2286 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
2287 h->picture_structure == PICT_BOTTOM_FIELD);
2290 static void er_add_slice(H264SliceContext *sl,
2291 int startx, int starty,
2292 int endx, int endy, int status)
2294 #if CONFIG_ERROR_RESILIENCE
2295 ERContext *er = &sl->er;
2297 if (!sl->h264->enable_er)
2300 er->ref_count = sl->ref_count[0];
2301 ff_er_add_slice(er, startx, starty, endx, endy, status);
2305 static int decode_slice(struct AVCodecContext *avctx, void *arg)
2307 H264SliceContext *sl = arg;
2308 const H264Context *h = sl->h264;
2309 int lf_x_start = sl->mb_x;
2310 int orig_deblock = sl->deblocking_filter;
2313 sl->linesize = h->cur_pic_ptr->f->linesize[0];
2314 sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
2316 ret = alloc_scratch_buffers(sl, sl->linesize);
2320 sl->mb_skip_run = -1;
2322 if (h->postpone_filter)
2323 sl->deblocking_filter = 0;
2325 sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
2326 (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
2328 if (h->ps.pps->cabac) {
2330 align_get_bits(&sl->gb);
2333 ff_init_cabac_decoder(&sl->cabac,
2334 sl->gb.buffer + get_bits_count(&sl->gb) / 8,
2335 (get_bits_left(&sl->gb) + 7) / 8);
2337 ff_h264_init_cabac_states(h, sl);
2343 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2344 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2345 sl->next_slice_idx);
2346 return AVERROR_INVALIDDATA;
2349 ret = ff_h264_decode_mb_cabac(h, sl);
2350 // STOP_TIMER("decode_mb_cabac")
2353 ff_h264_hl_decode_mb(h, sl);
2355 // FIXME optimal? or let mb_decode decode 16x32 ?
2356 if (ret >= 0 && FRAME_MBAFF(h)) {
2359 ret = ff_h264_decode_mb_cabac(h, sl);
2362 ff_h264_hl_decode_mb(h, sl);
2365 eos = get_cabac_terminate(&sl->cabac);
2367 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
2368 sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2369 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2370 sl->mb_y, ER_MB_END);
2371 if (sl->mb_x >= lf_x_start)
2372 loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
2375 if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2376 av_log(h->avctx, AV_LOG_ERROR,
2377 "error while decoding MB %d %d, bytestream %td\n",
2379 sl->cabac.bytestream_end - sl->cabac.bytestream);
2380 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2381 sl->mb_y, ER_MB_ERROR);
2382 return AVERROR_INVALIDDATA;
2385 if (++sl->mb_x >= h->mb_width) {
2386 loop_filter(h, sl, lf_x_start, sl->mb_x);
2387 sl->mb_x = lf_x_start = 0;
2388 decode_finish_row(h, sl);
2390 if (FIELD_OR_MBAFF_PICTURE(h)) {
2392 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2393 predict_field_decoding_flag(h, sl);
2397 if (eos || sl->mb_y >= h->mb_height) {
2398 ff_tlog(h->avctx, "slice end %d %d\n",
2399 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2400 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2401 sl->mb_y, ER_MB_END);
2402 if (sl->mb_x > lf_x_start)
2403 loop_filter(h, sl, lf_x_start, sl->mb_x);
2411 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2412 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2413 sl->next_slice_idx);
2414 return AVERROR_INVALIDDATA;
2417 ret = ff_h264_decode_mb_cavlc(h, sl);
2420 ff_h264_hl_decode_mb(h, sl);
2422 // FIXME optimal? or let mb_decode decode 16x32 ?
2423 if (ret >= 0 && FRAME_MBAFF(h)) {
2425 ret = ff_h264_decode_mb_cavlc(h, sl);
2428 ff_h264_hl_decode_mb(h, sl);
2433 av_log(h->avctx, AV_LOG_ERROR,
2434 "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
2435 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2436 sl->mb_y, ER_MB_ERROR);
2440 if (++sl->mb_x >= h->mb_width) {
2441 loop_filter(h, sl, lf_x_start, sl->mb_x);
2442 sl->mb_x = lf_x_start = 0;
2443 decode_finish_row(h, sl);
2445 if (FIELD_OR_MBAFF_PICTURE(h)) {
2447 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2448 predict_field_decoding_flag(h, sl);
2450 if (sl->mb_y >= h->mb_height) {
2451 ff_tlog(h->avctx, "slice end %d %d\n",
2452 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2454 if (get_bits_left(&sl->gb) == 0) {
2455 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2456 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2460 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2461 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2463 return AVERROR_INVALIDDATA;
2468 if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
2469 ff_tlog(h->avctx, "slice end %d %d\n",
2470 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2472 if (get_bits_left(&sl->gb) == 0) {
2473 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2474 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2475 if (sl->mb_x > lf_x_start)
2476 loop_filter(h, sl, lf_x_start, sl->mb_x);
2480 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2481 sl->mb_y, ER_MB_ERROR);
2483 return AVERROR_INVALIDDATA;
2490 sl->deblocking_filter = orig_deblock;
2495 * Call decode_slice() for each context.
2497 * @param h h264 master context
2499 int ff_h264_execute_decode_slices(H264Context *h)
2501 AVCodecContext *const avctx = h->avctx;
2502 H264SliceContext *sl;
2503 int context_count = h->nb_slice_ctx_queued;
2507 if (h->avctx->hwaccel || context_count < 1)
2509 if (context_count == 1) {
2511 h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2512 h->postpone_filter = 0;
2514 ret = decode_slice(avctx, &h->slice_ctx[0]);
2515 h->mb_y = h->slice_ctx[0].mb_y;
2519 for (i = 0; i < context_count; i++) {
2520 int next_slice_idx = h->mb_width * h->mb_height;
2523 sl = &h->slice_ctx[i];
2524 sl->er.error_count = 0;
2526 /* make sure none of those slices overlap */
2527 slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2528 for (j = 0; j < context_count; j++) {
2529 H264SliceContext *sl2 = &h->slice_ctx[j];
2530 int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2532 if (i == j || slice_idx2 < slice_idx)
2534 next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2536 sl->next_slice_idx = next_slice_idx;
2539 avctx->execute(avctx, decode_slice, h->slice_ctx,
2540 NULL, context_count, sizeof(h->slice_ctx[0]));
2542 /* pull back stuff from slices to master context */
2543 sl = &h->slice_ctx[context_count - 1];
2545 for (i = 1; i < context_count; i++)
2546 h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
2548 if (h->postpone_filter) {
2549 h->postpone_filter = 0;
2551 for (i = 0; i < context_count; i++) {
2554 sl = &h->slice_ctx[i];
2555 y_end = FFMIN(sl->mb_y + 1, h->mb_height);
2556 x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
2558 for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
2560 loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
2561 j == y_end - 1 ? x_end : h->mb_width);
2568 h->nb_slice_ctx_queued = 0;