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/imgutils.h"
30 #include "libavutil/timer.h"
33 #include "cabac_functions.h"
34 #include "error_resilience.h"
38 #include "h264chroma.h"
39 #include "h264_mvpred.h"
42 #include "mpegutils.h"
43 #include "rectangle.h"
46 static const uint8_t field_scan[16] = {
47 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
48 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
49 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
50 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
53 static const uint8_t field_scan8x8[64] = {
54 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
55 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
56 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
57 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
58 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
59 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
60 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
61 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
62 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
63 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
64 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
65 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
66 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
67 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
68 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
69 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
72 static const uint8_t field_scan8x8_cavlc[64] = {
73 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
74 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
75 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
76 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
77 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
78 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
79 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
80 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
81 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
82 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
83 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
84 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
85 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
86 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
87 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
88 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
91 // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
92 static const uint8_t zigzag_scan8x8_cavlc[64] = {
93 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
94 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
95 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
96 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
97 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
98 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
99 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
100 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
101 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
102 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
103 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
104 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
105 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
106 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
107 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
108 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
111 static void release_unused_pictures(H264Context *h, int remove_current)
115 /* release non reference frames */
116 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
117 if (h->DPB[i].f->buf[0] && !h->DPB[i].reference &&
118 (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
119 ff_h264_unref_picture(h, &h->DPB[i]);
124 static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
126 const H264Context *h = sl->h264;
127 int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
129 av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
130 // edge emu needs blocksize + filter length - 1
131 // (= 21x21 for H.264)
132 av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
134 av_fast_malloc(&sl->top_borders[0], &sl->top_borders_allocated[0],
135 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
136 av_fast_malloc(&sl->top_borders[1], &sl->top_borders_allocated[1],
137 h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
139 if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
140 !sl->top_borders[0] || !sl->top_borders[1]) {
141 av_freep(&sl->bipred_scratchpad);
142 av_freep(&sl->edge_emu_buffer);
143 av_freep(&sl->top_borders[0]);
144 av_freep(&sl->top_borders[1]);
146 sl->bipred_scratchpad_allocated = 0;
147 sl->edge_emu_buffer_allocated = 0;
148 sl->top_borders_allocated[0] = 0;
149 sl->top_borders_allocated[1] = 0;
150 return AVERROR(ENOMEM);
156 static int init_table_pools(H264Context *h)
158 const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
159 const int mb_array_size = h->mb_stride * h->mb_height;
160 const int b4_stride = h->mb_width * 4 + 1;
161 const int b4_array_size = b4_stride * h->mb_height * 4;
163 h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
165 h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
166 sizeof(uint32_t), av_buffer_allocz);
167 h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
168 sizeof(int16_t), av_buffer_allocz);
169 h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
171 if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
172 !h->ref_index_pool) {
173 av_buffer_pool_uninit(&h->qscale_table_pool);
174 av_buffer_pool_uninit(&h->mb_type_pool);
175 av_buffer_pool_uninit(&h->motion_val_pool);
176 av_buffer_pool_uninit(&h->ref_index_pool);
177 return AVERROR(ENOMEM);
183 static int alloc_picture(H264Context *h, H264Picture *pic)
187 av_assert0(!pic->f->data[0]);
190 ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
191 AV_GET_BUFFER_FLAG_REF : 0);
195 if (h->avctx->hwaccel) {
196 const AVHWAccel *hwaccel = h->avctx->hwaccel;
197 av_assert0(!pic->hwaccel_picture_private);
198 if (hwaccel->frame_priv_data_size) {
199 pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
200 if (!pic->hwaccel_priv_buf)
201 return AVERROR(ENOMEM);
202 pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
206 if (!h->qscale_table_pool) {
207 ret = init_table_pools(h);
212 pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
213 pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
214 if (!pic->qscale_table_buf || !pic->mb_type_buf)
217 pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
218 pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
220 for (i = 0; i < 2; i++) {
221 pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
222 pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
223 if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
226 pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
227 pic->ref_index[i] = pic->ref_index_buf[i]->data;
232 ff_h264_unref_picture(h, pic);
233 return (ret < 0) ? ret : AVERROR(ENOMEM);
236 static inline int pic_is_unused(H264Context *h, H264Picture *pic)
243 static int find_unused_picture(H264Context *h)
247 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
248 if (pic_is_unused(h, &h->DPB[i]))
251 if (i == H264_MAX_PICTURE_COUNT)
252 return AVERROR_INVALIDDATA;
257 static int initialize_cur_frame(H264Context *h)
262 release_unused_pictures(h, 1);
263 ff_h264_unref_picture(h, &h->cur_pic);
264 h->cur_pic_ptr = NULL;
266 ret = find_unused_picture(h);
268 av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
273 ret = alloc_picture(h, cur);
277 ret = ff_h264_ref_picture(h, &h->cur_pic, cur);
280 h->cur_pic_ptr = cur;
285 #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
287 #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
288 ((pic && pic >= old_ctx->DPB && \
289 pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
290 &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
292 static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
293 H264Context *new_base,
294 H264Context *old_base)
298 for (i = 0; i < count; i++) {
299 assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
300 IN_RANGE(from[i], old_base->DPB,
301 sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
303 to[i] = REBASE_PICTURE(from[i], new_base, old_base);
307 static int h264_slice_header_init(H264Context *h);
309 int ff_h264_update_thread_context(AVCodecContext *dst,
310 const AVCodecContext *src)
312 H264Context *h = dst->priv_data, *h1 = src->priv_data;
313 int inited = h->context_initialized, err = 0;
317 if (dst == src || !h1->context_initialized)
321 return AVERROR_INVALIDDATA;
324 (h->width != h1->width ||
325 h->height != h1->height ||
326 h->mb_width != h1->mb_width ||
327 h->mb_height != h1->mb_height ||
329 h->ps.sps->bit_depth_luma != h1->ps.sps->bit_depth_luma ||
330 h->ps.sps->chroma_format_idc != h1->ps.sps->chroma_format_idc ||
331 h->ps.sps->colorspace != h1->ps.sps->colorspace)) {
336 for (i = 0; i < FF_ARRAY_ELEMS(h->ps.sps_list); i++) {
337 av_buffer_unref(&h->ps.sps_list[i]);
338 if (h1->ps.sps_list[i]) {
339 h->ps.sps_list[i] = av_buffer_ref(h1->ps.sps_list[i]);
340 if (!h->ps.sps_list[i])
341 return AVERROR(ENOMEM);
344 for (i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++) {
345 av_buffer_unref(&h->ps.pps_list[i]);
346 if (h1->ps.pps_list[i]) {
347 h->ps.pps_list[i] = av_buffer_ref(h1->ps.pps_list[i]);
348 if (!h->ps.pps_list[i])
349 return AVERROR(ENOMEM);
353 h->ps.sps = h1->ps.sps;
355 if (need_reinit || !inited) {
356 h->width = h1->width;
357 h->height = h1->height;
358 h->mb_height = h1->mb_height;
359 h->mb_width = h1->mb_width;
360 h->mb_num = h1->mb_num;
361 h->mb_stride = h1->mb_stride;
362 h->b_stride = h1->b_stride;
364 if ((err = h264_slice_header_init(h)) < 0) {
365 av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
369 /* copy block_offset since frame_start may not be called */
370 memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
373 h->avctx->coded_height = h1->avctx->coded_height;
374 h->avctx->coded_width = h1->avctx->coded_width;
375 h->avctx->width = h1->avctx->width;
376 h->avctx->height = h1->avctx->height;
377 h->coded_picture_number = h1->coded_picture_number;
378 h->first_field = h1->first_field;
379 h->picture_structure = h1->picture_structure;
380 h->mb_aff_frame = h1->mb_aff_frame;
381 h->droppable = h1->droppable;
383 for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
384 ff_h264_unref_picture(h, &h->DPB[i]);
385 if (h1->DPB[i].f->buf[0] &&
386 (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
390 h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
391 ff_h264_unref_picture(h, &h->cur_pic);
392 if (h1->cur_pic.f->buf[0]) {
393 ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
398 h->enable_er = h1->enable_er;
399 h->workaround_bugs = h1->workaround_bugs;
400 h->droppable = h1->droppable;
402 // extradata/NAL handling
403 h->is_avc = h1->is_avc;
404 h->nal_length_size = h1->nal_length_size;
406 memcpy(&h->poc, &h1->poc, sizeof(h->poc));
408 h->curr_pic_num = h1->curr_pic_num;
409 h->max_pic_num = h1->max_pic_num;
411 memcpy(h->short_ref, h1->short_ref, sizeof(h->short_ref));
412 memcpy(h->long_ref, h1->long_ref, sizeof(h->long_ref));
413 memcpy(h->delayed_pic, h1->delayed_pic, sizeof(h->delayed_pic));
414 memcpy(h->last_pocs, h1->last_pocs, sizeof(h->last_pocs));
416 h->next_output_pic = h1->next_output_pic;
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->next_output_pic = NULL;
503 h->postpone_filter = 0;
505 h->mb_aff_frame = h->ps.sps->mb_aff && (h->picture_structure == PICT_FRAME);
507 assert(h->cur_pic_ptr->long_ref == 0);
512 static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
514 uint8_t *src_cb, uint8_t *src_cr,
515 int linesize, int uvlinesize,
520 const int pixel_shift = h->pixel_shift;
521 int chroma444 = CHROMA444(h);
522 int chroma422 = CHROMA422(h);
525 src_cb -= uvlinesize;
526 src_cr -= uvlinesize;
528 if (!simple && FRAME_MBAFF(h)) {
531 top_border = sl->top_borders[0][sl->mb_x];
532 AV_COPY128(top_border, src_y + 15 * linesize);
534 AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
535 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
538 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
539 AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
540 AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
541 AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
543 AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
544 AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
546 } else if (chroma422) {
548 AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
549 AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
551 AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
552 AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
556 AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
557 AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
559 AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
560 AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
565 } else if (MB_MBAFF(sl)) {
571 top_border = sl->top_borders[top_idx][sl->mb_x];
572 /* There are two lines saved, the line above the top macroblock
573 * of a pair, and the line above the bottom macroblock. */
574 AV_COPY128(top_border, src_y + 16 * linesize);
576 AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
578 if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
581 AV_COPY128(top_border + 32, src_cb + 16 * linesize);
582 AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
583 AV_COPY128(top_border + 64, src_cr + 16 * linesize);
584 AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
586 AV_COPY128(top_border + 16, src_cb + 16 * linesize);
587 AV_COPY128(top_border + 32, src_cr + 16 * linesize);
589 } else if (chroma422) {
591 AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
592 AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
594 AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
595 AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
599 AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
600 AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
602 AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
603 AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
610 * Initialize implicit_weight table.
611 * @param field 0/1 initialize the weight for interlaced MBAFF
612 * -1 initializes the rest
614 static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
616 int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
618 for (i = 0; i < 2; i++) {
619 sl->pwt.luma_weight_flag[i] = 0;
620 sl->pwt.chroma_weight_flag[i] = 0;
624 if (h->picture_structure == PICT_FRAME) {
625 cur_poc = h->cur_pic_ptr->poc;
627 cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
629 if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
630 sl->ref_list[0][0].poc + sl->ref_list[1][0].poc == 2 * cur_poc) {
631 sl->pwt.use_weight = 0;
632 sl->pwt.use_weight_chroma = 0;
636 ref_count0 = sl->ref_count[0];
637 ref_count1 = sl->ref_count[1];
639 cur_poc = h->cur_pic_ptr->field_poc[field];
641 ref_count0 = 16 + 2 * sl->ref_count[0];
642 ref_count1 = 16 + 2 * sl->ref_count[1];
645 sl->pwt.use_weight = 2;
646 sl->pwt.use_weight_chroma = 2;
647 sl->pwt.luma_log2_weight_denom = 5;
648 sl->pwt.chroma_log2_weight_denom = 5;
650 for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
651 int poc0 = sl->ref_list[0][ref0].poc;
652 for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
654 if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
655 int poc1 = sl->ref_list[1][ref1].poc;
656 int td = av_clip_int8(poc1 - poc0);
658 int tb = av_clip_int8(cur_poc - poc0);
659 int tx = (16384 + (FFABS(td) >> 1)) / td;
660 int dist_scale_factor = (tb * tx + 32) >> 8;
661 if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
662 w = 64 - dist_scale_factor;
666 sl->pwt.implicit_weight[ref0][ref1][0] =
667 sl->pwt.implicit_weight[ref0][ref1][1] = w;
669 sl->pwt.implicit_weight[ref0][ref1][field] = w;
676 * initialize scan tables
678 static void init_scan_tables(H264Context *h)
681 for (i = 0; i < 16; i++) {
682 #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
683 h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
684 h->field_scan[i] = TRANSPOSE(field_scan[i]);
687 for (i = 0; i < 64; i++) {
688 #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
689 h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
690 h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
691 h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
692 h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
695 if (h->ps.sps->transform_bypass) { // FIXME same ugly
696 h->zigzag_scan_q0 = ff_zigzag_scan;
697 h->zigzag_scan8x8_q0 = ff_zigzag_direct;
698 h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
699 h->field_scan_q0 = field_scan;
700 h->field_scan8x8_q0 = field_scan8x8;
701 h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
703 h->zigzag_scan_q0 = h->zigzag_scan;
704 h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
705 h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
706 h->field_scan_q0 = h->field_scan;
707 h->field_scan8x8_q0 = h->field_scan8x8;
708 h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
712 static enum AVPixelFormat get_pixel_format(H264Context *h)
714 #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
715 CONFIG_H264_D3D11VA_HWACCEL + \
716 CONFIG_H264_VAAPI_HWACCEL + \
717 (CONFIG_H264_VDA_HWACCEL * 2) + \
718 CONFIG_H264_VDPAU_HWACCEL)
719 enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
720 const enum AVPixelFormat *choices = pix_fmts;
722 switch (h->ps.sps->bit_depth_luma) {
725 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
726 *fmt++ = AV_PIX_FMT_GBRP9;
728 *fmt++ = AV_PIX_FMT_YUV444P9;
729 } else if (CHROMA422(h))
730 *fmt++ = AV_PIX_FMT_YUV422P9;
732 *fmt++ = AV_PIX_FMT_YUV420P9;
736 if (h->avctx->colorspace == AVCOL_SPC_RGB) {
737 *fmt++ = AV_PIX_FMT_GBRP10;
739 *fmt++ = AV_PIX_FMT_YUV444P10;
740 } else if (CHROMA422(h))
741 *fmt++ = AV_PIX_FMT_YUV422P10;
743 *fmt++ = AV_PIX_FMT_YUV420P10;
746 #if CONFIG_H264_VDPAU_HWACCEL
747 *fmt++ = AV_PIX_FMT_VDPAU;
750 if (h->avctx->colorspace == AVCOL_SPC_RGB)
751 *fmt++ = AV_PIX_FMT_GBRP;
752 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
753 *fmt++ = AV_PIX_FMT_YUVJ444P;
755 *fmt++ = AV_PIX_FMT_YUV444P;
756 } else if (CHROMA422(h)) {
757 if (h->avctx->color_range == AVCOL_RANGE_JPEG)
758 *fmt++ = AV_PIX_FMT_YUVJ422P;
760 *fmt++ = AV_PIX_FMT_YUV422P;
762 #if CONFIG_H264_DXVA2_HWACCEL
763 *fmt++ = AV_PIX_FMT_DXVA2_VLD;
765 #if CONFIG_H264_D3D11VA_HWACCEL
766 *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
768 #if CONFIG_H264_VAAPI_HWACCEL
769 *fmt++ = AV_PIX_FMT_VAAPI;
771 #if CONFIG_H264_VDA_HWACCEL
772 *fmt++ = AV_PIX_FMT_VDA_VLD;
773 *fmt++ = AV_PIX_FMT_VDA;
775 if (h->avctx->codec->pix_fmts)
776 choices = h->avctx->codec->pix_fmts;
777 else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
778 *fmt++ = AV_PIX_FMT_YUVJ420P;
780 *fmt++ = AV_PIX_FMT_YUV420P;
784 av_log(h->avctx, AV_LOG_ERROR,
785 "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);
786 return AVERROR_INVALIDDATA;
789 *fmt = AV_PIX_FMT_NONE;
791 return ff_get_format(h->avctx, choices);
794 /* export coded and cropped frame dimensions to AVCodecContext */
795 static int init_dimensions(H264Context *h)
797 SPS *sps = h->ps.sps;
798 int width = h->width - (sps->crop_right + sps->crop_left);
799 int height = h->height - (sps->crop_top + sps->crop_bottom);
801 /* handle container cropping */
802 if (FFALIGN(h->avctx->width, 16) == FFALIGN(width, 16) &&
803 FFALIGN(h->avctx->height, 16) == FFALIGN(height, 16)) {
804 width = h->avctx->width;
805 height = h->avctx->height;
808 if (width <= 0 || height <= 0) {
809 av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
811 if (h->avctx->err_recognition & AV_EF_EXPLODE)
812 return AVERROR_INVALIDDATA;
814 av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
825 h->avctx->coded_width = h->width;
826 h->avctx->coded_height = h->height;
827 h->avctx->width = width;
828 h->avctx->height = height;
833 static int h264_slice_header_init(H264Context *h)
835 const SPS *sps = h->ps.sps;
838 ff_set_sar(h->avctx, sps->sar);
839 av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
840 &h->chroma_x_shift, &h->chroma_y_shift);
842 if (sps->timing_info_present_flag) {
843 int64_t den = sps->time_scale;
844 if (h->sei.unregistered.x264_build < 44U)
846 av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
847 sps->num_units_in_tick, den, 1 << 30);
850 ff_h264_free_tables(h);
853 h->prev_interlaced_frame = 1;
856 ret = ff_h264_alloc_tables(h);
858 av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
862 if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 10) {
863 av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
864 sps->bit_depth_luma);
865 return AVERROR_INVALIDDATA;
868 h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
869 h->pixel_shift = sps->bit_depth_luma > 8;
870 h->chroma_format_idc = sps->chroma_format_idc;
871 h->bit_depth_luma = sps->bit_depth_luma;
873 ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
874 sps->chroma_format_idc);
875 ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
876 ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
877 ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
878 sps->chroma_format_idc);
879 ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
881 if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
882 ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
884 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
888 for (i = 0; i < h->nb_slice_ctx; i++) {
889 H264SliceContext *sl = &h->slice_ctx[i];
892 sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
893 sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
894 sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
896 if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
897 av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
903 h->context_initialized = 1;
908 static int h264_init_ps(H264Context *h, const H264SliceContext *sl)
911 int needs_reinit = 0, ret;
913 h->ps.pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
914 if (h->ps.sps != (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data) {
915 h->ps.sps = (SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data;
917 if (h->bit_depth_luma != h->ps.sps->bit_depth_luma ||
918 h->chroma_format_idc != h->ps.sps->chroma_format_idc)
923 h->avctx->profile = ff_h264_get_profile(sps);
924 h->avctx->level = sps->level_idc;
925 h->avctx->refs = sps->ref_frame_count;
927 if (h->mb_width != sps->mb_width ||
928 h->mb_height != sps->mb_height * (2 - sps->frame_mbs_only_flag))
931 h->mb_width = sps->mb_width;
932 h->mb_height = sps->mb_height * (2 - sps->frame_mbs_only_flag);
933 h->mb_num = h->mb_width * h->mb_height;
934 h->mb_stride = h->mb_width + 1;
936 h->b_stride = h->mb_width * 4;
938 h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
940 h->width = 16 * h->mb_width;
941 h->height = 16 * h->mb_height;
943 ret = init_dimensions(h);
947 if (sps->video_signal_type_present_flag) {
948 h->avctx->color_range = sps->full_range ? AVCOL_RANGE_JPEG
950 if (sps->colour_description_present_flag) {
951 if (h->avctx->colorspace != sps->colorspace)
953 h->avctx->color_primaries = sps->color_primaries;
954 h->avctx->color_trc = sps->color_trc;
955 h->avctx->colorspace = sps->colorspace;
959 if (!h->context_initialized || needs_reinit) {
960 h->context_initialized = 0;
961 if (sl != h->slice_ctx) {
962 av_log(h->avctx, AV_LOG_ERROR,
963 "changing width %d -> %d / height %d -> %d on "
965 h->width, h->avctx->coded_width,
966 h->height, h->avctx->coded_height,
967 h->current_slice + 1);
968 return AVERROR_INVALIDDATA;
971 ff_h264_flush_change(h);
973 if ((ret = get_pixel_format(h)) < 0)
975 h->avctx->pix_fmt = ret;
977 av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
978 "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
980 if ((ret = h264_slice_header_init(h)) < 0) {
981 av_log(h->avctx, AV_LOG_ERROR,
982 "h264_slice_header_init() failed\n");
990 /* This function is called right after decoding the slice header for a first
991 * slice in a field (or a frame). It decides whether we are decoding a new frame
992 * or a second field in a pair and does the necessary setup.
994 static int h264_field_start(H264Context *h, const H264SliceContext *sl,
999 int last_pic_structure, last_pic_droppable, ret;
1001 ret = h264_init_ps(h, sl);
1007 last_pic_droppable = h->droppable;
1008 last_pic_structure = h->picture_structure;
1009 h->droppable = (nal->ref_idc == 0);
1010 h->picture_structure = sl->picture_structure;
1012 h->poc.frame_num = sl->frame_num;
1013 h->poc.poc_lsb = sl->poc_lsb;
1014 h->poc.delta_poc_bottom = sl->delta_poc_bottom;
1015 h->poc.delta_poc[0] = sl->delta_poc[0];
1016 h->poc.delta_poc[1] = sl->delta_poc[1];
1018 /* Shorten frame num gaps so we don't have to allocate reference
1019 * frames just to throw them away */
1020 if (h->poc.frame_num != h->poc.prev_frame_num) {
1021 int unwrap_prev_frame_num = h->poc.prev_frame_num;
1022 int max_frame_num = 1 << sps->log2_max_frame_num;
1024 if (unwrap_prev_frame_num > h->poc.frame_num)
1025 unwrap_prev_frame_num -= max_frame_num;
1027 if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
1028 unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
1029 if (unwrap_prev_frame_num < 0)
1030 unwrap_prev_frame_num += max_frame_num;
1032 h->poc.prev_frame_num = unwrap_prev_frame_num;
1036 /* See if we have a decoded first field looking for a pair...
1037 * Here, we're using that to see if we should mark previously
1038 * decode frames as "finished".
1039 * We have to do that before the "dummy" in-between frame allocation,
1040 * since that can modify s->current_picture_ptr. */
1041 if (h->first_field) {
1042 assert(h->cur_pic_ptr);
1043 assert(h->cur_pic_ptr->f->buf[0]);
1044 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1046 /* figure out if we have a complementary field pair */
1047 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1048 /* Previous field is unmatched. Don't display it, but let it
1049 * remain for reference if marked as such. */
1050 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1051 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1052 last_pic_structure == PICT_TOP_FIELD);
1055 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1056 /* This and previous field were reference, but had
1057 * different frame_nums. Consider this field first in
1058 * pair. Throw away previous field except for reference
1060 if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
1061 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1062 last_pic_structure == PICT_TOP_FIELD);
1065 /* Second field in complementary pair */
1066 if (!((last_pic_structure == PICT_TOP_FIELD &&
1067 h->picture_structure == PICT_BOTTOM_FIELD) ||
1068 (last_pic_structure == PICT_BOTTOM_FIELD &&
1069 h->picture_structure == PICT_TOP_FIELD))) {
1070 av_log(h->avctx, AV_LOG_ERROR,
1071 "Invalid field mode combination %d/%d\n",
1072 last_pic_structure, h->picture_structure);
1073 h->picture_structure = last_pic_structure;
1074 h->droppable = last_pic_droppable;
1075 return AVERROR_INVALIDDATA;
1076 } else if (last_pic_droppable != h->droppable) {
1077 avpriv_request_sample(h->avctx,
1078 "Found reference and non-reference fields in the same frame, which");
1079 h->picture_structure = last_pic_structure;
1080 h->droppable = last_pic_droppable;
1081 return AVERROR_PATCHWELCOME;
1087 while (h->poc.frame_num != h->poc.prev_frame_num &&
1088 h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
1089 H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1090 av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1091 h->poc.frame_num, h->poc.prev_frame_num);
1092 ret = initialize_cur_frame(h);
1098 h->poc.prev_frame_num++;
1099 h->poc.prev_frame_num %= 1 << sps->log2_max_frame_num;
1100 h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
1101 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1102 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1104 h->explicit_ref_marking = 0;
1105 ret = ff_h264_execute_ref_pic_marking(h);
1106 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1108 /* Error concealment: If a ref is missing, copy the previous ref
1110 * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1111 * many assumptions about there being no actual duplicates.
1112 * FIXME: This does not copy padding for out-of-frame motion
1113 * vectors. Given we are concealing a lost frame, this probably
1114 * is not noticeable by comparison, but it should be fixed. */
1115 if (h->short_ref_count) {
1117 h->short_ref[0]->f->width == prev->f->width &&
1118 h->short_ref[0]->f->height == prev->f->height &&
1119 h->short_ref[0]->f->format == prev->f->format) {
1120 av_image_copy(h->short_ref[0]->f->data,
1121 h->short_ref[0]->f->linesize,
1122 (const uint8_t **)prev->f->data,
1127 h->short_ref[0]->poc = prev->poc + 2;
1129 h->short_ref[0]->frame_num = h->poc.prev_frame_num;
1133 /* See if we have a decoded first field looking for a pair...
1134 * We're using that to see whether to continue decoding in that
1135 * frame, or to allocate a new one. */
1136 if (h->first_field) {
1137 assert(h->cur_pic_ptr);
1138 assert(h->cur_pic_ptr->f->buf[0]);
1139 assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1141 /* figure out if we have a complementary field pair */
1142 if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1143 /* Previous field is unmatched. Don't display it, but let it
1144 * remain for reference if marked as such. */
1145 h->cur_pic_ptr = NULL;
1146 h->first_field = FIELD_PICTURE(h);
1148 if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1149 /* This and the previous field had different frame_nums.
1150 * Consider this field first in pair. Throw away previous
1151 * one except for reference purposes. */
1153 h->cur_pic_ptr = NULL;
1155 /* Second field in complementary pair */
1160 /* Frame or first field in a potentially complementary pair */
1161 h->first_field = FIELD_PICTURE(h);
1164 if (!FIELD_PICTURE(h) || h->first_field) {
1165 if (h264_frame_start(h) < 0) {
1167 return AVERROR_INVALIDDATA;
1170 release_unused_pictures(h, 0);
1176 static int h264_slice_header_parse(H264Context *h, H264SliceContext *sl,
1177 const H2645NAL *nal)
1182 unsigned int slice_type, tmp, i;
1183 int field_pic_flag, bottom_field_flag;
1184 int droppable, picture_structure;
1186 sl->first_mb_addr = get_ue_golomb(&sl->gb);
1188 slice_type = get_ue_golomb_31(&sl->gb);
1189 if (slice_type > 9) {
1190 av_log(h->avctx, AV_LOG_ERROR,
1191 "slice type %d too large at %d\n",
1192 slice_type, sl->first_mb_addr);
1193 return AVERROR_INVALIDDATA;
1195 if (slice_type > 4) {
1197 sl->slice_type_fixed = 1;
1199 sl->slice_type_fixed = 0;
1201 slice_type = ff_h264_golomb_to_pict_type[slice_type];
1202 sl->slice_type = slice_type;
1203 sl->slice_type_nos = slice_type & 3;
1205 if (nal->type == NAL_IDR_SLICE &&
1206 sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1207 av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
1208 return AVERROR_INVALIDDATA;
1211 sl->pps_id = get_ue_golomb(&sl->gb);
1212 if (sl->pps_id >= MAX_PPS_COUNT) {
1213 av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
1214 return AVERROR_INVALIDDATA;
1216 if (!h->ps.pps_list[sl->pps_id]) {
1217 av_log(h->avctx, AV_LOG_ERROR,
1218 "non-existing PPS %u referenced\n",
1220 return AVERROR_INVALIDDATA;
1222 pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
1224 if (!h->ps.sps_list[pps->sps_id]) {
1225 av_log(h->avctx, AV_LOG_ERROR,
1226 "non-existing SPS %u referenced\n", pps->sps_id);
1227 return AVERROR_INVALIDDATA;
1229 sps = (const SPS*)h->ps.sps_list[pps->sps_id]->data;
1231 sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
1235 droppable = nal->ref_idc == 0;
1236 if (sps->frame_mbs_only_flag) {
1237 picture_structure = PICT_FRAME;
1239 field_pic_flag = get_bits1(&sl->gb);
1240 if (field_pic_flag) {
1241 bottom_field_flag = get_bits1(&sl->gb);
1242 picture_structure = PICT_TOP_FIELD + bottom_field_flag;
1244 picture_structure = PICT_FRAME;
1247 sl->picture_structure = picture_structure;
1248 sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
1250 if (picture_structure == PICT_FRAME) {
1251 h->curr_pic_num = sl->frame_num;
1252 h->max_pic_num = 1 << sps->log2_max_frame_num;
1254 h->curr_pic_num = 2 * sl->frame_num + 1;
1255 h->max_pic_num = 1 << (sps->log2_max_frame_num + 1);
1258 if (nal->type == NAL_IDR_SLICE)
1259 get_ue_golomb(&sl->gb); /* idr_pic_id */
1261 if (sps->poc_type == 0) {
1262 sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
1264 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1265 sl->delta_poc_bottom = get_se_golomb(&sl->gb);
1268 if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
1269 sl->delta_poc[0] = get_se_golomb(&sl->gb);
1271 if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1272 sl->delta_poc[1] = get_se_golomb(&sl->gb);
1275 if (pps->redundant_pic_cnt_present)
1276 sl->redundant_pic_count = get_ue_golomb(&sl->gb);
1278 if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1279 sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1281 ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
1282 &sl->gb, pps, sl->slice_type_nos,
1287 if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1288 ret = ff_h264_decode_ref_pic_list_reordering(h, sl);
1290 sl->ref_count[1] = sl->ref_count[0] = 0;
1295 sl->pwt.use_weight = 0;
1296 for (i = 0; i < 2; i++) {
1297 sl->pwt.luma_weight_flag[i] = 0;
1298 sl->pwt.chroma_weight_flag[i] = 0;
1300 if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
1301 (pps->weighted_bipred_idc == 1 &&
1302 sl->slice_type_nos == AV_PICTURE_TYPE_B))
1303 ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
1304 sl->slice_type_nos, &sl->pwt);
1306 sl->explicit_ref_marking = 0;
1308 ret = ff_h264_decode_ref_pic_marking(h, sl, &sl->gb);
1309 if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1310 return AVERROR_INVALIDDATA;
1313 if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1314 tmp = get_ue_golomb_31(&sl->gb);
1316 av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1317 return AVERROR_INVALIDDATA;
1319 sl->cabac_init_idc = tmp;
1322 sl->last_qscale_diff = 0;
1323 tmp = pps->init_qp + get_se_golomb(&sl->gb);
1324 if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
1325 av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1326 return AVERROR_INVALIDDATA;
1329 sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
1330 sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
1331 // FIXME qscale / qp ... stuff
1332 if (sl->slice_type == AV_PICTURE_TYPE_SP)
1333 get_bits1(&sl->gb); /* sp_for_switch_flag */
1334 if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1335 sl->slice_type == AV_PICTURE_TYPE_SI)
1336 get_se_golomb(&sl->gb); /* slice_qs_delta */
1338 sl->deblocking_filter = 1;
1339 sl->slice_alpha_c0_offset = 0;
1340 sl->slice_beta_offset = 0;
1341 if (pps->deblocking_filter_parameters_present) {
1342 tmp = get_ue_golomb_31(&sl->gb);
1344 av_log(h->avctx, AV_LOG_ERROR,
1345 "deblocking_filter_idc %u out of range\n", tmp);
1346 return AVERROR_INVALIDDATA;
1348 sl->deblocking_filter = tmp;
1349 if (sl->deblocking_filter < 2)
1350 sl->deblocking_filter ^= 1; // 1<->0
1352 if (sl->deblocking_filter) {
1353 sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;
1354 sl->slice_beta_offset = get_se_golomb(&sl->gb) * 2;
1355 if (sl->slice_alpha_c0_offset > 12 ||
1356 sl->slice_alpha_c0_offset < -12 ||
1357 sl->slice_beta_offset > 12 ||
1358 sl->slice_beta_offset < -12) {
1359 av_log(h->avctx, AV_LOG_ERROR,
1360 "deblocking filter parameters %d %d out of range\n",
1361 sl->slice_alpha_c0_offset, sl->slice_beta_offset);
1362 return AVERROR_INVALIDDATA;
1371 * Decode a slice header.
1372 * This will (re)initialize the decoder and call h264_frame_start() as needed.
1374 * @param h h264context
1376 * @return 0 if okay, <0 if an error occurred
1378 int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl,
1379 const H2645NAL *nal)
1383 ret = h264_slice_header_parse(h, sl, nal);
1387 if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
1388 if (h->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
1389 ff_h264_field_end(h, sl, 1);
1392 h->current_slice = 0;
1393 if (!h->first_field) {
1394 if (h->cur_pic_ptr && !h->droppable) {
1395 ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1396 h->picture_structure == PICT_BOTTOM_FIELD);
1398 h->cur_pic_ptr = NULL;
1402 if (h->current_slice == 0) {
1403 ret = h264_field_start(h, sl, nal);
1407 if (h->ps.pps != (const PPS*)h->ps.pps_list[sl->pps_id]->data) {
1408 av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
1409 return AVERROR_INVALIDDATA;
1412 if (h->picture_structure != sl->picture_structure ||
1413 h->droppable != (nal->ref_idc == 0)) {
1414 av_log(h->avctx, AV_LOG_ERROR,
1415 "Changing field mode (%d -> %d) between slices is not allowed\n",
1416 h->picture_structure, sl->picture_structure);
1417 return AVERROR_INVALIDDATA;
1418 } else if (!h->cur_pic_ptr) {
1419 av_log(h->avctx, AV_LOG_ERROR,
1420 "unset cur_pic_ptr on slice %d\n",
1421 h->current_slice + 1);
1422 return AVERROR_INVALIDDATA;
1426 assert(h->mb_num == h->mb_width * h->mb_height);
1427 if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1428 sl->first_mb_addr >= h->mb_num) {
1429 av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1430 return AVERROR_INVALIDDATA;
1432 sl->resync_mb_x = sl->mb_x = sl->first_mb_addr % h->mb_width;
1433 sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
1434 FIELD_OR_MBAFF_PICTURE(h);
1435 if (h->picture_structure == PICT_BOTTOM_FIELD)
1436 sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
1437 assert(sl->mb_y < h->mb_height);
1439 if (!h->setup_finished) {
1440 ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
1441 h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
1443 memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
1444 h->nb_mmco = sl->nb_mmco;
1445 h->explicit_ref_marking = sl->explicit_ref_marking;
1448 ret = ff_h264_build_ref_list(h, sl);
1452 if (h->ps.pps->weighted_bipred_idc == 2 &&
1453 sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1454 implicit_weight_table(h, sl, -1);
1455 if (FRAME_MBAFF(h)) {
1456 implicit_weight_table(h, sl, 0);
1457 implicit_weight_table(h, sl, 1);
1461 if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
1462 ff_h264_direct_dist_scale_factor(h, sl);
1463 ff_h264_direct_ref_list_init(h, sl);
1465 if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1466 (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
1467 sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
1468 (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
1469 sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
1470 (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1472 sl->deblocking_filter = 0;
1474 if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
1475 if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
1476 /* Cheat slightly for speed:
1477 * Do not bother to deblock across slices. */
1478 sl->deblocking_filter = 2;
1480 h->postpone_filter = 1;
1483 sl->qp_thresh = 15 -
1484 FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
1486 h->ps.pps->chroma_qp_index_offset[0],
1487 h->ps.pps->chroma_qp_index_offset[1]) +
1488 6 * (h->ps.sps->bit_depth_luma - 8);
1490 sl->slice_num = ++h->current_slice;
1491 if (sl->slice_num >= MAX_SLICES) {
1492 av_log(h->avctx, AV_LOG_ERROR,
1493 "Too many slices, increase MAX_SLICES and recompile\n");
1496 for (j = 0; j < 2; j++) {
1498 int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
1499 for (i = 0; i < 16; i++) {
1501 if (j < sl->list_count && i < sl->ref_count[j] &&
1502 sl->ref_list[j][i].parent->f->buf[0]) {
1504 AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
1505 for (k = 0; k < h->short_ref_count; k++)
1506 if (h->short_ref[k]->f->buf[0]->buffer == buf) {
1510 for (k = 0; k < h->long_ref_count; k++)
1511 if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
1512 id_list[i] = h->short_ref_count + k;
1520 for (i = 0; i < 16; i++)
1521 ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
1523 ref2frm[18 + 1] = -1;
1524 for (i = 16; i < 48; i++)
1525 ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
1526 (sl->ref_list[j][i].reference & 3);
1529 if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
1530 av_log(h->avctx, AV_LOG_DEBUG,
1531 "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",
1533 (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
1534 sl->mb_y * h->mb_width + sl->mb_x,
1535 av_get_picture_type_char(sl->slice_type),
1536 sl->slice_type_fixed ? " fix" : "",
1537 nal->type == NAL_IDR_SLICE ? " IDR" : "",
1539 h->cur_pic_ptr->field_poc[0],
1540 h->cur_pic_ptr->field_poc[1],
1541 sl->ref_count[0], sl->ref_count[1],
1543 sl->deblocking_filter,
1544 sl->slice_alpha_c0_offset, sl->slice_beta_offset,
1546 sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
1547 sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
1553 int ff_h264_get_slice_type(const H264SliceContext *sl)
1555 switch (sl->slice_type) {
1556 case AV_PICTURE_TYPE_P:
1558 case AV_PICTURE_TYPE_B:
1560 case AV_PICTURE_TYPE_I:
1562 case AV_PICTURE_TYPE_SP:
1564 case AV_PICTURE_TYPE_SI:
1567 return AVERROR_INVALIDDATA;
1571 static av_always_inline void fill_filter_caches_inter(const H264Context *h,
1572 H264SliceContext *sl,
1573 int mb_type, int top_xy,
1574 int left_xy[LEFT_MBS],
1576 int left_type[LEFT_MBS],
1577 int mb_xy, int list)
1579 int b_stride = h->b_stride;
1580 int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
1581 int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
1582 if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
1583 if (USES_LIST(top_type, list)) {
1584 const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
1585 const int b8_xy = 4 * top_xy + 2;
1586 int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
1587 AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
1588 ref_cache[0 - 1 * 8] =
1589 ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
1590 ref_cache[2 - 1 * 8] =
1591 ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
1593 AV_ZERO128(mv_dst - 1 * 8);
1594 AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1597 if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
1598 if (USES_LIST(left_type[LTOP], list)) {
1599 const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
1600 const int b8_xy = 4 * left_xy[LTOP] + 1;
1601 int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
1602 AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
1603 AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
1604 AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
1605 AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
1607 ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
1608 ref_cache[-1 + 16] =
1609 ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
1611 AV_ZERO32(mv_dst - 1 + 0);
1612 AV_ZERO32(mv_dst - 1 + 8);
1613 AV_ZERO32(mv_dst - 1 + 16);
1614 AV_ZERO32(mv_dst - 1 + 24);
1617 ref_cache[-1 + 16] =
1618 ref_cache[-1 + 24] = LIST_NOT_USED;
1623 if (!USES_LIST(mb_type, list)) {
1624 fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
1625 AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1626 AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1627 AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1628 AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
1633 int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
1634 int (*ref2frm)[64] = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);
1635 uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
1636 uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
1637 AV_WN32A(&ref_cache[0 * 8], ref01);
1638 AV_WN32A(&ref_cache[1 * 8], ref01);
1639 AV_WN32A(&ref_cache[2 * 8], ref23);
1640 AV_WN32A(&ref_cache[3 * 8], ref23);
1644 int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
1645 AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
1646 AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
1647 AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
1648 AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
1653 * @return non zero if the loop filter can be skipped
1655 static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
1657 const int mb_xy = sl->mb_xy;
1658 int top_xy, left_xy[LEFT_MBS];
1659 int top_type, left_type[LEFT_MBS];
1663 top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
1665 left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
1666 if (FRAME_MBAFF(h)) {
1667 const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
1668 const int curr_mb_field_flag = IS_INTERLACED(mb_type);
1670 if (left_mb_field_flag != curr_mb_field_flag)
1671 left_xy[LTOP] -= h->mb_stride;
1673 if (curr_mb_field_flag)
1674 top_xy += h->mb_stride &
1675 (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
1676 if (left_mb_field_flag != curr_mb_field_flag)
1677 left_xy[LBOT] += h->mb_stride;
1681 sl->top_mb_xy = top_xy;
1682 sl->left_mb_xy[LTOP] = left_xy[LTOP];
1683 sl->left_mb_xy[LBOT] = left_xy[LBOT];
1685 /* For sufficiently low qp, filtering wouldn't do anything.
1686 * This is a conservative estimate: could also check beta_offset
1687 * and more accurate chroma_qp. */
1688 int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
1689 int qp = h->cur_pic.qscale_table[mb_xy];
1690 if (qp <= qp_thresh &&
1691 (left_xy[LTOP] < 0 ||
1692 ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
1694 ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
1695 if (!FRAME_MBAFF(h))
1697 if ((left_xy[LTOP] < 0 ||
1698 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
1699 (top_xy < h->mb_stride ||
1700 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
1705 top_type = h->cur_pic.mb_type[top_xy];
1706 left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
1707 left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
1708 if (sl->deblocking_filter == 2) {
1709 if (h->slice_table[top_xy] != sl->slice_num)
1711 if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
1712 left_type[LTOP] = left_type[LBOT] = 0;
1714 if (h->slice_table[top_xy] == 0xFFFF)
1716 if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
1717 left_type[LTOP] = left_type[LBOT] = 0;
1719 sl->top_type = top_type;
1720 sl->left_type[LTOP] = left_type[LTOP];
1721 sl->left_type[LBOT] = left_type[LBOT];
1723 if (IS_INTRA(mb_type))
1726 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
1727 top_type, left_type, mb_xy, 0);
1728 if (sl->list_count == 2)
1729 fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
1730 top_type, left_type, mb_xy, 1);
1732 nnz = h->non_zero_count[mb_xy];
1733 nnz_cache = sl->non_zero_count_cache;
1734 AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
1735 AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
1736 AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
1737 AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
1738 sl->cbp = h->cbp_table[mb_xy];
1741 nnz = h->non_zero_count[top_xy];
1742 AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
1745 if (left_type[LTOP]) {
1746 nnz = h->non_zero_count[left_xy[LTOP]];
1747 nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
1748 nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
1749 nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
1750 nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
1753 /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
1754 * from what the loop filter needs */
1755 if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
1756 if (IS_8x8DCT(top_type)) {
1757 nnz_cache[4 + 8 * 0] =
1758 nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
1759 nnz_cache[6 + 8 * 0] =
1760 nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
1762 if (IS_8x8DCT(left_type[LTOP])) {
1763 nnz_cache[3 + 8 * 1] =
1764 nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
1766 if (IS_8x8DCT(left_type[LBOT])) {
1767 nnz_cache[3 + 8 * 3] =
1768 nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
1771 if (IS_8x8DCT(mb_type)) {
1772 nnz_cache[scan8[0]] =
1773 nnz_cache[scan8[1]] =
1774 nnz_cache[scan8[2]] =
1775 nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
1777 nnz_cache[scan8[0 + 4]] =
1778 nnz_cache[scan8[1 + 4]] =
1779 nnz_cache[scan8[2 + 4]] =
1780 nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
1782 nnz_cache[scan8[0 + 8]] =
1783 nnz_cache[scan8[1 + 8]] =
1784 nnz_cache[scan8[2 + 8]] =
1785 nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
1787 nnz_cache[scan8[0 + 12]] =
1788 nnz_cache[scan8[1 + 12]] =
1789 nnz_cache[scan8[2 + 12]] =
1790 nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
1797 static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
1799 uint8_t *dest_y, *dest_cb, *dest_cr;
1800 int linesize, uvlinesize, mb_x, mb_y;
1801 const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
1802 const int old_slice_type = sl->slice_type;
1803 const int pixel_shift = h->pixel_shift;
1804 const int block_h = 16 >> h->chroma_y_shift;
1806 if (h->postpone_filter)
1809 if (sl->deblocking_filter) {
1810 for (mb_x = start_x; mb_x < end_x; mb_x++)
1811 for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
1813 mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
1814 mb_type = h->cur_pic.mb_type[mb_xy];
1818 sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
1822 dest_y = h->cur_pic.f->data[0] +
1823 ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
1824 dest_cb = h->cur_pic.f->data[1] +
1825 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
1826 mb_y * sl->uvlinesize * block_h;
1827 dest_cr = h->cur_pic.f->data[2] +
1828 (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
1829 mb_y * sl->uvlinesize * block_h;
1830 // FIXME simplify above
1833 linesize = sl->mb_linesize = sl->linesize * 2;
1834 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
1835 if (mb_y & 1) { // FIXME move out of this function?
1836 dest_y -= sl->linesize * 15;
1837 dest_cb -= sl->uvlinesize * (block_h - 1);
1838 dest_cr -= sl->uvlinesize * (block_h - 1);
1841 linesize = sl->mb_linesize = sl->linesize;
1842 uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
1844 backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
1846 if (fill_filter_caches(h, sl, mb_type))
1848 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
1849 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
1851 if (FRAME_MBAFF(h)) {
1852 ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
1853 linesize, uvlinesize);
1855 ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
1856 dest_cr, linesize, uvlinesize);
1860 sl->slice_type = old_slice_type;
1862 sl->mb_y = end_mb_y - FRAME_MBAFF(h);
1863 sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
1864 sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
1867 static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
1869 const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
1870 int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
1871 h->cur_pic.mb_type[mb_xy - 1] :
1872 (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
1873 h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
1874 sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
1878 * Draw edges and report progress for the last MB row.
1880 static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
1882 int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
1883 int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
1884 int height = 16 << FRAME_MBAFF(h);
1885 int deblock_border = (16 + 4) << FRAME_MBAFF(h);
1887 if (sl->deblocking_filter) {
1888 if ((top + height) >= pic_height)
1889 height += deblock_border;
1890 top -= deblock_border;
1893 if (top >= pic_height || (top + height) < 0)
1896 height = FFMIN(height, pic_height - top);
1898 height = top + height;
1902 ff_h264_draw_horiz_band(h, sl, top, height);
1907 ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
1908 h->picture_structure == PICT_BOTTOM_FIELD);
1911 static void er_add_slice(H264SliceContext *sl,
1912 int startx, int starty,
1913 int endx, int endy, int status)
1915 #if CONFIG_ERROR_RESILIENCE
1916 ERContext *er = &sl->er;
1918 if (!sl->h264->enable_er)
1921 er->ref_count = sl->ref_count[0];
1922 ff_er_add_slice(er, startx, starty, endx, endy, status);
1926 static int decode_slice(struct AVCodecContext *avctx, void *arg)
1928 H264SliceContext *sl = arg;
1929 const H264Context *h = sl->h264;
1930 int lf_x_start = sl->mb_x;
1931 int orig_deblock = sl->deblocking_filter;
1934 sl->linesize = h->cur_pic_ptr->f->linesize[0];
1935 sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
1937 ret = alloc_scratch_buffers(sl, sl->linesize);
1941 sl->mb_skip_run = -1;
1943 if (h->postpone_filter)
1944 sl->deblocking_filter = 0;
1946 sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
1947 avctx->codec_id != AV_CODEC_ID_H264 ||
1948 (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
1950 if (h->ps.pps->cabac) {
1952 align_get_bits(&sl->gb);
1955 ff_init_cabac_decoder(&sl->cabac,
1956 sl->gb.buffer + get_bits_count(&sl->gb) / 8,
1957 (get_bits_left(&sl->gb) + 7) / 8);
1959 ff_h264_init_cabac_states(h, sl);
1965 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
1966 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
1967 sl->next_slice_idx);
1968 return AVERROR_INVALIDDATA;
1971 ret = ff_h264_decode_mb_cabac(h, sl);
1972 // STOP_TIMER("decode_mb_cabac")
1975 ff_h264_hl_decode_mb(h, sl);
1977 // FIXME optimal? or let mb_decode decode 16x32 ?
1978 if (ret >= 0 && FRAME_MBAFF(h)) {
1981 ret = ff_h264_decode_mb_cabac(h, sl);
1984 ff_h264_hl_decode_mb(h, sl);
1987 eos = get_cabac_terminate(&sl->cabac);
1989 if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
1990 sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
1991 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
1992 sl->mb_y, ER_MB_END);
1993 if (sl->mb_x >= lf_x_start)
1994 loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
1997 if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
1998 av_log(h->avctx, AV_LOG_ERROR,
1999 "error while decoding MB %d %d, bytestream %td\n",
2001 sl->cabac.bytestream_end - sl->cabac.bytestream);
2002 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2003 sl->mb_y, ER_MB_ERROR);
2004 return AVERROR_INVALIDDATA;
2007 if (++sl->mb_x >= h->mb_width) {
2008 loop_filter(h, sl, lf_x_start, sl->mb_x);
2009 sl->mb_x = lf_x_start = 0;
2010 decode_finish_row(h, sl);
2012 if (FIELD_OR_MBAFF_PICTURE(h)) {
2014 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2015 predict_field_decoding_flag(h, sl);
2019 if (eos || sl->mb_y >= h->mb_height) {
2020 ff_tlog(h->avctx, "slice end %d %d\n",
2021 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2022 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2023 sl->mb_y, ER_MB_END);
2024 if (sl->mb_x > lf_x_start)
2025 loop_filter(h, sl, lf_x_start, sl->mb_x);
2033 if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2034 av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2035 sl->next_slice_idx);
2036 return AVERROR_INVALIDDATA;
2039 ret = ff_h264_decode_mb_cavlc(h, sl);
2042 ff_h264_hl_decode_mb(h, sl);
2044 // FIXME optimal? or let mb_decode decode 16x32 ?
2045 if (ret >= 0 && FRAME_MBAFF(h)) {
2047 ret = ff_h264_decode_mb_cavlc(h, sl);
2050 ff_h264_hl_decode_mb(h, sl);
2055 av_log(h->avctx, AV_LOG_ERROR,
2056 "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
2057 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2058 sl->mb_y, ER_MB_ERROR);
2062 if (++sl->mb_x >= h->mb_width) {
2063 loop_filter(h, sl, lf_x_start, sl->mb_x);
2064 sl->mb_x = lf_x_start = 0;
2065 decode_finish_row(h, sl);
2067 if (FIELD_OR_MBAFF_PICTURE(h)) {
2069 if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2070 predict_field_decoding_flag(h, sl);
2072 if (sl->mb_y >= h->mb_height) {
2073 ff_tlog(h->avctx, "slice end %d %d\n",
2074 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2076 if (get_bits_left(&sl->gb) == 0) {
2077 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2078 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2082 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2083 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2085 return AVERROR_INVALIDDATA;
2090 if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
2091 ff_tlog(h->avctx, "slice end %d %d\n",
2092 get_bits_count(&sl->gb), sl->gb.size_in_bits);
2094 if (get_bits_left(&sl->gb) == 0) {
2095 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2096 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2097 if (sl->mb_x > lf_x_start)
2098 loop_filter(h, sl, lf_x_start, sl->mb_x);
2102 er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2103 sl->mb_y, ER_MB_ERROR);
2105 return AVERROR_INVALIDDATA;
2112 sl->deblocking_filter = orig_deblock;
2117 * Call decode_slice() for each context.
2119 * @param h h264 master context
2120 * @param context_count number of contexts to execute
2122 int ff_h264_execute_decode_slices(H264Context *h, unsigned context_count)
2124 AVCodecContext *const avctx = h->avctx;
2125 H264SliceContext *sl;
2128 if (h->avctx->hwaccel)
2130 if (context_count == 1) {
2133 h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2134 h->postpone_filter = 0;
2136 ret = decode_slice(avctx, &h->slice_ctx[0]);
2137 h->mb_y = h->slice_ctx[0].mb_y;
2140 for (i = 0; i < context_count; i++) {
2141 int next_slice_idx = h->mb_width * h->mb_height;
2144 sl = &h->slice_ctx[i];
2145 sl->er.error_count = 0;
2147 /* make sure none of those slices overlap */
2148 slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2149 for (j = 0; j < context_count; j++) {
2150 H264SliceContext *sl2 = &h->slice_ctx[j];
2151 int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2153 if (i == j || slice_idx2 < slice_idx)
2155 next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2157 sl->next_slice_idx = next_slice_idx;
2160 avctx->execute(avctx, decode_slice, h->slice_ctx,
2161 NULL, context_count, sizeof(h->slice_ctx[0]));
2163 /* pull back stuff from slices to master context */
2164 sl = &h->slice_ctx[context_count - 1];
2166 for (i = 1; i < context_count; i++)
2167 h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
2169 if (h->postpone_filter) {
2170 h->postpone_filter = 0;
2172 for (i = 0; i < context_count; i++) {
2175 sl = &h->slice_ctx[i];
2176 y_end = FFMIN(sl->mb_y + 1, h->mb_height);
2177 x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
2179 for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
2181 loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
2182 j == y_end - 1 ? x_end : h->mb_width);