Coverage Report

Created: 2026-07-25 07:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ffmpeg/libavcodec/h264_slice.c
Line
Count
Source
1
/*
2
 * H.26L/H.264/AVC/JVT/14496-10/... decoder
3
 * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg 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.
11
 *
12
 * FFmpeg 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.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21
22
/**
23
 * @file
24
 * H.264 / AVC / MPEG-4 part10 codec.
25
 * @author Michael Niedermayer <michaelni@gmx.at>
26
 */
27
28
#include "config_components.h"
29
30
#include "libavutil/avassert.h"
31
#include "libavutil/mem.h"
32
#include "libavutil/pixdesc.h"
33
#include "libavutil/timecode.h"
34
#include "decode.h"
35
#include "cabac.h"
36
#include "cabac_functions.h"
37
#include "error_resilience.h"
38
#include "avcodec.h"
39
#include "h264.h"
40
#include "h264dec.h"
41
#include "h264data.h"
42
#include "h264chroma.h"
43
#include "h264_ps.h"
44
#include "golomb.h"
45
#include "mathops.h"
46
#include "mpegutils.h"
47
#include "rectangle.h"
48
#include "libavutil/refstruct.h"
49
#include "thread.h"
50
#include "threadframe.h"
51
52
static const uint8_t field_scan[16+1] = {
53
    0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
54
    0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
55
    2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
56
    3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
57
};
58
59
static const uint8_t field_scan8x8[64+1] = {
60
    0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
61
    1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
62
    2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
63
    0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
64
    2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
65
    2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
66
    2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
67
    3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
68
    3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
69
    4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
70
    4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
71
    5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
72
    5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
73
    7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
74
    6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
75
    7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
76
};
77
78
static const uint8_t field_scan8x8_cavlc[64+1] = {
79
    0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
80
    2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
81
    3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
82
    5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
83
    0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
84
    1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
85
    3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
86
    5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
87
    0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
88
    1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
89
    3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
90
    5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
91
    1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
92
    1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
93
    3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
94
    6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
95
};
96
97
// zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
98
static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
99
    0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
100
    4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
101
    3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
102
    2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
103
    1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
104
    3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
105
    2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
106
    3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
107
    0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
108
    2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
109
    1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
110
    4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
111
    0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
112
    1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
113
    0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
114
    5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
115
};
116
117
static void release_unused_pictures(H264Context *h, int remove_current)
118
4.04M
{
119
4.04M
    int i;
120
121
    /* release non reference frames */
122
149M
    for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
123
145M
        if (h->DPB[i].f->buf[0] && !h->DPB[i].reference &&
124
2.60M
            (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
125
2.60M
            ff_h264_unref_picture(&h->DPB[i]);
126
2.60M
        }
127
145M
    }
128
4.04M
}
129
130
static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
131
2.37M
{
132
2.37M
    const H264Context *h = sl->h264;
133
2.37M
    int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
134
135
2.37M
    av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
136
    // edge emu needs blocksize + filter length - 1
137
    // (= 21x21 for  H.264)
138
2.37M
    av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
139
140
2.37M
    av_fast_mallocz(&sl->top_borders[0], &sl->top_borders_allocated[0],
141
2.37M
                   h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
142
2.37M
    av_fast_mallocz(&sl->top_borders[1], &sl->top_borders_allocated[1],
143
2.37M
                   h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
144
145
2.37M
    if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
146
2.37M
        !sl->top_borders[0]    || !sl->top_borders[1]) {
147
0
        av_freep(&sl->bipred_scratchpad);
148
0
        av_freep(&sl->edge_emu_buffer);
149
0
        av_freep(&sl->top_borders[0]);
150
0
        av_freep(&sl->top_borders[1]);
151
152
0
        sl->bipred_scratchpad_allocated = 0;
153
0
        sl->edge_emu_buffer_allocated   = 0;
154
0
        sl->top_borders_allocated[0]    = 0;
155
0
        sl->top_borders_allocated[1]    = 0;
156
0
        return AVERROR(ENOMEM);
157
0
    }
158
159
2.37M
    return 0;
160
2.37M
}
161
162
static int init_table_pools(H264Context *h)
163
505k
{
164
505k
    const int big_mb_num    = h->mb_stride * (h->mb_height + 1) + 1;
165
505k
    const int mb_array_size = h->mb_stride * h->mb_height;
166
505k
    const int b4_stride     = h->mb_width * 4 + 1;
167
505k
    const int b4_array_size = b4_stride * h->mb_height * 4;
168
169
505k
    h->qscale_table_pool = av_refstruct_pool_alloc(big_mb_num + h->mb_stride, 0);
170
505k
    h->mb_type_pool      = av_refstruct_pool_alloc((big_mb_num + h->mb_stride) *
171
505k
                                                   sizeof(uint32_t), 0);
172
505k
    h->motion_val_pool   = av_refstruct_pool_alloc(2 * (b4_array_size + 4) *
173
505k
                                                   sizeof(int16_t), 0);
174
505k
    h->ref_index_pool    = av_refstruct_pool_alloc(4 * mb_array_size, 0);
175
176
505k
    if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
177
505k
        !h->ref_index_pool) {
178
0
        av_refstruct_pool_uninit(&h->qscale_table_pool);
179
0
        av_refstruct_pool_uninit(&h->mb_type_pool);
180
0
        av_refstruct_pool_uninit(&h->motion_val_pool);
181
0
        av_refstruct_pool_uninit(&h->ref_index_pool);
182
0
        return AVERROR(ENOMEM);
183
0
    }
184
185
505k
    return 0;
186
505k
}
187
188
static int alloc_picture(H264Context *h, H264Picture *pic)
189
4.04M
{
190
4.04M
    int i, ret = 0;
191
192
4.04M
    av_assert0(!pic->f->data[0]);
193
194
4.04M
    if (h->sei.common.itut_t35.lcevc) {
195
0
        ret = ff_frame_new_side_data_from_buf(h->avctx, pic->f, AV_FRAME_DATA_LCEVC, &h->sei.common.itut_t35.lcevc);
196
0
        if (ret < 0)
197
0
            return ret;
198
0
    }
199
200
4.04M
    pic->tf.f = pic->f;
201
4.04M
    ret = ff_thread_get_ext_buffer(h->avctx, &pic->tf,
202
4.04M
                                   pic->reference ? AV_GET_BUFFER_FLAG_REF : 0);
203
4.04M
    if (ret < 0)
204
6.39k
        goto fail;
205
206
4.03M
    if (pic->needs_fg) {
207
16.9k
        pic->f_grain->format = pic->f->format;
208
16.9k
        pic->f_grain->width = pic->f->width;
209
16.9k
        pic->f_grain->height = pic->f->height;
210
16.9k
        ret = ff_thread_get_buffer(h->avctx, pic->f_grain, 0);
211
16.9k
        if (ret < 0)
212
0
            goto fail;
213
16.9k
    }
214
215
4.03M
    ret = ff_hwaccel_frame_priv_alloc(h->avctx, &pic->hwaccel_picture_private);
216
4.03M
    if (ret < 0)
217
0
        goto fail;
218
219
4.03M
    if (h->decode_error_flags_pool) {
220
0
        pic->decode_error_flags = av_refstruct_pool_get(h->decode_error_flags_pool);
221
0
        if (!pic->decode_error_flags)
222
0
            goto fail;
223
0
        atomic_init(pic->decode_error_flags, 0);
224
0
    }
225
226
4.03M
    if (CONFIG_GRAY && !h->avctx->hwaccel && h->flags & AV_CODEC_FLAG_GRAY && pic->f->data[2]) {
227
0
        int h_chroma_shift, v_chroma_shift;
228
0
        av_pix_fmt_get_chroma_sub_sample(pic->f->format,
229
0
                                         &h_chroma_shift, &v_chroma_shift);
230
231
0
        for(i=0; i<AV_CEIL_RSHIFT(pic->f->height, v_chroma_shift); i++) {
232
0
            memset(pic->f->data[1] + pic->f->linesize[1]*i,
233
0
                   0x80, AV_CEIL_RSHIFT(pic->f->width, h_chroma_shift));
234
0
            memset(pic->f->data[2] + pic->f->linesize[2]*i,
235
0
                   0x80, AV_CEIL_RSHIFT(pic->f->width, h_chroma_shift));
236
0
        }
237
0
    }
238
239
4.03M
    if (!h->qscale_table_pool) {
240
505k
        ret = init_table_pools(h);
241
505k
        if (ret < 0)
242
0
            goto fail;
243
505k
    }
244
245
4.03M
    pic->qscale_table_base = av_refstruct_pool_get(h->qscale_table_pool);
246
4.03M
    pic->mb_type_base      = av_refstruct_pool_get(h->mb_type_pool);
247
4.03M
    if (!pic->qscale_table_base || !pic->mb_type_base)
248
0
        goto fail;
249
250
4.03M
    pic->mb_type      = pic->mb_type_base + 2 * h->mb_stride + 1;
251
4.03M
    pic->qscale_table = pic->qscale_table_base + 2 * h->mb_stride + 1;
252
253
12.1M
    for (i = 0; i < 2; i++) {
254
8.06M
        pic->motion_val_base[i] = av_refstruct_pool_get(h->motion_val_pool);
255
8.06M
        pic->ref_index[i]       = av_refstruct_pool_get(h->ref_index_pool);
256
8.06M
        if (!pic->motion_val_base[i] || !pic->ref_index[i])
257
0
            goto fail;
258
259
8.06M
        pic->motion_val[i] = pic->motion_val_base[i] + 4;
260
8.06M
    }
261
262
4.03M
    pic->pps = av_refstruct_ref_c(h->ps.pps);
263
264
4.03M
    pic->mb_width  = h->mb_width;
265
4.03M
    pic->mb_height = h->mb_height;
266
4.03M
    pic->mb_stride = h->mb_stride;
267
268
4.03M
    return 0;
269
6.39k
fail:
270
6.39k
    ff_h264_unref_picture(pic);
271
6.39k
    return (ret < 0) ? ret : AVERROR(ENOMEM);
272
4.03M
}
273
274
static int find_unused_picture(const H264Context *h)
275
4.04M
{
276
4.04M
    int i;
277
278
13.7M
    for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
279
13.7M
        if (!h->DPB[i].f->buf[0])
280
4.04M
            return i;
281
13.7M
    }
282
0
    return AVERROR_INVALIDDATA;
283
4.04M
}
284
285
286
#define IN_RANGE(a, b, size) (((void*)(a) >= (void*)(b)) && ((void*)(a) < (void*)((b) + (size))))
287
288
#define REBASE_PICTURE(pic, new_ctx, old_ctx)             \
289
0
    (((pic) && (pic) >= (old_ctx)->DPB &&                       \
290
0
      (pic) < (old_ctx)->DPB + H264_MAX_PICTURE_COUNT) ?          \
291
0
     &(new_ctx)->DPB[(pic) - (old_ctx)->DPB] : NULL)
292
293
static void copy_picture_range(H264Picture **to, H264Picture *const *from, int count,
294
                               H264Context *new_base, const H264Context *old_base)
295
0
{
296
0
    int i;
297
298
0
    for (i = 0; i < count; i++) {
299
0
        av_assert1(!from[i] ||
300
0
                   IN_RANGE(from[i], old_base, 1) ||
301
0
                   IN_RANGE(from[i], old_base->DPB, H264_MAX_PICTURE_COUNT));
302
0
        to[i] = REBASE_PICTURE(from[i], new_base, old_base);
303
0
    }
304
0
}
305
306
static void color_frame(AVFrame *frame, const int c[4])
307
287k
{
308
287k
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
309
310
287k
    av_assert0(desc->flags & AV_PIX_FMT_FLAG_PLANAR);
311
312
1.15M
    for (int p = 0; p < desc->nb_components; p++) {
313
863k
        uint8_t *dst = frame->data[p];
314
863k
        int is_chroma = p == 1 || p == 2;
315
863k
        int bytes  = is_chroma ? AV_CEIL_RSHIFT(frame->width,  desc->log2_chroma_w) : frame->width;
316
863k
        int height = is_chroma ? AV_CEIL_RSHIFT(frame->height, desc->log2_chroma_h) : frame->height;
317
863k
        if (desc->comp[0].depth >= 9) {
318
522k
            if (bytes >= 1)
319
522k
                ((uint16_t*)dst)[0] = c[p];
320
522k
            if (bytes >= 2)
321
522k
                av_memcpy_backptr(dst + 2, 2, 2 * (bytes - 1));
322
522k
            dst += frame->linesize[p];
323
131M
            for (int y = 1; y < height; y++) {
324
130M
                memcpy(dst, frame->data[p], 2*bytes);
325
130M
                dst += frame->linesize[p];
326
130M
            }
327
522k
        } else {
328
141M
            for (int y = 0; y < height; y++) {
329
141M
                memset(dst, c[p], bytes);
330
141M
                dst += frame->linesize[p];
331
141M
            }
332
341k
        }
333
863k
    }
334
287k
}
335
336
static int h264_slice_header_init(H264Context *h);
337
338
int ff_h264_update_thread_context(AVCodecContext *dst,
339
                                  const AVCodecContext *src)
340
0
{
341
0
    H264Context *h = dst->priv_data, *h1 = src->priv_data;
342
0
    int inited = h->context_initialized, err = 0;
343
0
    int need_reinit = 0;
344
0
    int i, ret;
345
346
0
    if (dst == src)
347
0
        return 0;
348
349
0
    if (inited && !h1->ps.sps)
350
0
        return AVERROR_INVALIDDATA;
351
352
0
    if (inited &&
353
0
        (h->width                 != h1->width                 ||
354
0
         h->height                != h1->height                ||
355
0
         h->mb_width              != h1->mb_width              ||
356
0
         h->mb_height             != h1->mb_height             ||
357
0
         !h->ps.sps                                            ||
358
0
         h->ps.sps->bit_depth_luma    != h1->ps.sps->bit_depth_luma    ||
359
0
         h->ps.sps->chroma_format_idc != h1->ps.sps->chroma_format_idc ||
360
0
         h->ps.sps->vui.matrix_coeffs != h1->ps.sps->vui.matrix_coeffs)) {
361
0
        need_reinit = 1;
362
0
    }
363
364
    /* copy block_offset since frame_start may not be called */
365
0
    memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
366
367
    // SPS/PPS
368
0
    for (int i = 0; i < FF_ARRAY_ELEMS(h->ps.sps_list); i++)
369
0
        av_refstruct_replace(&h->ps.sps_list[i], h1->ps.sps_list[i]);
370
0
    for (int i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++)
371
0
        av_refstruct_replace(&h->ps.pps_list[i], h1->ps.pps_list[i]);
372
373
0
    av_refstruct_replace(&h->ps.pps, h1->ps.pps);
374
0
    h->ps.sps = h1->ps.sps;
375
376
0
    if (need_reinit || !inited) {
377
0
        h->width     = h1->width;
378
0
        h->height    = h1->height;
379
0
        h->mb_height = h1->mb_height;
380
0
        h->mb_width  = h1->mb_width;
381
0
        h->mb_num    = h1->mb_num;
382
0
        h->mb_stride = h1->mb_stride;
383
0
        h->b_stride  = h1->b_stride;
384
0
        h->x264_build = h1->x264_build;
385
386
0
        if (h->context_initialized || h1->context_initialized) {
387
0
            if ((err = h264_slice_header_init(h)) < 0) {
388
0
                av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
389
0
                return err;
390
0
            }
391
0
        }
392
393
        /* copy block_offset since frame_start may not be called */
394
0
        memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
395
0
    }
396
397
0
    h->width_from_caller    = h1->width_from_caller;
398
0
    h->height_from_caller   = h1->height_from_caller;
399
0
    h->first_field          = h1->first_field;
400
0
    h->picture_structure    = h1->picture_structure;
401
0
    h->mb_aff_frame         = h1->mb_aff_frame;
402
0
    h->droppable            = h1->droppable;
403
404
0
    for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
405
0
        ret = ff_h264_replace_picture(&h->DPB[i], &h1->DPB[i]);
406
0
        if (ret < 0)
407
0
            return ret;
408
0
    }
409
410
0
    h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
411
0
    ret = ff_h264_replace_picture(&h->cur_pic, &h1->cur_pic);
412
0
    if (ret < 0)
413
0
        return ret;
414
415
0
    h->enable_er       = h1->enable_er;
416
0
    h->workaround_bugs = h1->workaround_bugs;
417
0
    h->droppable       = h1->droppable;
418
419
    // extradata/NAL handling
420
0
    h->is_avc = h1->is_avc;
421
0
    h->nal_length_size = h1->nal_length_size;
422
423
0
    memcpy(&h->poc,        &h1->poc,        sizeof(h->poc));
424
425
0
    memcpy(h->short_ref,   h1->short_ref,   sizeof(h->short_ref));
426
0
    memcpy(h->long_ref,    h1->long_ref,    sizeof(h->long_ref));
427
0
    memcpy(h->delayed_pic, h1->delayed_pic, sizeof(h->delayed_pic));
428
0
    memcpy(h->last_pocs,   h1->last_pocs,   sizeof(h->last_pocs));
429
430
0
    h->next_output_pic   = h1->next_output_pic;
431
0
    h->next_outputed_poc = h1->next_outputed_poc;
432
0
    h->poc_offset        = h1->poc_offset;
433
434
0
    memcpy(h->mmco, h1->mmco, sizeof(h->mmco));
435
0
    h->nb_mmco         = h1->nb_mmco;
436
0
    h->mmco_reset      = h1->mmco_reset;
437
0
    h->explicit_ref_marking = h1->explicit_ref_marking;
438
0
    h->long_ref_count  = h1->long_ref_count;
439
0
    h->short_ref_count = h1->short_ref_count;
440
441
0
    copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
442
0
    copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
443
0
    copy_picture_range(h->delayed_pic, h1->delayed_pic,
444
0
                       FF_ARRAY_ELEMS(h->delayed_pic), h, h1);
445
446
0
    h->frame_recovered       = h1->frame_recovered;
447
448
0
    ret = ff_h2645_sei_ctx_replace(&h->sei.common, &h1->sei.common);
449
0
    if (ret < 0)
450
0
        return ret;
451
452
0
    h->sei.common.unregistered.x264_build = h1->sei.common.unregistered.x264_build;
453
454
0
    if (!h->cur_pic_ptr)
455
0
        return 0;
456
457
0
    if (!h->droppable) {
458
0
        err = ff_h264_execute_ref_pic_marking(h);
459
0
        h->poc.prev_poc_msb = h->poc.poc_msb;
460
0
        h->poc.prev_poc_lsb = h->poc.poc_lsb;
461
0
    }
462
0
    h->poc.prev_frame_num_offset = h->poc.frame_num_offset;
463
0
    h->poc.prev_frame_num        = h->poc.frame_num;
464
465
0
    h->recovery_frame        = h1->recovery_frame;
466
0
    h->non_gray              = h1->non_gray;
467
468
0
    return err;
469
0
}
470
471
int ff_h264_update_thread_context_for_user(AVCodecContext *dst,
472
                                           const AVCodecContext *src)
473
0
{
474
0
    H264Context *h = dst->priv_data;
475
0
    const H264Context *h1 = src->priv_data;
476
477
0
    h->is_avc = h1->is_avc;
478
0
    h->nal_length_size = h1->nal_length_size;
479
480
0
    return 0;
481
0
}
482
483
static int h264_frame_start(H264Context *h)
484
4.04M
{
485
4.04M
    H264Picture *pic;
486
4.04M
    int i, ret;
487
4.04M
    const int pixel_shift = h->pixel_shift;
488
489
4.04M
    if (!ff_thread_can_start_frame(h->avctx)) {
490
0
        av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
491
0
        return AVERROR_BUG;
492
0
    }
493
494
4.04M
    release_unused_pictures(h, 1);
495
4.04M
    h->cur_pic_ptr = NULL;
496
497
4.04M
    i = find_unused_picture(h);
498
4.04M
    if (i < 0) {
499
0
        av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
500
0
        return i;
501
0
    }
502
4.04M
    pic = &h->DPB[i];
503
504
4.04M
    pic->reference              = h->droppable ? 0 : h->picture_structure;
505
4.04M
    pic->field_picture          = h->picture_structure != PICT_FRAME;
506
4.04M
    pic->frame_num               = h->poc.frame_num;
507
    /*
508
     * Zero key_frame here; IDR markings per slice in frame or fields are ORed
509
     * in later.
510
     * See decode_nal_units().
511
     */
512
4.04M
    pic->f->flags   &= ~AV_FRAME_FLAG_KEY;
513
4.04M
    pic->mmco_reset  = 0;
514
4.04M
    pic->recovered   = 0;
515
4.04M
    pic->invalid_gap = 0;
516
4.04M
    pic->sei_recovery_frame_cnt = h->sei.recovery_point.recovery_frame_cnt;
517
518
4.04M
    pic->f->pict_type = h->slice_ctx[0].slice_type;
519
520
4.04M
    pic->f->crop_left   = h->crop_left;
521
4.04M
    pic->f->crop_right  = h->crop_right;
522
4.04M
    pic->f->crop_top    = h->crop_top;
523
4.04M
    pic->f->crop_bottom = h->crop_bottom;
524
525
4.04M
    pic->needs_fg =
526
4.04M
        h->sei.common.film_grain_characteristics &&
527
82.5k
        h->sei.common.film_grain_characteristics->present &&
528
16.9k
        !h->avctx->hwaccel &&
529
16.9k
        !(h->avctx->export_side_data & AV_CODEC_EXPORT_DATA_FILM_GRAIN);
530
531
4.04M
    if ((ret = alloc_picture(h, pic)) < 0)
532
6.39k
        return ret;
533
534
4.03M
    h->cur_pic_ptr = pic;
535
4.03M
    ff_h264_unref_picture(&h->cur_pic);
536
4.03M
    if (CONFIG_ERROR_RESILIENCE) {
537
4.03M
        ff_h264_set_erpic(&h->er.cur_pic, NULL);
538
4.03M
    }
539
540
4.03M
    if ((ret = ff_h264_ref_picture(&h->cur_pic, h->cur_pic_ptr)) < 0)
541
0
        return ret;
542
543
8.06M
    for (i = 0; i < h->nb_slice_ctx; i++) {
544
4.03M
        h->slice_ctx[i].linesize   = h->cur_pic_ptr->f->linesize[0];
545
4.03M
        h->slice_ctx[i].uvlinesize = h->cur_pic_ptr->f->linesize[1];
546
4.03M
    }
547
548
4.03M
    if (CONFIG_ERROR_RESILIENCE && h->enable_er) {
549
4.03M
        ff_er_frame_start(&h->er);
550
4.03M
        ff_h264_set_erpic(&h->er.last_pic, NULL);
551
4.03M
        ff_h264_set_erpic(&h->er.next_pic, NULL);
552
4.03M
    }
553
554
68.5M
    for (i = 0; i < 16; i++) {
555
64.5M
        h->block_offset[i]           = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
556
64.5M
        h->block_offset[48 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
557
64.5M
    }
558
68.5M
    for (i = 0; i < 16; i++) {
559
64.5M
        h->block_offset[16 + i]      =
560
64.5M
        h->block_offset[32 + i]      = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
561
64.5M
        h->block_offset[48 + 16 + i] =
562
64.5M
        h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
563
64.5M
    }
564
565
    /* We mark the current picture as non-reference after allocating it, so
566
     * that if we break out due to an error it can be released automatically
567
     * in the next ff_mpv_frame_start().
568
     */
569
4.03M
    h->cur_pic_ptr->reference = 0;
570
571
4.03M
    h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
572
573
4.03M
    h->next_output_pic = NULL;
574
575
4.03M
    h->postpone_filter = 0;
576
577
4.03M
    h->mb_aff_frame = h->ps.sps->mb_aff && (h->picture_structure == PICT_FRAME);
578
579
4.03M
    if (h->sei.common.unregistered.x264_build >= 0)
580
504k
        h->x264_build = h->sei.common.unregistered.x264_build;
581
582
4.03M
    assert(h->cur_pic_ptr->long_ref == 0);
583
584
4.03M
    return 0;
585
4.03M
}
586
587
static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
588
                                              const uint8_t *src_y,
589
                                              const uint8_t *src_cb, const uint8_t *src_cr,
590
                                              int linesize, int uvlinesize,
591
                                              int simple)
592
32.9M
{
593
32.9M
    uint8_t *top_border;
594
32.9M
    int top_idx = 1;
595
32.9M
    const int pixel_shift = h->pixel_shift;
596
32.9M
    int chroma444 = CHROMA444(h);
597
32.9M
    int chroma422 = CHROMA422(h);
598
599
32.9M
    src_y  -= linesize;
600
32.9M
    src_cb -= uvlinesize;
601
32.9M
    src_cr -= uvlinesize;
602
603
32.9M
    if (!simple && FRAME_MBAFF(h)) {
604
14.1M
        if (sl->mb_y & 1) {
605
7.08M
            if (!MB_MBAFF(sl)) {
606
4.58M
                top_border = sl->top_borders[0][sl->mb_x];
607
4.58M
                AV_COPY128(top_border, src_y + 15 * linesize);
608
4.58M
                if (pixel_shift)
609
3.88M
                    AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
610
4.58M
                if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
611
4.58M
                    if (chroma444) {
612
93.7k
                        if (pixel_shift) {
613
65.2k
                            AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
614
65.2k
                            AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
615
65.2k
                            AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
616
65.2k
                            AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
617
65.2k
                        } else {
618
28.5k
                            AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
619
28.5k
                            AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
620
28.5k
                        }
621
4.49M
                    } else if (chroma422) {
622
2.40M
                        if (pixel_shift) {
623
2.24M
                            AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
624
2.24M
                            AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
625
2.24M
                        } else {
626
160k
                            AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
627
160k
                            AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
628
160k
                        }
629
2.40M
                    } else {
630
2.09M
                        if (pixel_shift) {
631
1.58M
                            AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
632
1.58M
                            AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
633
1.58M
                        } else {
634
508k
                            AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
635
508k
                            AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
636
508k
                        }
637
2.09M
                    }
638
4.58M
                }
639
4.58M
            }
640
7.08M
        } else if (MB_MBAFF(sl)) {
641
2.49M
            top_idx = 0;
642
2.49M
        } else
643
4.58M
            return;
644
14.1M
    }
645
646
28.3M
    top_border = sl->top_borders[top_idx][sl->mb_x];
647
    /* There are two lines saved, the line above the top macroblock
648
     * of a pair, and the line above the bottom macroblock. */
649
28.3M
    AV_COPY128(top_border, src_y + 16 * linesize);
650
28.3M
    if (pixel_shift)
651
20.1M
        AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
652
653
28.3M
    if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
654
28.3M
        if (chroma444) {
655
1.73M
            if (pixel_shift) {
656
1.28M
                AV_COPY128(top_border + 32, src_cb + 16 * linesize);
657
1.28M
                AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
658
1.28M
                AV_COPY128(top_border + 64, src_cr + 16 * linesize);
659
1.28M
                AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
660
1.28M
            } else {
661
445k
                AV_COPY128(top_border + 16, src_cb + 16 * linesize);
662
445k
                AV_COPY128(top_border + 32, src_cr + 16 * linesize);
663
445k
            }
664
26.5M
        } else if (chroma422) {
665
9.70M
            if (pixel_shift) {
666
8.54M
                AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
667
8.54M
                AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
668
8.54M
            } else {
669
1.16M
                AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
670
1.16M
                AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
671
1.16M
            }
672
16.8M
        } else {
673
16.8M
            if (pixel_shift) {
674
10.3M
                AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
675
10.3M
                AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
676
10.3M
            } else {
677
6.51M
                AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
678
6.51M
                AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
679
6.51M
            }
680
16.8M
        }
681
28.3M
    }
682
28.3M
}
683
684
/**
685
 * Initialize implicit_weight table.
686
 * @param field  0/1 initialize the weight for interlaced MBAFF
687
 *                -1 initializes the rest
688
 */
689
static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
690
861k
{
691
861k
    int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
692
693
2.58M
    for (i = 0; i < 2; i++) {
694
1.72M
        sl->pwt.luma_weight_flag[i]   = 0;
695
1.72M
        sl->pwt.chroma_weight_flag[i] = 0;
696
1.72M
    }
697
698
861k
    if (field < 0) {
699
488k
        if (h->picture_structure == PICT_FRAME) {
700
393k
            cur_poc = h->cur_pic_ptr->poc;
701
393k
        } else {
702
94.2k
            cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
703
94.2k
        }
704
488k
        if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
705
5.80k
            sl->ref_list[0][0].poc + (int64_t)sl->ref_list[1][0].poc == 2LL * cur_poc) {
706
480
            sl->pwt.use_weight        = 0;
707
480
            sl->pwt.use_weight_chroma = 0;
708
480
            return;
709
480
        }
710
487k
        ref_start  = 0;
711
487k
        ref_count0 = sl->ref_count[0];
712
487k
        ref_count1 = sl->ref_count[1];
713
487k
    } else {
714
372k
        cur_poc    = h->cur_pic_ptr->field_poc[field];
715
372k
        ref_start  = 16;
716
372k
        ref_count0 = 16 + 2 * sl->ref_count[0];
717
372k
        ref_count1 = 16 + 2 * sl->ref_count[1];
718
372k
    }
719
720
860k
    sl->pwt.use_weight               = 2;
721
860k
    sl->pwt.use_weight_chroma        = 2;
722
860k
    sl->pwt.luma_log2_weight_denom   = 5;
723
860k
    sl->pwt.chroma_log2_weight_denom = 5;
724
725
8.26M
    for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
726
7.40M
        int64_t poc0 = sl->ref_list[0][ref0].poc;
727
22.3M
        for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
728
14.8M
            int w = 32;
729
14.8M
            if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
730
8.90M
                int poc1 = sl->ref_list[1][ref1].poc;
731
8.90M
                int td   = av_clip_int8(poc1 - poc0);
732
8.90M
                if (td) {
733
1.61M
                    int tb = av_clip_int8(cur_poc - poc0);
734
1.61M
                    int tx = (16384 + (FFABS(td) >> 1)) / td;
735
1.61M
                    int dist_scale_factor = (tb * tx + 32) >> 8;
736
1.61M
                    if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
737
860k
                        w = 64 - dist_scale_factor;
738
1.61M
                }
739
8.90M
            }
740
14.8M
            if (field < 0) {
741
3.61M
                sl->pwt.implicit_weight[ref0][ref1][0] =
742
3.61M
                sl->pwt.implicit_weight[ref0][ref1][1] = w;
743
11.2M
            } else {
744
11.2M
                sl->pwt.implicit_weight[ref0][ref1][field] = w;
745
11.2M
            }
746
14.8M
        }
747
7.40M
    }
748
860k
}
749
750
/**
751
 * initialize scan tables
752
 */
753
static void init_scan_tables(H264Context *h)
754
507k
{
755
507k
    int i;
756
8.62M
    for (i = 0; i < 16; i++) {
757
16.2M
#define TRANSPOSE(x) ((x) >> 2) | (((x) << 2) & 0xF)
758
8.11M
        h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
759
8.11M
        h->field_scan[i]  = TRANSPOSE(field_scan[i]);
760
8.11M
#undef TRANSPOSE
761
8.11M
    }
762
32.9M
    for (i = 0; i < 64; i++) {
763
129M
#define TRANSPOSE(x) ((x) >> 3) | (((x) & 7) << 3)
764
32.4M
        h->zigzag_scan8x8[i]       = TRANSPOSE(ff_zigzag_direct[i]);
765
32.4M
        h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
766
32.4M
        h->field_scan8x8[i]        = TRANSPOSE(field_scan8x8[i]);
767
32.4M
        h->field_scan8x8_cavlc[i]  = TRANSPOSE(field_scan8x8_cavlc[i]);
768
32.4M
#undef TRANSPOSE
769
32.4M
    }
770
507k
    if (h->ps.sps->transform_bypass) { // FIXME same ugly
771
123k
        memcpy(h->zigzag_scan_q0          , ff_zigzag_scan          , sizeof(h->zigzag_scan_q0         ));
772
123k
        memcpy(h->zigzag_scan8x8_q0       , ff_zigzag_direct        , sizeof(h->zigzag_scan8x8_q0      ));
773
123k
        memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc    , sizeof(h->zigzag_scan8x8_cavlc_q0));
774
123k
        memcpy(h->field_scan_q0           , field_scan              , sizeof(h->field_scan_q0          ));
775
123k
        memcpy(h->field_scan8x8_q0        , field_scan8x8           , sizeof(h->field_scan8x8_q0       ));
776
123k
        memcpy(h->field_scan8x8_cavlc_q0  , field_scan8x8_cavlc     , sizeof(h->field_scan8x8_cavlc_q0 ));
777
383k
    } else {
778
383k
        memcpy(h->zigzag_scan_q0          , h->zigzag_scan          , sizeof(h->zigzag_scan_q0         ));
779
383k
        memcpy(h->zigzag_scan8x8_q0       , h->zigzag_scan8x8       , sizeof(h->zigzag_scan8x8_q0      ));
780
383k
        memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
781
383k
        memcpy(h->field_scan_q0           , h->field_scan           , sizeof(h->field_scan_q0          ));
782
383k
        memcpy(h->field_scan8x8_q0        , h->field_scan8x8        , sizeof(h->field_scan8x8_q0       ));
783
383k
        memcpy(h->field_scan8x8_cavlc_q0  , h->field_scan8x8_cavlc  , sizeof(h->field_scan8x8_cavlc_q0 ));
784
383k
    }
785
507k
}
786
787
static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
788
3.00M
{
789
3.00M
#define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
790
3.00M
                     (CONFIG_H264_D3D11VA_HWACCEL * 2) + \
791
3.00M
                     CONFIG_H264_D3D12VA_HWACCEL + \
792
3.00M
                     CONFIG_H264_NVDEC_HWACCEL + \
793
3.00M
                     CONFIG_H264_NVDEC_CUARRAY_HWACCEL + \
794
3.00M
                     CONFIG_H264_VAAPI_HWACCEL + \
795
3.00M
                     CONFIG_H264_VIDEOTOOLBOX_HWACCEL + \
796
3.00M
                     CONFIG_H264_VDPAU_HWACCEL + \
797
3.00M
                     CONFIG_H264_VULKAN_HWACCEL)
798
3.00M
    enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
799
800
3.00M
    switch (h->ps.sps->bit_depth_luma) {
801
468k
    case 9:
802
468k
        if (CHROMA444(h)) {
803
102k
            if (h->avctx->colorspace == AVCOL_SPC_RGB) {
804
221
                *fmt++ = AV_PIX_FMT_GBRP9;
805
221
            } else
806
102k
                *fmt++ = AV_PIX_FMT_YUV444P9;
807
365k
        } else if (CHROMA422(h))
808
246k
            *fmt++ = AV_PIX_FMT_YUV422P9;
809
119k
        else
810
119k
            *fmt++ = AV_PIX_FMT_YUV420P9;
811
468k
        break;
812
302k
    case 10:
813
#if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
814
        if (h->avctx->colorspace != AVCOL_SPC_RGB)
815
            *fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
816
#endif
817
#if CONFIG_H264_VULKAN_HWACCEL
818
        *fmt++ = AV_PIX_FMT_VULKAN;
819
#endif
820
#if CONFIG_H264_NVDEC_HWACCEL
821
        *fmt++ = AV_PIX_FMT_CUDA;
822
#endif
823
#if CONFIG_H264_NVDEC_CUARRAY_HWACCEL
824
        *fmt++ = AV_PIX_FMT_CUARRAY;
825
#endif
826
302k
        if (CHROMA444(h)) {
827
22.0k
            if (h->avctx->colorspace == AVCOL_SPC_RGB) {
828
587
                *fmt++ = AV_PIX_FMT_GBRP10;
829
587
            } else
830
21.4k
                *fmt++ = AV_PIX_FMT_YUV444P10;
831
280k
        } else if (CHROMA422(h))
832
128k
            *fmt++ = AV_PIX_FMT_YUV422P10;
833
152k
        else {
834
#if CONFIG_H264_VAAPI_HWACCEL
835
            // Just add as candidate. Whether VAProfileH264High10 usable or
836
            // not is decided by vaapi_decode_make_config() defined in FFmpeg
837
            // and vaQueryCodingProfile() defined in libva.
838
            *fmt++ = AV_PIX_FMT_VAAPI;
839
#endif
840
152k
            *fmt++ = AV_PIX_FMT_YUV420P10;
841
152k
        }
842
302k
        break;
843
722k
    case 12:
844
#if CONFIG_H264_VULKAN_HWACCEL
845
        *fmt++ = AV_PIX_FMT_VULKAN;
846
#endif
847
722k
        if (CHROMA444(h)) {
848
13.8k
            if (h->avctx->colorspace == AVCOL_SPC_RGB) {
849
1.15k
                *fmt++ = AV_PIX_FMT_GBRP12;
850
1.15k
            } else
851
12.6k
                *fmt++ = AV_PIX_FMT_YUV444P12;
852
708k
        } else if (CHROMA422(h))
853
392k
            *fmt++ = AV_PIX_FMT_YUV422P12;
854
315k
        else
855
315k
            *fmt++ = AV_PIX_FMT_YUV420P12;
856
722k
        break;
857
437k
    case 14:
858
437k
        if (CHROMA444(h)) {
859
97.9k
            if (h->avctx->colorspace == AVCOL_SPC_RGB) {
860
422
                *fmt++ = AV_PIX_FMT_GBRP14;
861
422
            } else
862
97.5k
                *fmt++ = AV_PIX_FMT_YUV444P14;
863
339k
        } else if (CHROMA422(h))
864
171k
            *fmt++ = AV_PIX_FMT_YUV422P14;
865
168k
        else
866
168k
            *fmt++ = AV_PIX_FMT_YUV420P14;
867
437k
        break;
868
1.06M
    case 8:
869
#if CONFIG_H264_VDPAU_HWACCEL
870
        *fmt++ = AV_PIX_FMT_VDPAU;
871
#endif
872
#if CONFIG_H264_VULKAN_HWACCEL
873
        *fmt++ = AV_PIX_FMT_VULKAN;
874
#endif
875
#if CONFIG_H264_NVDEC_HWACCEL
876
        *fmt++ = AV_PIX_FMT_CUDA;
877
#endif
878
#if CONFIG_H264_NVDEC_CUARRAY_HWACCEL
879
        *fmt++ = AV_PIX_FMT_CUARRAY;
880
#endif
881
#if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
882
        if (h->avctx->colorspace != AVCOL_SPC_RGB)
883
            *fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
884
#endif
885
1.06M
        if (CHROMA444(h)) {
886
130k
            if (h->avctx->colorspace == AVCOL_SPC_RGB)
887
20.3k
                *fmt++ = AV_PIX_FMT_GBRP;
888
110k
            else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
889
33.1k
                *fmt++ = AV_PIX_FMT_YUVJ444P;
890
77.1k
            else
891
77.1k
                *fmt++ = AV_PIX_FMT_YUV444P;
892
938k
        } else if (CHROMA422(h)) {
893
83.7k
            if (h->avctx->color_range == AVCOL_RANGE_JPEG)
894
20.9k
                *fmt++ = AV_PIX_FMT_YUVJ422P;
895
62.7k
            else
896
62.7k
                *fmt++ = AV_PIX_FMT_YUV422P;
897
854k
        } else {
898
#if CONFIG_H264_DXVA2_HWACCEL
899
            *fmt++ = AV_PIX_FMT_DXVA2_VLD;
900
#endif
901
#if CONFIG_H264_D3D11VA_HWACCEL
902
            *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
903
            *fmt++ = AV_PIX_FMT_D3D11;
904
#endif
905
#if CONFIG_H264_D3D12VA_HWACCEL
906
            *fmt++ = AV_PIX_FMT_D3D12;
907
#endif
908
#if CONFIG_H264_VAAPI_HWACCEL
909
            *fmt++ = AV_PIX_FMT_VAAPI;
910
#endif
911
854k
            if (h->avctx->color_range == AVCOL_RANGE_JPEG)
912
276k
                *fmt++ = AV_PIX_FMT_YUVJ420P;
913
578k
            else
914
578k
                *fmt++ = AV_PIX_FMT_YUV420P;
915
854k
        }
916
1.06M
        break;
917
0
    default:
918
0
        av_log(h->avctx, AV_LOG_ERROR,
919
0
               "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);
920
0
        return AVERROR_INVALIDDATA;
921
3.00M
    }
922
923
3.00M
    *fmt = AV_PIX_FMT_NONE;
924
925
3.14M
    for (int i = 0; pix_fmts[i] != AV_PIX_FMT_NONE; i++)
926
3.00M
        if (pix_fmts[i] == h->avctx->pix_fmt && !force_callback)
927
2.85M
            return pix_fmts[i];
928
147k
    return ff_get_format(h->avctx, pix_fmts);
929
3.00M
}
930
931
/* export coded and cropped frame dimensions to AVCodecContext */
932
static void init_dimensions(H264Context *h)
933
2.52M
{
934
2.52M
    const SPS *sps = h->ps.sps;
935
2.52M
    int cr = sps->crop_right;
936
2.52M
    int cl = sps->crop_left;
937
2.52M
    int ct = sps->crop_top;
938
2.52M
    int cb = sps->crop_bottom;
939
2.52M
    int width  = h->width  - (cr + cl);
940
2.52M
    int height = h->height - (ct + cb);
941
2.52M
    av_assert0(sps->crop_right + sps->crop_left < (unsigned)h->width);
942
2.52M
    av_assert0(sps->crop_top + sps->crop_bottom < (unsigned)h->height);
943
944
    /* handle container cropping */
945
2.52M
    if (h->width_from_caller > 0 && h->height_from_caller > 0     &&
946
140
        !sps->crop_top && !sps->crop_left                         &&
947
128
        FFALIGN(h->width_from_caller,  16) == FFALIGN(width,  16) &&
948
88
        FFALIGN(h->height_from_caller, 16) == FFALIGN(height, 16) &&
949
85
        h->width_from_caller  <= width &&
950
85
        h->height_from_caller <= height) {
951
85
        width  = h->width_from_caller;
952
85
        height = h->height_from_caller;
953
85
        cl = 0;
954
85
        ct = 0;
955
85
        cr = h->width - width;
956
85
        cb = h->height - height;
957
2.52M
    } else {
958
2.52M
        h->width_from_caller  = 0;
959
2.52M
        h->height_from_caller = 0;
960
2.52M
    }
961
962
2.52M
    h->avctx->coded_width  = h->width;
963
2.52M
    h->avctx->coded_height = h->height;
964
2.52M
    h->avctx->width        = width;
965
2.52M
    h->avctx->height       = height;
966
2.52M
    h->crop_right          = cr;
967
2.52M
    h->crop_left           = cl;
968
2.52M
    h->crop_top            = ct;
969
2.52M
    h->crop_bottom         = cb;
970
2.52M
}
971
972
static int h264_slice_header_init(H264Context *h)
973
507k
{
974
507k
    const SPS *sps = h->ps.sps;
975
507k
    int i, ret;
976
977
507k
    if (!sps) {
978
0
        ret = AVERROR_INVALIDDATA;
979
0
        goto fail;
980
0
    }
981
982
507k
    ff_set_sar(h->avctx, sps->vui.sar);
983
507k
    av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
984
507k
                                     &h->chroma_x_shift, &h->chroma_y_shift);
985
986
507k
    if (sps->timing_info_present_flag) {
987
98.8k
        int64_t den = sps->time_scale;
988
98.8k
        if (h->x264_build < 44U)
989
2.71k
            den *= 2;
990
98.8k
        av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
991
98.8k
                  sps->num_units_in_tick * 2, den, 1 << 30);
992
98.8k
    }
993
994
507k
    ff_h264_free_tables(h);
995
996
507k
    h->first_field           = 0;
997
507k
    h->prev_interlaced_frame = 1;
998
999
507k
    init_scan_tables(h);
1000
507k
    ret = ff_h264_alloc_tables(h);
1001
507k
    if (ret < 0) {
1002
0
        av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
1003
0
        goto fail;
1004
0
    }
1005
1006
507k
    if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 14 ||
1007
507k
        sps->bit_depth_luma == 11 || sps->bit_depth_luma == 13
1008
507k
    ) {
1009
0
        av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
1010
0
               sps->bit_depth_luma);
1011
0
        ret = AVERROR_INVALIDDATA;
1012
0
        goto fail;
1013
0
    }
1014
1015
507k
    h->cur_bit_depth_luma         =
1016
507k
    h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
1017
507k
    h->cur_chroma_format_idc      = sps->chroma_format_idc;
1018
507k
    h->pixel_shift                = sps->bit_depth_luma > 8;
1019
507k
    h->chroma_format_idc          = sps->chroma_format_idc;
1020
507k
    h->bit_depth_luma             = sps->bit_depth_luma;
1021
1022
507k
    ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
1023
507k
                    sps->chroma_format_idc);
1024
507k
    ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
1025
507k
    ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
1026
507k
    ff_h264_pred_init(&h->hpc, AV_CODEC_ID_H264, sps->bit_depth_luma,
1027
507k
                      sps->chroma_format_idc);
1028
507k
    ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
1029
1030
507k
    if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
1031
507k
        ff_h264_slice_context_init(h, &h->slice_ctx[0]);
1032
507k
    } else {
1033
0
        for (i = 0; i < h->nb_slice_ctx; i++) {
1034
0
            H264SliceContext *sl = &h->slice_ctx[i];
1035
1036
0
            sl->h264               = h;
1037
0
            sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
1038
0
            sl->mvd_table[0]       = h->mvd_table[0]       + i * 8 * 2 * h->mb_stride;
1039
0
            sl->mvd_table[1]       = h->mvd_table[1]       + i * 8 * 2 * h->mb_stride;
1040
1041
0
            ff_h264_slice_context_init(h, sl);
1042
0
        }
1043
0
    }
1044
1045
507k
    h->context_initialized = 1;
1046
1047
507k
    return 0;
1048
0
fail:
1049
0
    ff_h264_free_tables(h);
1050
0
    h->context_initialized = 0;
1051
0
    return ret;
1052
507k
}
1053
1054
static enum AVPixelFormat non_j_pixfmt(enum AVPixelFormat a)
1055
4.98M
{
1056
4.98M
    switch (a) {
1057
429k
    case AV_PIX_FMT_YUVJ420P: return AV_PIX_FMT_YUV420P;
1058
32.8k
    case AV_PIX_FMT_YUVJ422P: return AV_PIX_FMT_YUV422P;
1059
51.2k
    case AV_PIX_FMT_YUVJ444P: return AV_PIX_FMT_YUV444P;
1060
4.47M
    default:
1061
4.47M
        return a;
1062
4.98M
    }
1063
4.98M
}
1064
1065
static int h264_init_ps(H264Context *h, const H264SliceContext *sl, int first_slice)
1066
2.52M
{
1067
2.52M
    const SPS *sps;
1068
2.52M
    int needs_reinit = 0, must_reinit, ret;
1069
1070
2.52M
    if (first_slice)
1071
1.88M
        av_refstruct_replace(&h->ps.pps, h->ps.pps_list[sl->pps_id]);
1072
1073
2.52M
    if (h->ps.sps != h->ps.pps->sps) {
1074
127k
        h->ps.sps = h->ps.pps->sps;
1075
1076
127k
        if (h->mb_width  != h->ps.sps->mb_width ||
1077
38.8k
            h->mb_height != h->ps.sps->mb_height ||
1078
33.2k
            h->cur_bit_depth_luma    != h->ps.sps->bit_depth_luma ||
1079
30.7k
            h->cur_chroma_format_idc != h->ps.sps->chroma_format_idc
1080
127k
        )
1081
98.1k
            needs_reinit = 1;
1082
1083
127k
        if (h->bit_depth_luma    != h->ps.sps->bit_depth_luma ||
1084
50.5k
            h->chroma_format_idc != h->ps.sps->chroma_format_idc)
1085
83.5k
            needs_reinit         = 1;
1086
127k
    }
1087
2.52M
    sps = h->ps.sps;
1088
1089
2.52M
    must_reinit = (h->context_initialized &&
1090
2.06M
                    (   16*sps->mb_width != h->avctx->coded_width
1091
2.02M
                     || 16*sps->mb_height != h->avctx->coded_height
1092
2.02M
                     || h->cur_bit_depth_luma    != sps->bit_depth_luma
1093
2.02M
                     || h->cur_chroma_format_idc != sps->chroma_format_idc
1094
2.02M
                     || h->mb_width  != sps->mb_width
1095
2.02M
                     || h->mb_height != sps->mb_height
1096
2.06M
                    ));
1097
2.52M
    if (h->avctx->pix_fmt == AV_PIX_FMT_NONE
1098
2.49M
        || (non_j_pixfmt(h->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h, 0))))
1099
82.8k
        must_reinit = 1;
1100
1101
2.52M
    if (first_slice && av_cmp_q(sps->vui.sar, h->avctx->sample_aspect_ratio))
1102
13.8k
        must_reinit = 1;
1103
1104
2.52M
    if (!h->setup_finished) {
1105
2.52M
        h->avctx->profile = ff_h264_get_profile(sps);
1106
2.52M
        h->avctx->level   = sps->level_idc;
1107
2.52M
        h->avctx->refs    = sps->ref_frame_count;
1108
1109
2.52M
        h->mb_width  = sps->mb_width;
1110
2.52M
        h->mb_height = sps->mb_height;
1111
2.52M
        h->mb_num    = h->mb_width * h->mb_height;
1112
2.52M
        h->mb_stride = h->mb_width + 1;
1113
1114
2.52M
        h->b_stride = h->mb_width * 4;
1115
1116
2.52M
        h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
1117
1118
2.52M
        h->width  = 16 * h->mb_width;
1119
2.52M
        h->height = 16 * h->mb_height;
1120
1121
2.52M
        init_dimensions(h);
1122
1123
2.52M
        if (sps->vui.video_signal_type_present_flag) {
1124
505k
            h->avctx->color_range = sps->vui.video_full_range_flag > 0 ? AVCOL_RANGE_JPEG
1125
505k
                                                                       : AVCOL_RANGE_MPEG;
1126
505k
            if (sps->vui.colour_description_present_flag) {
1127
361k
                if (h->avctx->colorspace != sps->vui.matrix_coeffs)
1128
3.46k
                    needs_reinit = 1;
1129
361k
                h->avctx->color_primaries = sps->vui.colour_primaries;
1130
361k
                h->avctx->color_trc       = sps->vui.transfer_characteristics;
1131
361k
                h->avctx->colorspace      = sps->vui.matrix_coeffs;
1132
361k
            }
1133
505k
        }
1134
1135
2.52M
        if (h->sei.common.alternative_transfer.present &&
1136
26.8k
            av_color_transfer_name(h->sei.common.alternative_transfer.preferred_transfer_characteristics) &&
1137
3.66k
            h->sei.common.alternative_transfer.preferred_transfer_characteristics != AVCOL_TRC_UNSPECIFIED) {
1138
2.95k
            h->avctx->color_trc = h->sei.common.alternative_transfer.preferred_transfer_characteristics;
1139
2.95k
        }
1140
2.52M
    }
1141
2.52M
    h->avctx->chroma_sample_location = sps->vui.chroma_location;
1142
1143
2.52M
    if (!h->context_initialized || must_reinit || needs_reinit) {
1144
507k
        int flush_changes = h->context_initialized;
1145
507k
        h->context_initialized = 0;
1146
507k
        if (sl != h->slice_ctx) {
1147
0
            av_log(h->avctx, AV_LOG_ERROR,
1148
0
                   "changing width %d -> %d / height %d -> %d on "
1149
0
                   "slice %d\n",
1150
0
                   h->width, h->avctx->coded_width,
1151
0
                   h->height, h->avctx->coded_height,
1152
0
                   h->current_slice + 1);
1153
0
            return AVERROR_INVALIDDATA;
1154
0
        }
1155
1156
507k
        av_assert1(first_slice);
1157
1158
507k
        if (flush_changes)
1159
44.4k
            ff_h264_flush_change(h);
1160
1161
507k
        if ((ret = get_pixel_format(h, must_reinit || needs_reinit)) < 0)
1162
0
            return ret;
1163
507k
        h->avctx->pix_fmt = ret;
1164
1165
507k
        av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
1166
507k
               "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
1167
1168
507k
        if ((ret = h264_slice_header_init(h)) < 0) {
1169
0
            av_log(h->avctx, AV_LOG_ERROR,
1170
0
                   "h264_slice_header_init() failed\n");
1171
0
            return ret;
1172
0
        }
1173
507k
    }
1174
1175
2.52M
    return 0;
1176
2.52M
}
1177
1178
static int h264_export_frame_props(H264Context *h)
1179
2.45M
{
1180
2.45M
    const SPS *sps = h->ps.sps;
1181
2.45M
    H264Picture *cur = h->cur_pic_ptr;
1182
2.45M
    AVFrame *out = cur->f;
1183
2.45M
    int interlaced_frame = 0, top_field_first = 0;
1184
2.45M
    int ret;
1185
1186
2.45M
    out->flags &= ~AV_FRAME_FLAG_INTERLACED;
1187
2.45M
    out->repeat_pict      = 0;
1188
1189
    /* Signal interlacing information externally. */
1190
    /* Prioritize picture timing SEI information over used
1191
     * decoding process if it exists. */
1192
2.45M
    if (h->sei.picture_timing.present) {
1193
298k
        int ret = ff_h264_sei_process_picture_timing(&h->sei.picture_timing, sps,
1194
298k
                                                     h->avctx);
1195
298k
        if (ret < 0) {
1196
3.28k
            av_log(h->avctx, AV_LOG_ERROR, "Error processing a picture timing SEI\n");
1197
3.28k
            if (h->avctx->err_recognition & AV_EF_EXPLODE)
1198
104
                return ret;
1199
3.17k
            h->sei.picture_timing.present = 0;
1200
3.17k
        }
1201
298k
    }
1202
1203
2.45M
    if (sps->pic_struct_present_flag && h->sei.picture_timing.present) {
1204
154k
        const H264SEIPictureTiming *pt = &h->sei.picture_timing;
1205
154k
        switch (pt->pic_struct) {
1206
121k
        case H264_SEI_PIC_STRUCT_FRAME:
1207
121k
            break;
1208
3.07k
        case H264_SEI_PIC_STRUCT_TOP_FIELD:
1209
6.50k
        case H264_SEI_PIC_STRUCT_BOTTOM_FIELD:
1210
6.50k
            interlaced_frame = 1;
1211
6.50k
            break;
1212
5.86k
        case H264_SEI_PIC_STRUCT_TOP_BOTTOM:
1213
7.56k
        case H264_SEI_PIC_STRUCT_BOTTOM_TOP:
1214
7.56k
            if (FIELD_OR_MBAFF_PICTURE(h))
1215
5.73k
                interlaced_frame = 1;
1216
1.83k
            else
1217
                // try to flag soft telecine progressive
1218
1.83k
                interlaced_frame = !!h->prev_interlaced_frame;
1219
7.56k
            break;
1220
5.28k
        case H264_SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
1221
12.1k
        case H264_SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
1222
            /* Signal the possibility of telecined film externally
1223
             * (pic_struct 5,6). From these hints, let the applications
1224
             * decide if they apply deinterlacing. */
1225
12.1k
            out->repeat_pict = 1;
1226
12.1k
            break;
1227
1.32k
        case H264_SEI_PIC_STRUCT_FRAME_DOUBLING:
1228
1.32k
            out->repeat_pict = 2;
1229
1.32k
            break;
1230
5.41k
        case H264_SEI_PIC_STRUCT_FRAME_TRIPLING:
1231
5.41k
            out->repeat_pict = 4;
1232
5.41k
            break;
1233
154k
        }
1234
1235
154k
        if ((pt->ct_type & 3) &&
1236
9.67k
            pt->pic_struct <= H264_SEI_PIC_STRUCT_BOTTOM_TOP)
1237
3.92k
            interlaced_frame = ((pt->ct_type & (1 << 1)) != 0);
1238
2.29M
    } else {
1239
        /* Derive interlacing flag from used decoding process. */
1240
2.29M
        interlaced_frame = !!FIELD_OR_MBAFF_PICTURE(h);
1241
2.29M
    }
1242
2.45M
    h->prev_interlaced_frame = interlaced_frame;
1243
1244
2.45M
    if (cur->field_poc[0] != cur->field_poc[1]) {
1245
        /* Derive top_field_first from field pocs. */
1246
903k
        top_field_first = (cur->field_poc[0] < cur->field_poc[1]);
1247
1.54M
    } else {
1248
1.54M
        if (sps->pic_struct_present_flag && h->sei.picture_timing.present) {
1249
            /* Use picture timing SEI information. Even if it is a
1250
             * information of a past frame, better than nothing. */
1251
28.5k
            if (h->sei.picture_timing.pic_struct == H264_SEI_PIC_STRUCT_TOP_BOTTOM ||
1252
27.0k
                h->sei.picture_timing.pic_struct == H264_SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
1253
5.60k
                top_field_first = 1;
1254
1.52M
        } else if (interlaced_frame) {
1255
            /* Default to top field first when pic_struct_present_flag
1256
             * is not set but interlaced frame detected */
1257
711k
            top_field_first = 1;
1258
711k
        } // else
1259
            /* Most likely progressive */
1260
1.54M
    }
1261
1262
2.45M
    out->flags |= (AV_FRAME_FLAG_INTERLACED * interlaced_frame) |
1263
2.45M
                  (AV_FRAME_FLAG_TOP_FIELD_FIRST * top_field_first);
1264
1265
2.45M
    ret = ff_h2645_sei_to_frame(out, &h->sei.common, AV_CODEC_ID_H264, h->avctx,
1266
2.45M
                                &sps->vui, sps->bit_depth_luma, sps->bit_depth_chroma,
1267
2.45M
                                cur->poc + (unsigned)(h->poc_offset << 5));
1268
2.45M
    if (ret < 0)
1269
0
        return ret;
1270
1271
2.45M
    if (h->sei.picture_timing.timecode_cnt > 0) {
1272
28.6k
        uint32_t *tc_sd;
1273
28.6k
        char tcbuf[AV_TIMECODE_STR_SIZE];
1274
28.6k
        AVFrameSideData *tcside;
1275
28.6k
        ret = ff_frame_new_side_data(h->avctx, out, AV_FRAME_DATA_S12M_TIMECODE,
1276
28.6k
                                     sizeof(uint32_t)*4, &tcside);
1277
28.6k
        if (ret < 0)
1278
0
            return ret;
1279
1280
28.6k
        if (tcside) {
1281
28.6k
            tc_sd = (uint32_t*)tcside->data;
1282
28.6k
            tc_sd[0] = h->sei.picture_timing.timecode_cnt;
1283
1284
62.4k
            for (int i = 0; i < tc_sd[0]; i++) {
1285
33.7k
                int drop = h->sei.picture_timing.timecode[i].dropframe;
1286
33.7k
                int   hh = h->sei.picture_timing.timecode[i].hours;
1287
33.7k
                int   mm = h->sei.picture_timing.timecode[i].minutes;
1288
33.7k
                int   ss = h->sei.picture_timing.timecode[i].seconds;
1289
33.7k
                int   ff = h->sei.picture_timing.timecode[i].frame;
1290
1291
33.7k
                tc_sd[i + 1] = av_timecode_get_smpte(h->avctx->framerate, drop, hh, mm, ss, ff);
1292
33.7k
                av_timecode_make_smpte_tc_string2(tcbuf, h->avctx->framerate, tc_sd[i + 1], 0, 0);
1293
33.7k
                av_dict_set(&out->metadata, "timecode", tcbuf, 0);
1294
33.7k
            }
1295
28.6k
        }
1296
28.6k
        h->sei.picture_timing.timecode_cnt = 0;
1297
28.6k
    }
1298
1299
2.45M
    return 0;
1300
2.45M
}
1301
1302
static int h264_select_output_frame(H264Context *h)
1303
2.45M
{
1304
2.45M
    const SPS *sps = h->ps.sps;
1305
2.45M
    H264Picture *out = h->cur_pic_ptr;
1306
2.45M
    H264Picture *cur = h->cur_pic_ptr;
1307
2.45M
    int i, pics, out_of_order, out_idx;
1308
1309
2.45M
    cur->mmco_reset = h->mmco_reset;
1310
2.45M
    h->mmco_reset = 0;
1311
1312
2.45M
    if (sps->bitstream_restriction_flag ||
1313
2.15M
        h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
1314
298k
        h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
1315
298k
    }
1316
1317
41.0M
    for (i = 0; 1; i++) {
1318
41.0M
        if(i == H264_MAX_DPB_FRAMES || cur->poc < h->last_pocs[i]){
1319
2.45M
            if(i)
1320
2.44M
                h->last_pocs[i-1] = cur->poc;
1321
2.45M
            break;
1322
38.5M
        } else if(i) {
1323
36.1M
            h->last_pocs[i-1]= h->last_pocs[i];
1324
36.1M
        }
1325
41.0M
    }
1326
2.45M
    out_of_order = H264_MAX_DPB_FRAMES - i;
1327
2.45M
    if(   cur->f->pict_type == AV_PICTURE_TYPE_B
1328
1.80M
       || (h->last_pocs[H264_MAX_DPB_FRAMES-2] > INT_MIN && h->last_pocs[H264_MAX_DPB_FRAMES-1] - (int64_t)h->last_pocs[H264_MAX_DPB_FRAMES-2] > 2))
1329
751k
        out_of_order = FFMAX(out_of_order, 1);
1330
2.45M
    if (out_of_order == H264_MAX_DPB_FRAMES) {
1331
6.92k
        av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
1332
110k
        for (i = 1; i < H264_MAX_DPB_FRAMES; i++)
1333
103k
            h->last_pocs[i] = INT_MIN;
1334
6.92k
        h->last_pocs[0] = cur->poc;
1335
6.92k
        cur->mmco_reset = 1;
1336
2.44M
    } else if(h->avctx->has_b_frames < out_of_order && !sps->bitstream_restriction_flag){
1337
19.6k
        int loglevel = h->avctx->frame_num > 1 ? AV_LOG_WARNING : AV_LOG_VERBOSE;
1338
19.6k
        av_log(h->avctx, loglevel, "Increasing reorder buffer to %d\n", out_of_order);
1339
19.6k
        h->avctx->has_b_frames = out_of_order;
1340
19.6k
    }
1341
1342
2.45M
    pics = 0;
1343
7.57M
    while (h->delayed_pic[pics])
1344
5.12M
        pics++;
1345
1346
2.45M
    av_assert0(pics <= H264_MAX_DPB_FRAMES);
1347
1348
2.45M
    h->delayed_pic[pics++] = cur;
1349
2.45M
    if (cur->reference == 0)
1350
2.44M
        cur->reference = DELAYED_PIC_REF;
1351
1352
2.45M
    out     = h->delayed_pic[0];
1353
2.45M
    out_idx = 0;
1354
4.32M
    for (i = 1; h->delayed_pic[i] &&
1355
2.58M
                !(h->delayed_pic[i]->f->flags & AV_FRAME_FLAG_KEY) &&
1356
1.93M
                !h->delayed_pic[i]->mmco_reset;
1357
2.45M
         i++)
1358
1.87M
        if (h->delayed_pic[i]->poc < out->poc) {
1359
391k
            out     = h->delayed_pic[i];
1360
391k
            out_idx = i;
1361
391k
        }
1362
2.45M
    if (h->avctx->has_b_frames == 0 &&
1363
586k
        ((h->delayed_pic[0]->f->flags & AV_FRAME_FLAG_KEY) || h->delayed_pic[0]->mmco_reset))
1364
311k
        h->next_outputed_poc = INT_MIN;
1365
2.45M
    out_of_order = out->poc < h->next_outputed_poc;
1366
1367
2.45M
    if (out_of_order || pics > h->avctx->has_b_frames) {
1368
1.99M
        out->reference &= ~DELAYED_PIC_REF;
1369
8.20M
        for (i = out_idx; h->delayed_pic[i]; i++)
1370
6.21M
            h->delayed_pic[i] = h->delayed_pic[i + 1];
1371
1.99M
    }
1372
2.45M
    if (!out_of_order && pics > h->avctx->has_b_frames) {
1373
1.81M
        h->next_output_pic = out;
1374
1.81M
        if (out_idx == 0 && h->delayed_pic[0] && ((h->delayed_pic[0]->f->flags & AV_FRAME_FLAG_KEY) || h->delayed_pic[0]->mmco_reset)) {
1375
569k
            h->next_outputed_poc = INT_MIN;
1376
569k
        } else
1377
1.24M
            h->next_outputed_poc = out->poc;
1378
1379
        // We have reached an recovery point and all frames after it in
1380
        // display order are "recovered".
1381
1.81M
        h->frame_recovered |= out->recovered;
1382
1383
1.81M
        out->recovered |= h->frame_recovered & FRAME_RECOVERED_SEI;
1384
1385
1.81M
        if (!out->recovered) {
1386
507k
            if (!(h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) &&
1387
507k
                !(h->avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL)) {
1388
507k
                h->next_output_pic = NULL;
1389
507k
            } else {
1390
0
                out->f->flags |= AV_FRAME_FLAG_CORRUPT;
1391
0
            }
1392
507k
        }
1393
1.81M
    } else {
1394
633k
        av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
1395
633k
    }
1396
1397
2.45M
    return 0;
1398
2.45M
}
1399
1400
/* This function is called right after decoding the slice header for a first
1401
 * slice in a field (or a frame). It decides whether we are decoding a new frame
1402
 * or a second field in a pair and does the necessary setup.
1403
 */
1404
static int h264_field_start(H264Context *h, const H264SliceContext *sl,
1405
                            const H2645NAL *nal, int first_slice)
1406
2.52M
{
1407
2.52M
    int i;
1408
2.52M
    const SPS *sps;
1409
1410
2.52M
    int last_pic_structure, last_pic_droppable, ret;
1411
1412
2.52M
    ret = h264_init_ps(h, sl, first_slice);
1413
2.52M
    if (ret < 0)
1414
0
        return ret;
1415
1416
2.52M
    sps = h->ps.sps;
1417
1418
2.52M
    if (sps->bitstream_restriction_flag &&
1419
311k
        h->avctx->has_b_frames < sps->num_reorder_frames) {
1420
1.80k
        h->avctx->has_b_frames = sps->num_reorder_frames;
1421
1.80k
    }
1422
1423
2.52M
    last_pic_droppable   = h->droppable;
1424
2.52M
    last_pic_structure   = h->picture_structure;
1425
2.52M
    h->droppable         = (nal->ref_idc == 0);
1426
2.52M
    h->picture_structure = sl->picture_structure;
1427
1428
2.52M
    h->poc.frame_num        = sl->frame_num;
1429
2.52M
    h->poc.poc_lsb          = sl->poc_lsb;
1430
2.52M
    h->poc.delta_poc_bottom = sl->delta_poc_bottom;
1431
2.52M
    h->poc.delta_poc[0]     = sl->delta_poc[0];
1432
2.52M
    h->poc.delta_poc[1]     = sl->delta_poc[1];
1433
1434
2.52M
    if (nal->type == H264_NAL_IDR_SLICE)
1435
965k
        h->poc_offset = sl->idr_pic_id;
1436
1.56M
    else if (h->picture_intra_only)
1437
0
        h->poc_offset = 0;
1438
1439
    /* Shorten frame num gaps so we don't have to allocate reference
1440
     * frames just to throw them away */
1441
2.52M
    if (h->poc.frame_num != h->poc.prev_frame_num) {
1442
901k
        int unwrap_prev_frame_num = h->poc.prev_frame_num;
1443
901k
        int max_frame_num         = 1 << sps->log2_max_frame_num;
1444
1445
901k
        if (unwrap_prev_frame_num > h->poc.frame_num)
1446
120k
            unwrap_prev_frame_num -= max_frame_num;
1447
1448
901k
        if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
1449
513k
            unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
1450
513k
            if (unwrap_prev_frame_num < 0)
1451
103k
                unwrap_prev_frame_num += max_frame_num;
1452
1453
513k
            h->poc.prev_frame_num = unwrap_prev_frame_num;
1454
513k
        }
1455
901k
    }
1456
1457
    /* See if we have a decoded first field looking for a pair...
1458
     * Here, we're using that to see if we should mark previously
1459
     * decode frames as "finished".
1460
     * We have to do that before the "dummy" in-between frame allocation,
1461
     * since that can modify h->cur_pic_ptr. */
1462
2.52M
    if (h->first_field) {
1463
652k
        int last_field = last_pic_structure == PICT_BOTTOM_FIELD;
1464
652k
        av_assert0(h->cur_pic_ptr);
1465
652k
        av_assert0(h->cur_pic_ptr->f->buf[0]);
1466
652k
        assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1467
1468
        /* Mark old field/frame as completed */
1469
652k
        if (h->cur_pic_ptr->tf.owner[last_field] == h->avctx) {
1470
652k
            ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, last_field);
1471
652k
        }
1472
1473
        /* figure out if we have a complementary field pair */
1474
652k
        if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1475
            /* Previous field is unmatched. Don't display it, but let it
1476
             * remain for reference if marked as such. */
1477
633k
            if (last_pic_structure != PICT_FRAME) {
1478
633k
                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1479
633k
                                          last_pic_structure == PICT_TOP_FIELD);
1480
633k
            }
1481
633k
        } else {
1482
19.1k
            if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1483
                /* This and previous field were reference, but had
1484
                 * different frame_nums. Consider this field first in
1485
                 * pair. Throw away previous field except for reference
1486
                 * purposes. */
1487
9.63k
                if (last_pic_structure != PICT_FRAME) {
1488
9.63k
                    ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1489
9.63k
                                              last_pic_structure == PICT_TOP_FIELD);
1490
9.63k
                }
1491
9.63k
            } else {
1492
                /* Second field in complementary pair */
1493
9.53k
                if (!((last_pic_structure   == PICT_TOP_FIELD &&
1494
6.31k
                       h->picture_structure == PICT_BOTTOM_FIELD) ||
1495
3.22k
                      (last_pic_structure   == PICT_BOTTOM_FIELD &&
1496
3.22k
                       h->picture_structure == PICT_TOP_FIELD))) {
1497
0
                    av_log(h->avctx, AV_LOG_ERROR,
1498
0
                           "Invalid field mode combination %d/%d\n",
1499
0
                           last_pic_structure, h->picture_structure);
1500
0
                    h->picture_structure = last_pic_structure;
1501
0
                    h->droppable         = last_pic_droppable;
1502
0
                    return AVERROR_INVALIDDATA;
1503
9.53k
                } else if (last_pic_droppable != h->droppable) {
1504
504
                    avpriv_request_sample(h->avctx,
1505
504
                                          "Found reference and non-reference fields in the same frame, which");
1506
504
                    h->picture_structure = last_pic_structure;
1507
504
                    h->droppable         = last_pic_droppable;
1508
504
                    return AVERROR_PATCHWELCOME;
1509
504
                }
1510
9.53k
            }
1511
19.1k
        }
1512
652k
    }
1513
1514
4.04M
    while (h->poc.frame_num != h->poc.prev_frame_num && !h->first_field &&
1515
2.33M
           h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
1516
1.52M
        const H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
1517
1.52M
        av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
1518
1.52M
               h->poc.frame_num, h->poc.prev_frame_num);
1519
1.52M
        if (!sps->gaps_in_frame_num_allowed_flag)
1520
22.2M
            for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
1521
20.9M
                h->last_pocs[i] = INT_MIN;
1522
1.52M
        ret = h264_frame_start(h);
1523
1.52M
        if (ret < 0) {
1524
3.14k
            h->first_field = 0;
1525
3.14k
            return ret;
1526
3.14k
        }
1527
1528
1.52M
        h->poc.prev_frame_num++;
1529
1.52M
        h->poc.prev_frame_num        %= 1 << sps->log2_max_frame_num;
1530
1.52M
        h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
1531
1.52M
        h->cur_pic_ptr->invalid_gap = !sps->gaps_in_frame_num_allowed_flag;
1532
1.52M
        ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
1533
1.52M
        ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
1534
1535
1.52M
        h->explicit_ref_marking = 0;
1536
1.52M
        ret = ff_h264_execute_ref_pic_marking(h);
1537
1.52M
        if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1538
264
            return ret;
1539
        /* Error concealment: If a ref is missing, copy the previous ref
1540
         * in its place.
1541
         * FIXME: Avoiding a memcpy would be nice, but ref handling makes
1542
         * many assumptions about there being no actual duplicates.
1543
         * FIXME: This does not copy padding for out-of-frame motion
1544
         * vectors.  Given we are concealing a lost frame, this probably
1545
         * is not noticeable by comparison, but it should be fixed. */
1546
1.52M
        if (h->short_ref_count) {
1547
1.50M
            int c[4] = {
1548
1.50M
                1<<(h->ps.sps->bit_depth_luma-1),
1549
1.50M
                1<<(h->ps.sps->bit_depth_chroma-1),
1550
1.50M
                1<<(h->ps.sps->bit_depth_chroma-1),
1551
1.50M
                -1
1552
1.50M
            };
1553
1554
1.50M
            if (prev &&
1555
1.14M
                h->short_ref[0]->f->width == prev->f->width &&
1556
1.14M
                h->short_ref[0]->f->height == prev->f->height &&
1557
1.14M
                h->short_ref[0]->f->format == prev->f->format) {
1558
1.14M
                ff_thread_await_progress(&prev->tf, INT_MAX, 0);
1559
1.14M
                if (prev->field_picture)
1560
166k
                    ff_thread_await_progress(&prev->tf, INT_MAX, 1);
1561
1.14M
                ff_thread_release_ext_buffer(&h->short_ref[0]->tf);
1562
1.14M
                h->short_ref[0]->tf.f = h->short_ref[0]->f;
1563
1.14M
                ret = ff_thread_ref_frame(&h->short_ref[0]->tf, &prev->tf);
1564
1.14M
                if (ret < 0)
1565
0
                    return ret;
1566
1.14M
                h->short_ref[0]->poc = prev->poc + 2U;
1567
1.14M
                h->short_ref[0]->gray = prev->gray;
1568
1.14M
                ff_thread_report_progress(&h->short_ref[0]->tf, INT_MAX, 0);
1569
1.14M
                if (h->short_ref[0]->field_picture)
1570
174k
                    ff_thread_report_progress(&h->short_ref[0]->tf, INT_MAX, 1);
1571
1.14M
            } else if (!h->frame_recovered) {
1572
287k
                if (!h->avctx->hwaccel)
1573
287k
                    color_frame(h->short_ref[0]->f, c);
1574
287k
                h->short_ref[0]->gray = 1;
1575
287k
            }
1576
1.50M
            h->short_ref[0]->frame_num = h->poc.prev_frame_num;
1577
1.50M
        }
1578
1.52M
    }
1579
1580
    /* See if we have a decoded first field looking for a pair...
1581
     * We're using that to see whether to continue decoding in that
1582
     * frame, or to allocate a new one. */
1583
2.52M
    if (h->first_field) {
1584
651k
        av_assert0(h->cur_pic_ptr);
1585
651k
        av_assert0(h->cur_pic_ptr->f->buf[0]);
1586
651k
        assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
1587
1588
        /* figure out if we have a complementary field pair */
1589
651k
        if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
1590
            /* Previous field is unmatched. Don't display it, but let it
1591
             * remain for reference if marked as such. */
1592
633k
            h->missing_fields ++;
1593
633k
            h->cur_pic_ptr = NULL;
1594
633k
            h->first_field = FIELD_PICTURE(h);
1595
633k
        } else {
1596
18.6k
            h->missing_fields = 0;
1597
18.6k
            if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
1598
9.63k
                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
1599
9.63k
                                          h->picture_structure==PICT_BOTTOM_FIELD);
1600
                /* This and the previous field had different frame_nums.
1601
                 * Consider this field first in pair. Throw away previous
1602
                 * one except for reference purposes. */
1603
9.63k
                h->first_field = 1;
1604
9.63k
                h->cur_pic_ptr = NULL;
1605
9.63k
            } else if (h->cur_pic_ptr->reference & DELAYED_PIC_REF) {
1606
                /* This frame was already output, we cannot draw into it
1607
                 * anymore.
1608
                 */
1609
905
                h->first_field = 1;
1610
905
                h->cur_pic_ptr = NULL;
1611
8.12k
            } else {
1612
                /* Second field in complementary pair */
1613
8.12k
                h->first_field = 0;
1614
8.12k
            }
1615
18.6k
        }
1616
1.87M
    } else {
1617
        /* Frame or first field in a potentially complementary pair */
1618
1.87M
        h->first_field = FIELD_PICTURE(h);
1619
1.87M
    }
1620
1621
2.52M
    if (!FIELD_PICTURE(h) || h->first_field) {
1622
2.51M
        if (h264_frame_start(h) < 0) {
1623
3.25k
            h->first_field = 0;
1624
3.25k
            return AVERROR_INVALIDDATA;
1625
3.25k
        }
1626
2.51M
    } else {
1627
8.12k
        int field = h->picture_structure == PICT_BOTTOM_FIELD;
1628
8.12k
        release_unused_pictures(h, 0);
1629
8.12k
        h->cur_pic_ptr->tf.owner[field] = h->avctx;
1630
8.12k
    }
1631
    /* Some macroblocks can be accessed before they're available in case
1632
    * of lost slices, MBAFF or threading. */
1633
2.52M
    if (FIELD_PICTURE(h)) {
1634
19.1M
        for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
1635
18.3M
            memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
1636
1.74M
    } else {
1637
1.74M
        memset(h->slice_table, -1,
1638
1.74M
            (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
1639
1.74M
    }
1640
1641
2.52M
    ret = ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
1642
2.52M
                     h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
1643
2.52M
    if (ret < 0)
1644
1.66k
        return ret;
1645
1646
2.51M
    memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
1647
2.51M
    h->nb_mmco = sl->nb_mmco;
1648
2.51M
    h->explicit_ref_marking = sl->explicit_ref_marking;
1649
1650
2.51M
    h->picture_idr = nal->type == H264_NAL_IDR_SLICE;
1651
1652
2.51M
    if (h->sei.recovery_point.recovery_frame_cnt >= 0) {
1653
285k
        const int sei_recovery_frame_cnt = h->sei.recovery_point.recovery_frame_cnt;
1654
1655
285k
        if (h->poc.frame_num != sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
1656
266k
            h->valid_recovery_point = 1;
1657
1658
285k
        if (   h->recovery_frame < 0
1659
208k
            || av_zero_extend(h->recovery_frame - h->poc.frame_num, h->ps.sps->log2_max_frame_num) > sei_recovery_frame_cnt) {
1660
208k
            h->recovery_frame = av_zero_extend(h->poc.frame_num + sei_recovery_frame_cnt, h->ps.sps->log2_max_frame_num);
1661
1662
208k
            if (!h->valid_recovery_point)
1663
6.33k
                h->recovery_frame = h->poc.frame_num;
1664
208k
        }
1665
285k
    }
1666
1667
2.51M
    h->cur_pic_ptr->f->flags |= AV_FRAME_FLAG_KEY * !!(nal->type == H264_NAL_IDR_SLICE);
1668
1669
2.51M
    if (nal->type == H264_NAL_IDR_SLICE) {
1670
960k
        h->cur_pic_ptr->recovered |= FRAME_RECOVERED_IDR;
1671
        // If we have an IDR, all frames after it in decoded order are
1672
        // "recovered".
1673
960k
        h->frame_recovered |= FRAME_RECOVERED_IDR;
1674
960k
    }
1675
1676
2.51M
    if (h->recovery_frame == h->poc.frame_num && nal->ref_idc) {
1677
194k
        h->recovery_frame = -1;
1678
194k
        h->cur_pic_ptr->recovered |= FRAME_RECOVERED_SEI;
1679
194k
    }
1680
1681
2.51M
#if 1
1682
2.51M
    h->cur_pic_ptr->recovered |= h->frame_recovered;
1683
#else
1684
    h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
1685
#endif
1686
1687
    /* Set the frame properties/side data. Only done for the second field in
1688
     * field coded frames, since some SEI information is present for each field
1689
     * and is merged by the SEI parsing code. */
1690
2.51M
    if (!FIELD_PICTURE(h) || !h->first_field || h->missing_fields > 1) {
1691
2.45M
        ret = h264_export_frame_props(h);
1692
2.45M
        if (ret < 0)
1693
104
            return ret;
1694
1695
2.45M
        ret = h264_select_output_frame(h);
1696
2.45M
        if (ret < 0)
1697
0
            return ret;
1698
2.45M
    }
1699
1700
2.51M
    return 0;
1701
2.51M
}
1702
1703
static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
1704
                                   const H2645NAL *nal)
1705
4.78M
{
1706
4.78M
    const SPS *sps;
1707
4.78M
    const PPS *pps;
1708
4.78M
    int ret;
1709
4.78M
    unsigned int slice_type, tmp, i;
1710
4.78M
    int field_pic_flag, bottom_field_flag;
1711
4.78M
    int first_slice = sl == h->slice_ctx && !h->current_slice;
1712
4.78M
    int picture_structure;
1713
1714
4.78M
    if (first_slice)
1715
2.97M
        av_assert0(!h->setup_finished);
1716
1717
4.78M
    sl->first_mb_addr = get_ue_golomb_long(&sl->gb);
1718
1719
4.78M
    slice_type = get_ue_golomb_31(&sl->gb);
1720
4.78M
    if (slice_type > 9) {
1721
161k
        av_log(h->avctx, AV_LOG_ERROR,
1722
161k
               "slice type %d too large at %d\n",
1723
161k
               slice_type, sl->first_mb_addr);
1724
161k
        return AVERROR_INVALIDDATA;
1725
161k
    }
1726
4.62M
    if (slice_type > 4) {
1727
2.11M
        slice_type -= 5;
1728
2.11M
        sl->slice_type_fixed = 1;
1729
2.11M
    } else
1730
2.51M
        sl->slice_type_fixed = 0;
1731
1732
4.62M
    slice_type         = ff_h264_golomb_to_pict_type[slice_type];
1733
4.62M
    sl->slice_type     = slice_type;
1734
4.62M
    sl->slice_type_nos = slice_type & 3;
1735
1736
4.62M
    if (nal->type  == H264_NAL_IDR_SLICE &&
1737
1.40M
        sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1738
80.5k
        av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
1739
80.5k
        return AVERROR_INVALIDDATA;
1740
80.5k
    }
1741
1742
4.54M
    sl->pps_id = get_ue_golomb(&sl->gb);
1743
4.54M
    if (sl->pps_id >= MAX_PPS_COUNT) {
1744
44.9k
        av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
1745
44.9k
        return AVERROR_INVALIDDATA;
1746
44.9k
    }
1747
4.49M
    if (!h->ps.pps_list[sl->pps_id]) {
1748
170k
        av_log(h->avctx, AV_LOG_ERROR,
1749
170k
               "non-existing PPS %u referenced\n",
1750
170k
               sl->pps_id);
1751
170k
        return AVERROR_INVALIDDATA;
1752
170k
    }
1753
4.32M
    pps = h->ps.pps_list[sl->pps_id];
1754
4.32M
    sps = pps->sps;
1755
1756
4.32M
    sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
1757
4.32M
    if (!first_slice) {
1758
1.65M
        if (h->poc.frame_num != sl->frame_num) {
1759
664k
            av_log(h->avctx, AV_LOG_ERROR, "Frame num change from %d to %d\n",
1760
664k
                   h->poc.frame_num, sl->frame_num);
1761
664k
            return AVERROR_INVALIDDATA;
1762
664k
        }
1763
1.65M
    }
1764
1765
3.66M
    sl->mb_mbaff       = 0;
1766
1767
3.66M
    if (sps->frame_mbs_only_flag) {
1768
1.19M
        picture_structure = PICT_FRAME;
1769
2.46M
    } else {
1770
2.46M
        if (!sps->direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
1771
72.7k
            av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
1772
72.7k
            return -1;
1773
72.7k
        }
1774
2.39M
        field_pic_flag = get_bits1(&sl->gb);
1775
2.39M
        if (field_pic_flag) {
1776
1.07M
            bottom_field_flag = get_bits1(&sl->gb);
1777
1.07M
            picture_structure = PICT_TOP_FIELD + bottom_field_flag;
1778
1.32M
        } else {
1779
1.32M
            picture_structure = PICT_FRAME;
1780
1.32M
        }
1781
2.39M
    }
1782
3.59M
    sl->picture_structure      = picture_structure;
1783
3.59M
    sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
1784
1785
3.59M
    if (picture_structure == PICT_FRAME) {
1786
2.51M
        sl->curr_pic_num = sl->frame_num;
1787
2.51M
        sl->max_pic_num  = 1 << sps->log2_max_frame_num;
1788
2.51M
    } else {
1789
1.07M
        sl->curr_pic_num = 2 * sl->frame_num + 1;
1790
1.07M
        sl->max_pic_num  = 1 << (sps->log2_max_frame_num + 1);
1791
1.07M
    }
1792
1793
3.59M
    if (nal->type == H264_NAL_IDR_SLICE) {
1794
1.12M
        unsigned idr_pic_id = get_ue_golomb_long(&sl->gb);
1795
1.12M
        if (idr_pic_id < 65536) {
1796
950k
            sl->idr_pic_id = idr_pic_id;
1797
950k
        } else
1798
175k
            av_log(h->avctx, AV_LOG_WARNING, "idr_pic_id is invalid\n");
1799
1.12M
    }
1800
1801
3.59M
    sl->poc_lsb = 0;
1802
3.59M
    sl->delta_poc_bottom = 0;
1803
3.59M
    if (sps->poc_type == 0) {
1804
2.38M
        sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
1805
1806
2.38M
        if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1807
257k
            sl->delta_poc_bottom = get_se_golomb(&sl->gb);
1808
2.38M
    }
1809
1810
3.59M
    sl->delta_poc[0] = sl->delta_poc[1] = 0;
1811
3.59M
    if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
1812
640k
        sl->delta_poc[0] = get_se_golomb(&sl->gb);
1813
1814
640k
        if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1815
132k
            sl->delta_poc[1] = get_se_golomb(&sl->gb);
1816
640k
    }
1817
1818
3.59M
    sl->redundant_pic_count = 0;
1819
3.59M
    if (pps->redundant_pic_cnt_present)
1820
374k
        sl->redundant_pic_count = get_ue_golomb(&sl->gb);
1821
1822
3.59M
    if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
1823
941k
        sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
1824
1825
3.59M
    ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
1826
3.59M
                                  &sl->gb, pps, sl->slice_type_nos,
1827
3.59M
                                  picture_structure, h->avctx);
1828
3.59M
    if (ret < 0)
1829
50.1k
        return ret;
1830
1831
3.54M
    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
1832
2.31M
       ret = ff_h264_decode_ref_pic_list_reordering(sl, h->avctx);
1833
2.31M
       if (ret < 0) {
1834
288k
           sl->ref_count[1] = sl->ref_count[0] = 0;
1835
288k
           return ret;
1836
288k
       }
1837
2.31M
    }
1838
1839
3.25M
    sl->pwt.use_weight = 0;
1840
9.75M
    for (i = 0; i < 2; i++) {
1841
6.50M
        sl->pwt.luma_weight_flag[i]   = 0;
1842
6.50M
        sl->pwt.chroma_weight_flag[i] = 0;
1843
6.50M
    }
1844
3.25M
    if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
1845
2.50M
        (pps->weighted_bipred_idc == 1 &&
1846
809k
         sl->slice_type_nos == AV_PICTURE_TYPE_B)) {
1847
809k
        ret = ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
1848
809k
                                  sl->slice_type_nos, &sl->pwt,
1849
809k
                                  picture_structure, h->avctx);
1850
809k
        if (ret < 0)
1851
100k
            return ret;
1852
809k
    }
1853
1854
3.15M
    sl->explicit_ref_marking = 0;
1855
3.15M
    if (nal->ref_idc) {
1856
2.02M
        ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, h->avctx);
1857
2.02M
        if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1858
1.56k
            return AVERROR_INVALIDDATA;
1859
2.02M
    }
1860
1861
3.14M
    if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1862
1.34M
        tmp = get_ue_golomb_31(&sl->gb);
1863
1.34M
        if (tmp > 2) {
1864
161k
            av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
1865
161k
            return AVERROR_INVALIDDATA;
1866
161k
        }
1867
1.18M
        sl->cabac_init_idc = tmp;
1868
1.18M
    }
1869
1870
2.98M
    sl->last_qscale_diff = 0;
1871
2.98M
    tmp = pps->init_qp + (unsigned)get_se_golomb(&sl->gb);
1872
2.98M
    if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
1873
86.6k
        av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
1874
86.6k
        return AVERROR_INVALIDDATA;
1875
86.6k
    }
1876
2.90M
    sl->qscale       = tmp;
1877
2.90M
    sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
1878
2.90M
    sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
1879
    // FIXME qscale / qp ... stuff
1880
2.90M
    if (sl->slice_type == AV_PICTURE_TYPE_SP)
1881
274k
        get_bits1(&sl->gb); /* sp_for_switch_flag */
1882
2.90M
    if (sl->slice_type == AV_PICTURE_TYPE_SP ||
1883
2.62M
        sl->slice_type == AV_PICTURE_TYPE_SI)
1884
307k
        get_se_golomb(&sl->gb); /* slice_qs_delta */
1885
1886
2.90M
    sl->deblocking_filter     = 1;
1887
2.90M
    sl->slice_alpha_c0_offset = 0;
1888
2.90M
    sl->slice_beta_offset     = 0;
1889
2.90M
    if (pps->deblocking_filter_parameters_present) {
1890
1.01M
        tmp = get_ue_golomb_31(&sl->gb);
1891
1.01M
        if (tmp > 2) {
1892
80.1k
            av_log(h->avctx, AV_LOG_ERROR,
1893
80.1k
                   "deblocking_filter_idc %u out of range\n", tmp);
1894
80.1k
            return AVERROR_INVALIDDATA;
1895
80.1k
        }
1896
939k
        sl->deblocking_filter = tmp;
1897
939k
        if (sl->deblocking_filter < 2)
1898
867k
            sl->deblocking_filter ^= 1;  // 1<->0
1899
1900
939k
        if (sl->deblocking_filter) {
1901
876k
            int slice_alpha_c0_offset_div2 = get_se_golomb(&sl->gb);
1902
876k
            int slice_beta_offset_div2     = get_se_golomb(&sl->gb);
1903
876k
            if (slice_alpha_c0_offset_div2 >  6 ||
1904
868k
                slice_alpha_c0_offset_div2 < -6 ||
1905
861k
                slice_beta_offset_div2 >  6     ||
1906
847k
                slice_beta_offset_div2 < -6) {
1907
31.4k
                av_log(h->avctx, AV_LOG_ERROR,
1908
31.4k
                       "deblocking filter parameters %d %d out of range\n",
1909
31.4k
                       slice_alpha_c0_offset_div2, slice_beta_offset_div2);
1910
31.4k
                return AVERROR_INVALIDDATA;
1911
31.4k
            }
1912
845k
            sl->slice_alpha_c0_offset = slice_alpha_c0_offset_div2 * 2;
1913
845k
            sl->slice_beta_offset     = slice_beta_offset_div2 * 2;
1914
845k
        }
1915
939k
    }
1916
1917
2.79M
    return 0;
1918
2.90M
}
1919
1920
/* do all the per-slice initialization needed before we can start decoding the
1921
 * actual MBs */
1922
static int h264_slice_init(H264Context *h, H264SliceContext *sl,
1923
                           const H2645NAL *nal)
1924
2.58M
{
1925
2.58M
    int i, j, ret = 0;
1926
1927
2.58M
    if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {
1928
538
        av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");
1929
538
        return AVERROR_INVALIDDATA;
1930
538
    }
1931
1932
2.58M
    av_assert1(h->mb_num == h->mb_width * h->mb_height);
1933
2.58M
    if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
1934
2.50M
        sl->first_mb_addr >= h->mb_num) {
1935
74.5k
        av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
1936
74.5k
        return AVERROR_INVALIDDATA;
1937
74.5k
    }
1938
2.50M
    sl->resync_mb_x = sl->mb_x =  sl->first_mb_addr % h->mb_width;
1939
2.50M
    sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
1940
2.50M
                                 FIELD_OR_MBAFF_PICTURE(h);
1941
2.50M
    if (h->picture_structure == PICT_BOTTOM_FIELD)
1942
197k
        sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
1943
2.50M
    av_assert1(sl->mb_y < h->mb_height);
1944
1945
2.50M
    ret = ff_h264_build_ref_list(h, sl);
1946
2.50M
    if (ret < 0)
1947
128k
        return ret;
1948
1949
2.37M
    if (h->ps.pps->weighted_bipred_idc == 2 &&
1950
965k
        sl->slice_type_nos == AV_PICTURE_TYPE_B) {
1951
488k
        implicit_weight_table(h, sl, -1);
1952
488k
        if (FRAME_MBAFF(h)) {
1953
186k
            implicit_weight_table(h, sl, 0);
1954
186k
            implicit_weight_table(h, sl, 1);
1955
186k
        }
1956
488k
    }
1957
1958
2.37M
    if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
1959
306k
        ff_h264_direct_dist_scale_factor(h, sl);
1960
2.37M
    ff_h264_direct_ref_list_init(h, sl);
1961
1962
2.37M
    if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
1963
2.37M
        (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
1964
0
         h->nal_unit_type != H264_NAL_IDR_SLICE) ||
1965
2.37M
        (h->avctx->skip_loop_filter >= AVDISCARD_NONINTRA &&
1966
0
         sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
1967
2.37M
        (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&
1968
0
         sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
1969
2.37M
        (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
1970
0
         nal->ref_idc == 0))
1971
0
        sl->deblocking_filter = 0;
1972
1973
2.37M
    if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
1974
0
        if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
1975
            /* Cheat slightly for speed:
1976
             * Do not bother to deblock across slices. */
1977
0
            sl->deblocking_filter = 2;
1978
0
        } else {
1979
0
            h->postpone_filter = 1;
1980
0
        }
1981
0
    }
1982
2.37M
    sl->qp_thresh = 15 -
1983
2.37M
                   FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
1984
2.37M
                   FFMAX3(0,
1985
2.37M
                          h->ps.pps->chroma_qp_index_offset[0],
1986
2.37M
                          h->ps.pps->chroma_qp_index_offset[1]) +
1987
2.37M
                   6 * (h->ps.sps->bit_depth_luma - 8);
1988
1989
    // slice_table is uint16_t initialized to 0xFFFF as a sentinel.
1990
2.37M
    if (h->current_slice >= 0xFFFE) {
1991
0
        av_log(h->avctx, AV_LOG_ERROR, "Too many slices (%d)\n", h->current_slice + 1);
1992
0
        return AVERROR_PATCHWELCOME;
1993
0
    }
1994
1995
2.37M
    sl->slice_num       = ++h->current_slice;
1996
1997
2.37M
    if (sl->slice_num)
1998
2.37M
        h->slice_row[(sl->slice_num-1)&(MAX_SLICES-1)]= sl->resync_mb_y;
1999
2.37M
    if (   h->slice_row[sl->slice_num&(MAX_SLICES-1)] + 3 >= sl->resync_mb_y
2000
2.34M
        && h->slice_row[sl->slice_num&(MAX_SLICES-1)] <= sl->resync_mb_y
2001
2.30M
        && sl->slice_num >= MAX_SLICES) {
2002
        //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
2003
17.8k
        av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", sl->slice_num, MAX_SLICES);
2004
17.8k
    }
2005
2006
7.13M
    for (j = 0; j < 2; j++) {
2007
4.75M
        int id_list[16];
2008
4.75M
        int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
2009
80.8M
        for (i = 0; i < 16; i++) {
2010
76.0M
            id_list[i] = 60;
2011
76.0M
            if (j < sl->list_count && i < sl->ref_count[j] &&
2012
7.40M
                sl->ref_list[j][i].parent->f->buf[0]) {
2013
7.40M
                int k;
2014
7.40M
                const AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
2015
8.12M
                for (k = 0; k < h->short_ref_count; k++)
2016
6.68M
                    if (h->short_ref[k]->f->buf[0]->buffer == buf) {
2017
5.97M
                        id_list[i] = k;
2018
5.97M
                        break;
2019
5.97M
                    }
2020
8.48M
                for (k = 0; k < h->long_ref_count; k++)
2021
2.37M
                    if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
2022
1.30M
                        id_list[i] = h->short_ref_count + k;
2023
1.30M
                        break;
2024
1.30M
                    }
2025
7.40M
            }
2026
76.0M
        }
2027
2028
4.75M
        ref2frm[0] =
2029
4.75M
        ref2frm[1] = -1;
2030
80.8M
        for (i = 0; i < 16; i++)
2031
76.0M
            ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
2032
4.75M
        ref2frm[18 + 0] =
2033
4.75M
        ref2frm[18 + 1] = -1;
2034
156M
        for (i = 16; i < 48; i++)
2035
152M
            ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
2036
152M
                             (sl->ref_list[j][i].reference & 3);
2037
4.75M
    }
2038
2039
2.37M
    if (sl->slice_type_nos == AV_PICTURE_TYPE_I) {
2040
988k
        h->cur_pic_ptr->gray = 0;
2041
988k
        h->non_gray = 1;
2042
1.38M
    } else {
2043
1.38M
        int gray = 0;
2044
3.42M
        for (j = 0; j < sl->list_count; j++) {
2045
9.78M
            for (i = 0; i < sl->ref_count[j]; i++) {
2046
7.74M
                gray |= sl->ref_list[j][i].parent->gray;
2047
7.74M
            }
2048
2.03M
        }
2049
1.38M
        h->cur_pic_ptr->gray = gray;
2050
1.38M
    }
2051
2052
2.37M
    if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
2053
0
        av_log(h->avctx, AV_LOG_DEBUG,
2054
0
               "slice:%d %c mb:%d %c%s%s frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
2055
0
               sl->slice_num,
2056
0
               (h->picture_structure == PICT_FRAME ? 'F' : h->picture_structure == PICT_TOP_FIELD ? 'T' : 'B'),
2057
0
               sl->mb_y * h->mb_width + sl->mb_x,
2058
0
               av_get_picture_type_char(sl->slice_type),
2059
0
               sl->slice_type_fixed ? " fix" : "",
2060
0
               nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",
2061
0
               h->poc.frame_num,
2062
0
               h->cur_pic_ptr->field_poc[0],
2063
0
               h->cur_pic_ptr->field_poc[1],
2064
0
               sl->ref_count[0], sl->ref_count[1],
2065
0
               sl->qscale,
2066
0
               sl->deblocking_filter,
2067
0
               sl->slice_alpha_c0_offset, sl->slice_beta_offset,
2068
0
               sl->pwt.use_weight,
2069
0
               sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
2070
0
               sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
2071
0
    }
2072
2073
2.37M
    return 0;
2074
2.37M
}
2075
2076
int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)
2077
4.78M
{
2078
4.78M
    H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
2079
4.78M
    int first_slice = sl == h->slice_ctx && !h->current_slice;
2080
4.78M
    int ret;
2081
2082
4.78M
    sl->gb = nal->gb;
2083
2084
4.78M
    ret = h264_slice_header_parse(h, sl, nal);
2085
4.78M
    if (ret < 0)
2086
1.99M
        return ret;
2087
2088
    // discard redundant pictures
2089
2.79M
    if (sl->redundant_pic_count > 0) {
2090
77.0k
        sl->ref_count[0] = sl->ref_count[1] = 0;
2091
77.0k
        return 0;
2092
77.0k
    }
2093
2094
2.71M
    if (sl->first_mb_addr == 0 || !h->current_slice) {
2095
2.64M
        if (h->setup_finished) {
2096
0
            av_log(h->avctx, AV_LOG_ERROR, "Too many fields\n");
2097
0
            return AVERROR_INVALIDDATA;
2098
0
        }
2099
2.64M
    }
2100
2101
2.71M
    if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
2102
2.23M
        if (h->current_slice) {
2103
            // this slice starts a new field
2104
            // first decode any pending queued slices
2105
755k
            if (h->nb_slice_ctx_queued) {
2106
0
                H264SliceContext tmp_ctx;
2107
2108
0
                ret = ff_h264_execute_decode_slices(h);
2109
0
                if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
2110
0
                    return ret;
2111
2112
0
                memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));
2113
0
                memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));
2114
0
                memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));
2115
0
                sl = h->slice_ctx;
2116
0
            }
2117
2118
755k
            if (h->cur_pic_ptr && FIELD_PICTURE(h) && h->first_field) {
2119
379k
                ret = ff_h264_field_end(h, h->slice_ctx, 1);
2120
379k
                if (ret < 0)
2121
34
                    return ret;
2122
379k
            } else if (h->cur_pic_ptr && !FIELD_PICTURE(h) && !h->first_field && h->nal_unit_type  == H264_NAL_IDR_SLICE) {
2123
295k
                av_log(h->avctx, AV_LOG_WARNING, "Broken frame packetizing\n");
2124
295k
                ret = ff_h264_field_end(h, h->slice_ctx, 1);
2125
295k
                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
2126
295k
                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
2127
295k
                h->cur_pic_ptr = NULL;
2128
295k
                if (ret < 0)
2129
20
                    return ret;
2130
295k
            } else
2131
80.6k
                return AVERROR_INVALIDDATA;
2132
755k
        }
2133
2134
2.15M
        if (!h->first_field) {
2135
1.51M
            if (h->cur_pic_ptr && !h->droppable) {
2136
12.7k
                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
2137
12.7k
                                          h->picture_structure == PICT_BOTTOM_FIELD);
2138
12.7k
            }
2139
1.51M
            h->cur_pic_ptr = NULL;
2140
1.51M
        }
2141
2.15M
    }
2142
2143
2.63M
    if (!h->current_slice)
2144
2.56M
        av_assert0(sl == h->slice_ctx);
2145
2146
2.63M
    if (h->current_slice == 0 && !h->first_field) {
2147
1.89M
        if (
2148
1.89M
            (h->avctx->skip_frame >= AVDISCARD_NONREF && !h->nal_ref_idc) ||
2149
1.89M
            (h->avctx->skip_frame >= AVDISCARD_BIDIR  && sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
2150
1.89M
            (h->avctx->skip_frame >= AVDISCARD_NONINTRA && sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
2151
1.88M
            (h->avctx->skip_frame >= AVDISCARD_NONKEY && h->nal_unit_type != H264_NAL_IDR_SLICE && h->sei.recovery_point.recovery_frame_cnt < 0) ||
2152
1.88M
            h->avctx->skip_frame >= AVDISCARD_ALL) {
2153
9.03k
            return 0;
2154
9.03k
        }
2155
1.89M
    }
2156
2157
2.62M
    if (!first_slice) {
2158
743k
        const PPS *pps = h->ps.pps_list[sl->pps_id];
2159
2160
743k
        if (h->ps.pps->sps_id != pps->sps_id ||
2161
742k
            h->ps.pps->transform_8x8_mode != pps->transform_8x8_mode /*||
2162
743k
            (h->setup_finished && h->ps.pps != pps)*/) {
2163
10.0k
            av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
2164
10.0k
            return AVERROR_INVALIDDATA;
2165
10.0k
        }
2166
733k
        if (h->ps.sps != pps->sps) {
2167
21.9k
            av_log(h->avctx, AV_LOG_ERROR,
2168
21.9k
               "SPS changed in the middle of the frame\n");
2169
21.9k
            return AVERROR_INVALIDDATA;
2170
21.9k
        }
2171
733k
    }
2172
2173
2.59M
    if (h->current_slice == 0) {
2174
2.52M
        ret = h264_field_start(h, sl, nal, first_slice);
2175
2.52M
        if (ret < 0)
2176
8.93k
            return ret;
2177
2.52M
    } else {
2178
63.5k
        if (h->picture_structure != sl->picture_structure ||
2179
62.3k
            h->droppable         != (nal->ref_idc == 0)) {
2180
1.96k
            av_log(h->avctx, AV_LOG_ERROR,
2181
1.96k
                   "Changing field mode (%d -> %d) between slices is not allowed\n",
2182
1.96k
                   h->picture_structure, sl->picture_structure);
2183
1.96k
            return AVERROR_INVALIDDATA;
2184
61.5k
        } else if (!h->cur_pic_ptr) {
2185
0
            av_log(h->avctx, AV_LOG_ERROR,
2186
0
                   "unset cur_pic_ptr on slice %d\n",
2187
0
                   h->current_slice + 1);
2188
0
            return AVERROR_INVALIDDATA;
2189
0
        }
2190
63.5k
    }
2191
2192
2.58M
    ret = h264_slice_init(h, sl, nal);
2193
2.58M
    if (ret < 0)
2194
203k
        return ret;
2195
2196
2.37M
    h->nb_slice_ctx_queued++;
2197
2198
2.37M
    return 0;
2199
2.58M
}
2200
2201
int ff_h264_get_slice_type(const H264SliceContext *sl)
2202
0
{
2203
0
    switch (sl->slice_type) {
2204
0
    case AV_PICTURE_TYPE_P:
2205
0
        return 0;
2206
0
    case AV_PICTURE_TYPE_B:
2207
0
        return 1;
2208
0
    case AV_PICTURE_TYPE_I:
2209
0
        return 2;
2210
0
    case AV_PICTURE_TYPE_SP:
2211
0
        return 3;
2212
0
    case AV_PICTURE_TYPE_SI:
2213
0
        return 4;
2214
0
    default:
2215
0
        return AVERROR_INVALIDDATA;
2216
0
    }
2217
0
}
2218
2219
static av_always_inline void fill_filter_caches_inter(const H264Context *h,
2220
                                                      H264SliceContext *sl,
2221
                                                      int mb_type, int top_xy,
2222
                                                      const int left_xy[LEFT_MBS],
2223
                                                      int top_type,
2224
                                                      const int left_type[LEFT_MBS],
2225
                                                      int mb_xy, int list)
2226
44.5M
{
2227
44.5M
    int b_stride = h->b_stride;
2228
44.5M
    int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
2229
44.5M
    int8_t *ref_cache   = &sl->ref_cache[list][scan8[0]];
2230
44.5M
    if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
2231
44.5M
        if (USES_LIST(top_type, list)) {
2232
27.3M
            const int b_xy  = h->mb2b_xy[top_xy] + 3 * b_stride;
2233
27.3M
            const int b8_xy = 4 * top_xy + 2;
2234
27.3M
            const int *ref2frm = &h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
2235
27.3M
            AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
2236
27.3M
            ref_cache[0 - 1 * 8] =
2237
27.3M
            ref_cache[1 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 0]];
2238
27.3M
            ref_cache[2 - 1 * 8] =
2239
27.3M
            ref_cache[3 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 1]];
2240
27.3M
        } else {
2241
17.1M
            AV_ZERO128(mv_dst - 1 * 8);
2242
17.1M
            AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2243
17.1M
        }
2244
2245
44.5M
        if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
2246
40.8M
            if (USES_LIST(left_type[LTOP], list)) {
2247
33.0M
                const int b_xy  = h->mb2b_xy[left_xy[LTOP]] + 3;
2248
33.0M
                const int b8_xy = 4 * left_xy[LTOP] + 1;
2249
33.0M
                const int *ref2frm = &h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
2250
33.0M
                AV_COPY32(mv_dst - 1 +  0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
2251
33.0M
                AV_COPY32(mv_dst - 1 +  8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
2252
33.0M
                AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
2253
33.0M
                AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
2254
33.0M
                ref_cache[-1 +  0] =
2255
33.0M
                ref_cache[-1 +  8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
2256
33.0M
                ref_cache[-1 + 16] =
2257
33.0M
                ref_cache[-1 + 24] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
2258
33.0M
            } else {
2259
7.79M
                AV_ZERO32(mv_dst - 1 +  0);
2260
7.79M
                AV_ZERO32(mv_dst - 1 +  8);
2261
7.79M
                AV_ZERO32(mv_dst - 1 + 16);
2262
7.79M
                AV_ZERO32(mv_dst - 1 + 24);
2263
7.79M
                ref_cache[-1 +  0] =
2264
7.79M
                ref_cache[-1 +  8] =
2265
7.79M
                ref_cache[-1 + 16] =
2266
7.79M
                ref_cache[-1 + 24] = LIST_NOT_USED;
2267
7.79M
            }
2268
40.8M
        }
2269
44.5M
    }
2270
2271
44.5M
    if (!USES_LIST(mb_type, list)) {
2272
5.06M
        fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
2273
5.06M
        AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2274
5.06M
        AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2275
5.06M
        AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2276
5.06M
        AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
2277
5.06M
        return;
2278
5.06M
    }
2279
2280
39.4M
    {
2281
39.4M
        const int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
2282
39.4M
        const int *ref2frm = &h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
2283
39.4M
        uint32_t ref01 = (pack16to32(ref2frm[ref[0]], ref2frm[ref[1]]) & 0x00FF00FF) * 0x0101;
2284
39.4M
        uint32_t ref23 = (pack16to32(ref2frm[ref[2]], ref2frm[ref[3]]) & 0x00FF00FF) * 0x0101;
2285
39.4M
        AV_WN32A(&ref_cache[0 * 8], ref01);
2286
39.4M
        AV_WN32A(&ref_cache[1 * 8], ref01);
2287
39.4M
        AV_WN32A(&ref_cache[2 * 8], ref23);
2288
39.4M
        AV_WN32A(&ref_cache[3 * 8], ref23);
2289
39.4M
    }
2290
2291
39.4M
    {
2292
39.4M
        int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
2293
39.4M
        AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
2294
39.4M
        AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
2295
39.4M
        AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
2296
39.4M
        AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
2297
39.4M
    }
2298
39.4M
}
2299
2300
/**
2301
 * @return non zero if the loop filter can be skipped
2302
 */
2303
static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
2304
32.9M
{
2305
32.9M
    const int mb_xy = sl->mb_xy;
2306
32.9M
    int top_xy, left_xy[LEFT_MBS];
2307
32.9M
    int top_type, left_type[LEFT_MBS];
2308
32.9M
    const uint8_t *nnz;
2309
32.9M
    uint8_t *nnz_cache;
2310
2311
32.9M
    top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
2312
2313
32.9M
    left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
2314
32.9M
    if (FRAME_MBAFF(h)) {
2315
14.1M
        const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
2316
14.1M
        const int curr_mb_field_flag = IS_INTERLACED(mb_type);
2317
14.1M
        if (sl->mb_y & 1) {
2318
7.08M
            if (left_mb_field_flag != curr_mb_field_flag)
2319
908k
                left_xy[LTOP] -= h->mb_stride;
2320
7.08M
        } else {
2321
7.08M
            if (curr_mb_field_flag)
2322
2.49M
                top_xy += h->mb_stride &
2323
2.49M
                          (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
2324
7.08M
            if (left_mb_field_flag != curr_mb_field_flag)
2325
910k
                left_xy[LBOT] += h->mb_stride;
2326
7.08M
        }
2327
14.1M
    }
2328
2329
32.9M
    sl->top_mb_xy        = top_xy;
2330
32.9M
    sl->left_mb_xy[LTOP] = left_xy[LTOP];
2331
32.9M
    sl->left_mb_xy[LBOT] = left_xy[LBOT];
2332
32.9M
    {
2333
        /* For sufficiently low qp, filtering wouldn't do anything.
2334
         * This is a conservative estimate: could also check beta_offset
2335
         * and more accurate chroma_qp. */
2336
32.9M
        int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
2337
32.9M
        int qp        = h->cur_pic.qscale_table[mb_xy];
2338
32.9M
        if (qp <= qp_thresh &&
2339
2.25M
            (left_xy[LTOP] < 0 ||
2340
2.16M
             ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
2341
2.22M
            (top_xy < 0 ||
2342
1.93M
             ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
2343
1.93M
            if (!FRAME_MBAFF(h))
2344
841k
                return 1;
2345
1.09M
            if ((left_xy[LTOP] < 0 ||
2346
1.08M
                 ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
2347
1.09M
                (top_xy < h->mb_stride ||
2348
1.01M
                 ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
2349
995k
                return 1;
2350
1.09M
        }
2351
32.9M
    }
2352
2353
31.0M
    top_type        = h->cur_pic.mb_type[top_xy];
2354
31.0M
    left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
2355
31.0M
    left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
2356
31.0M
    if (sl->deblocking_filter == 2) {
2357
2.68M
        if (h->slice_table[top_xy] != sl->slice_num)
2358
844k
            top_type = 0;
2359
2.68M
        if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
2360
211k
            left_type[LTOP] = left_type[LBOT] = 0;
2361
28.3M
    } else {
2362
28.3M
        if (h->slice_table[top_xy] == 0xFFFF)
2363
8.44M
            top_type = 0;
2364
28.3M
        if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
2365
3.26M
            left_type[LTOP] = left_type[LBOT] = 0;
2366
28.3M
    }
2367
31.0M
    sl->top_type        = top_type;
2368
31.0M
    sl->left_type[LTOP] = left_type[LTOP];
2369
31.0M
    sl->left_type[LBOT] = left_type[LBOT];
2370
2371
31.0M
    if (IS_INTRA(mb_type))
2372
2.69M
        return 0;
2373
2374
28.3M
    fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2375
28.3M
                             top_type, left_type, mb_xy, 0);
2376
28.3M
    if (sl->list_count == 2)
2377
16.1M
        fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
2378
16.1M
                                 top_type, left_type, mb_xy, 1);
2379
2380
28.3M
    nnz       = h->non_zero_count[mb_xy];
2381
28.3M
    nnz_cache = sl->non_zero_count_cache;
2382
28.3M
    AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
2383
28.3M
    AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
2384
28.3M
    AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
2385
28.3M
    AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
2386
28.3M
    sl->cbp = h->cbp_table[mb_xy];
2387
2388
28.3M
    if (top_type) {
2389
19.8M
        nnz = h->non_zero_count[top_xy];
2390
19.8M
        AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
2391
19.8M
    }
2392
2393
28.3M
    if (left_type[LTOP]) {
2394
25.2M
        nnz = h->non_zero_count[left_xy[LTOP]];
2395
25.2M
        nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
2396
25.2M
        nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
2397
25.2M
        nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
2398
25.2M
        nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
2399
25.2M
    }
2400
2401
    /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
2402
     * from what the loop filter needs */
2403
28.3M
    if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
2404
2.31M
        if (IS_8x8DCT(top_type)) {
2405
25.2k
            nnz_cache[4 + 8 * 0] =
2406
25.2k
            nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
2407
25.2k
            nnz_cache[6 + 8 * 0] =
2408
25.2k
            nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
2409
25.2k
        }
2410
2.31M
        if (IS_8x8DCT(left_type[LTOP])) {
2411
30.6k
            nnz_cache[3 + 8 * 1] =
2412
30.6k
            nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
2413
30.6k
        }
2414
2.31M
        if (IS_8x8DCT(left_type[LBOT])) {
2415
29.7k
            nnz_cache[3 + 8 * 3] =
2416
29.7k
            nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
2417
29.7k
        }
2418
2419
2.31M
        if (IS_8x8DCT(mb_type)) {
2420
44.4k
            nnz_cache[scan8[0]] =
2421
44.4k
            nnz_cache[scan8[1]] =
2422
44.4k
            nnz_cache[scan8[2]] =
2423
44.4k
            nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
2424
2425
44.4k
            nnz_cache[scan8[0 + 4]] =
2426
44.4k
            nnz_cache[scan8[1 + 4]] =
2427
44.4k
            nnz_cache[scan8[2 + 4]] =
2428
44.4k
            nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
2429
2430
44.4k
            nnz_cache[scan8[0 + 8]] =
2431
44.4k
            nnz_cache[scan8[1 + 8]] =
2432
44.4k
            nnz_cache[scan8[2 + 8]] =
2433
44.4k
            nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
2434
2435
44.4k
            nnz_cache[scan8[0 + 12]] =
2436
44.4k
            nnz_cache[scan8[1 + 12]] =
2437
44.4k
            nnz_cache[scan8[2 + 12]] =
2438
44.4k
            nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
2439
44.4k
        }
2440
2.31M
    }
2441
2442
28.3M
    return 0;
2443
31.0M
}
2444
2445
static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
2446
3.43M
{
2447
3.43M
    uint8_t *dest_y, *dest_cb, *dest_cr;
2448
3.43M
    int linesize, uvlinesize, mb_x, mb_y;
2449
3.43M
    const int end_mb_y       = sl->mb_y + FRAME_MBAFF(h);
2450
3.43M
    const int old_slice_type = sl->slice_type;
2451
3.43M
    const int pixel_shift    = h->pixel_shift;
2452
3.43M
    const int block_h        = 16 >> h->chroma_y_shift;
2453
2454
3.43M
    if (h->postpone_filter)
2455
0
        return;
2456
2457
3.43M
    if (sl->deblocking_filter) {
2458
28.8M
        for (mb_x = start_x; mb_x < end_x; mb_x++)
2459
58.7M
            for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
2460
32.9M
                int mb_xy, mb_type;
2461
32.9M
                mb_xy         = sl->mb_xy = mb_x + mb_y * h->mb_stride;
2462
32.9M
                mb_type       = h->cur_pic.mb_type[mb_xy];
2463
2464
32.9M
                if (FRAME_MBAFF(h))
2465
14.1M
                    sl->mb_mbaff               =
2466
14.1M
                    sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
2467
2468
32.9M
                sl->mb_x = mb_x;
2469
32.9M
                sl->mb_y = mb_y;
2470
32.9M
                dest_y  = h->cur_pic.f->data[0] +
2471
32.9M
                          ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
2472
32.9M
                dest_cb = h->cur_pic.f->data[1] +
2473
32.9M
                          (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2474
32.9M
                          mb_y * sl->uvlinesize * block_h;
2475
32.9M
                dest_cr = h->cur_pic.f->data[2] +
2476
32.9M
                          (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
2477
32.9M
                          mb_y * sl->uvlinesize * block_h;
2478
                // FIXME simplify above
2479
2480
32.9M
                if (MB_FIELD(sl)) {
2481
12.7M
                    linesize   = sl->mb_linesize   = sl->linesize   * 2;
2482
12.7M
                    uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
2483
12.7M
                    if (mb_y & 1) { // FIXME move out of this function?
2484
3.97M
                        dest_y  -= sl->linesize   * 15;
2485
3.97M
                        dest_cb -= sl->uvlinesize * (block_h - 1);
2486
3.97M
                        dest_cr -= sl->uvlinesize * (block_h - 1);
2487
3.97M
                    }
2488
20.1M
                } else {
2489
20.1M
                    linesize   = sl->mb_linesize   = sl->linesize;
2490
20.1M
                    uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
2491
20.1M
                }
2492
32.9M
                backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
2493
32.9M
                                 uvlinesize, 0);
2494
32.9M
                if (fill_filter_caches(h, sl, mb_type))
2495
1.83M
                    continue;
2496
31.0M
                sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
2497
31.0M
                sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
2498
2499
31.0M
                if (FRAME_MBAFF(h)) {
2500
13.1M
                    ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
2501
13.1M
                                      linesize, uvlinesize);
2502
17.8M
                } else {
2503
17.8M
                    ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
2504
17.8M
                                           dest_cr, linesize, uvlinesize);
2505
17.8M
                }
2506
31.0M
            }
2507
3.00M
    }
2508
3.43M
    sl->slice_type  = old_slice_type;
2509
3.43M
    sl->mb_x         = end_x;
2510
3.43M
    sl->mb_y         = end_mb_y - FRAME_MBAFF(h);
2511
3.43M
    sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
2512
3.43M
    sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
2513
3.43M
}
2514
2515
static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
2516
894k
{
2517
894k
    const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
2518
894k
    int mb_type     = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
2519
0
                      h->cur_pic.mb_type[mb_xy - 1] :
2520
894k
                      (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
2521
810k
                      h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
2522
894k
    sl->mb_mbaff    = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
2523
894k
}
2524
2525
/**
2526
 * Draw edges and report progress for the last MB row.
2527
 */
2528
static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
2529
3.08M
{
2530
3.08M
    int top            = 16 * (sl->mb_y      >> FIELD_PICTURE(h));
2531
3.08M
    int pic_height     = 16 *  h->mb_height >> FIELD_PICTURE(h);
2532
3.08M
    int height         =  16      << FRAME_MBAFF(h);
2533
3.08M
    int deblock_border = (16 + 4) << FRAME_MBAFF(h);
2534
2535
3.08M
    if (sl->deblocking_filter) {
2536
2.66M
        if ((top + height) >= pic_height)
2537
269k
            height += deblock_border;
2538
2.66M
        top -= deblock_border;
2539
2.66M
    }
2540
2541
3.08M
    if (top >= pic_height || (top + height) < 0)
2542
663k
        return;
2543
2544
2.41M
    height = FFMIN(height, pic_height - top);
2545
2.41M
    if (top < 0) {
2546
599k
        height = top + height;
2547
599k
        top    = 0;
2548
599k
    }
2549
2550
2.41M
    ff_h264_draw_horiz_band(h, sl, top, height);
2551
2552
2.41M
    if (h->droppable || h->er.error_occurred)
2553
1.86M
        return;
2554
2555
551k
    ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
2556
551k
                              h->picture_structure == PICT_BOTTOM_FIELD);
2557
551k
}
2558
2559
static void er_add_slice(H264SliceContext *sl,
2560
                         int startx, int starty,
2561
                         int endx, int endy, int status)
2562
2.33M
{
2563
2.33M
    if (!sl->h264->enable_er)
2564
0
        return;
2565
2566
2.33M
    if (CONFIG_ERROR_RESILIENCE) {
2567
2.33M
        ff_er_add_slice(sl->er, startx, starty, endx, endy, status);
2568
2.33M
    }
2569
2.33M
}
2570
2571
static int decode_slice(struct AVCodecContext *avctx, void *arg)
2572
2.37M
{
2573
2.37M
    H264SliceContext *sl = arg;
2574
2.37M
    const H264Context *h = sl->h264;
2575
2.37M
    int lf_x_start = sl->mb_x;
2576
2.37M
    int orig_deblock = sl->deblocking_filter;
2577
2.37M
    int ret;
2578
2579
2.37M
    sl->linesize   = h->cur_pic_ptr->f->linesize[0];
2580
2.37M
    sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
2581
2582
2.37M
    ret = alloc_scratch_buffers(sl, sl->linesize);
2583
2.37M
    if (ret < 0)
2584
0
        return ret;
2585
2586
2.37M
    sl->mb_skip_run = -1;
2587
2588
2.37M
    av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * sl->linesize * ((scan8[15] - scan8[0]) >> 3));
2589
2590
2.37M
    if (h->postpone_filter)
2591
0
        sl->deblocking_filter = 0;
2592
2593
2.37M
    sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
2594
884k
                     (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
2595
2596
2.37M
    if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && sl->er->error_status_table) {
2597
1.63M
        const int start_i  = av_clip(sl->resync_mb_x + sl->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
2598
1.63M
        if (start_i) {
2599
332k
            int prev_status = sl->er->error_status_table[sl->er->mb_index2xy[start_i - 1]];
2600
332k
            prev_status &= ~ VP_START;
2601
332k
            if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
2602
329k
                sl->er->error_occurred = 1;
2603
332k
        }
2604
1.63M
    }
2605
2606
2.37M
    if (h->ps.pps->cabac) {
2607
        /* realign */
2608
1.62M
        align_get_bits(&sl->gb);
2609
2610
        /* init cabac */
2611
1.62M
        ret = ff_init_cabac_decoder(&sl->cabac,
2612
1.62M
                              sl->gb.buffer + get_bits_count(&sl->gb) / 8,
2613
1.62M
                              (get_bits_left(&sl->gb) + 7) / 8);
2614
1.62M
        if (ret < 0)
2615
39.2k
            return ret;
2616
2617
1.58M
        ff_h264_init_cabac_states(h, sl);
2618
2619
25.7M
        for (;;) {
2620
25.7M
            int ret, eos;
2621
25.7M
            if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2622
0
                av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2623
0
                       sl->next_slice_idx);
2624
0
                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2625
0
                             sl->mb_y, ER_MB_ERROR);
2626
0
                return AVERROR_INVALIDDATA;
2627
0
            }
2628
2629
25.7M
            ret = ff_h264_decode_mb_cabac(h, sl);
2630
2631
25.7M
            if (ret >= 0)
2632
25.2M
                ff_h264_hl_decode_mb(h, sl);
2633
2634
            // FIXME optimal? or let mb_decode decode 16x32 ?
2635
25.7M
            if (ret >= 0 && FRAME_MBAFF(h)) {
2636
7.40M
                sl->mb_y++;
2637
2638
7.40M
                ret = ff_h264_decode_mb_cabac(h, sl);
2639
2640
7.40M
                if (ret >= 0)
2641
7.35M
                    ff_h264_hl_decode_mb(h, sl);
2642
7.40M
                sl->mb_y--;
2643
7.40M
            }
2644
25.7M
            eos = get_cabac_terminate(&sl->cabac);
2645
2646
25.7M
            if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
2647
9.31M
                sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
2648
271k
                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2649
271k
                             sl->mb_y, ER_MB_END);
2650
271k
                if (sl->mb_x >= lf_x_start)
2651
271k
                    loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
2652
271k
                goto finish;
2653
271k
            }
2654
25.4M
            if (sl->cabac.bytestream > sl->cabac.bytestream_end + 2 )
2655
1.06M
                av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", sl->cabac.bytestream_end - sl->cabac.bytestream);
2656
25.4M
            if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 4) {
2657
990k
                av_log(h->avctx, AV_LOG_ERROR,
2658
990k
                       "error while decoding MB %d %d, bytestream %td\n",
2659
990k
                       sl->mb_x, sl->mb_y,
2660
990k
                       sl->cabac.bytestream_end - sl->cabac.bytestream);
2661
990k
                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2662
990k
                             sl->mb_y, ER_MB_ERROR);
2663
990k
                return AVERROR_INVALIDDATA;
2664
990k
            }
2665
2666
24.4M
            if (++sl->mb_x >= h->mb_width) {
2667
2.49M
                loop_filter(h, sl, lf_x_start, sl->mb_x);
2668
2.49M
                sl->mb_x = lf_x_start = 0;
2669
2.49M
                decode_finish_row(h, sl);
2670
2.49M
                ++sl->mb_y;
2671
2.49M
                if (FIELD_OR_MBAFF_PICTURE(h)) {
2672
1.46M
                    ++sl->mb_y;
2673
1.46M
                    if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2674
790k
                        predict_field_decoding_flag(h, sl);
2675
1.46M
                }
2676
2.49M
            }
2677
2678
24.4M
            if (eos || sl->mb_y >= h->mb_height) {
2679
320k
                ff_tlog(h->avctx, "slice end %d %d\n",
2680
320k
                        get_bits_count(&sl->gb), sl->gb.size_in_bits);
2681
320k
                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
2682
320k
                             sl->mb_y, ER_MB_END);
2683
320k
                if (sl->mb_x > lf_x_start)
2684
79.1k
                    loop_filter(h, sl, lf_x_start, sl->mb_x);
2685
320k
                goto finish;
2686
320k
            }
2687
24.4M
        }
2688
1.58M
    } else {
2689
6.15M
        for (;;) {
2690
6.15M
            int ret;
2691
2692
6.15M
            if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
2693
0
                av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
2694
0
                       sl->next_slice_idx);
2695
0
                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2696
0
                             sl->mb_y, ER_MB_ERROR);
2697
0
                return AVERROR_INVALIDDATA;
2698
0
            }
2699
2700
6.15M
            ret = ff_h264_decode_mb_cavlc(h, sl);
2701
2702
6.15M
            if (ret >= 0)
2703
5.58M
                ff_h264_hl_decode_mb(h, sl);
2704
2705
            // FIXME optimal? or let mb_decode decode 16x32 ?
2706
6.15M
            if (ret >= 0 && FRAME_MBAFF(h)) {
2707
1.81M
                sl->mb_y++;
2708
1.81M
                ret = ff_h264_decode_mb_cavlc(h, sl);
2709
2710
1.81M
                if (ret >= 0)
2711
1.73M
                    ff_h264_hl_decode_mb(h, sl);
2712
1.81M
                sl->mb_y--;
2713
1.81M
            }
2714
2715
6.15M
            if (ret < 0) {
2716
651k
                av_log(h->avctx, AV_LOG_ERROR,
2717
651k
                       "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
2718
651k
                er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2719
651k
                             sl->mb_y, ER_MB_ERROR);
2720
651k
                return ret;
2721
651k
            }
2722
2723
5.50M
            if (++sl->mb_x >= h->mb_width) {
2724
584k
                loop_filter(h, sl, lf_x_start, sl->mb_x);
2725
584k
                sl->mb_x = lf_x_start = 0;
2726
584k
                decode_finish_row(h, sl);
2727
584k
                ++sl->mb_y;
2728
584k
                if (FIELD_OR_MBAFF_PICTURE(h)) {
2729
308k
                    ++sl->mb_y;
2730
308k
                    if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
2731
103k
                        predict_field_decoding_flag(h, sl);
2732
308k
                }
2733
584k
                if (sl->mb_y >= h->mb_height) {
2734
52.2k
                    ff_tlog(h->avctx, "slice end %d %d\n",
2735
52.2k
                            get_bits_count(&sl->gb), sl->gb.size_in_bits);
2736
2737
52.2k
                    if (   get_bits_left(&sl->gb) == 0
2738
49.2k
                        || get_bits_left(&sl->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
2739
43.7k
                        er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2740
43.7k
                                     sl->mb_x - 1, sl->mb_y, ER_MB_END);
2741
2742
43.7k
                        goto finish;
2743
43.7k
                    } else {
2744
8.46k
                        er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2745
8.46k
                                     sl->mb_x, sl->mb_y, ER_MB_END);
2746
2747
8.46k
                        return AVERROR_INVALIDDATA;
2748
8.46k
                    }
2749
52.2k
                }
2750
584k
            }
2751
2752
5.45M
            if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
2753
51.6k
                ff_tlog(h->avctx, "slice end %d %d\n",
2754
51.6k
                        get_bits_count(&sl->gb), sl->gb.size_in_bits);
2755
2756
51.6k
                if (get_bits_left(&sl->gb) == 0) {
2757
11.5k
                    er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
2758
11.5k
                                 sl->mb_x - 1, sl->mb_y, ER_MB_END);
2759
11.5k
                    if (sl->mb_x > lf_x_start)
2760
7.71k
                        loop_filter(h, sl, lf_x_start, sl->mb_x);
2761
2762
11.5k
                    goto finish;
2763
40.0k
                } else {
2764
40.0k
                    er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
2765
40.0k
                                 sl->mb_y, ER_MB_ERROR);
2766
2767
40.0k
                    return AVERROR_INVALIDDATA;
2768
40.0k
                }
2769
51.6k
            }
2770
5.45M
        }
2771
755k
    }
2772
2773
647k
finish:
2774
647k
    sl->deblocking_filter = orig_deblock;
2775
647k
    return 0;
2776
2.37M
}
2777
2778
/**
2779
 * Call decode_slice() for each context.
2780
 *
2781
 * @param h h264 master context
2782
 */
2783
int ff_h264_execute_decode_slices(H264Context *h)
2784
5.65M
{
2785
5.65M
    AVCodecContext *const avctx = h->avctx;
2786
5.65M
    H264SliceContext *sl;
2787
5.65M
    int context_count = h->nb_slice_ctx_queued;
2788
5.65M
    int ret = 0;
2789
5.65M
    int i, j;
2790
2791
5.65M
    h->slice_ctx[0].next_slice_idx = INT_MAX;
2792
2793
5.65M
    if (h->avctx->hwaccel || context_count < 1)
2794
3.27M
        return 0;
2795
2796
2.37M
    av_assert0(context_count && h->slice_ctx[context_count - 1].mb_y < h->mb_height);
2797
2798
2.37M
    if (context_count == 1) {
2799
2800
2.37M
        h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
2801
2.37M
        h->postpone_filter = 0;
2802
2803
2.37M
        ret = decode_slice(avctx, &h->slice_ctx[0]);
2804
2.37M
        h->mb_y = h->slice_ctx[0].mb_y;
2805
2.37M
        if (ret < 0)
2806
1.72M
            goto finish;
2807
2.37M
    } else {
2808
0
        av_assert0(context_count > 0);
2809
0
        for (i = 0; i < context_count; i++) {
2810
0
            int next_slice_idx = h->mb_width * h->mb_height;
2811
0
            int slice_idx;
2812
2813
0
            sl                 = &h->slice_ctx[i];
2814
2815
            /* make sure none of those slices overlap */
2816
0
            slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
2817
0
            for (j = 0; j < context_count; j++) {
2818
0
                H264SliceContext *sl2 = &h->slice_ctx[j];
2819
0
                int        slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
2820
2821
0
                if (i == j || slice_idx2 < slice_idx)
2822
0
                    continue;
2823
0
                next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
2824
0
            }
2825
0
            sl->next_slice_idx = next_slice_idx;
2826
0
        }
2827
2828
0
        avctx->execute(avctx, decode_slice, h->slice_ctx,
2829
0
                       NULL, context_count, sizeof(h->slice_ctx[0]));
2830
2831
        /* pull back stuff from slices to master context */
2832
0
        sl                   = &h->slice_ctx[context_count - 1];
2833
0
        h->mb_y              = sl->mb_y;
2834
2835
0
        if (h->postpone_filter) {
2836
0
            h->postpone_filter = 0;
2837
2838
0
            for (i = 0; i < context_count; i++) {
2839
0
                int y_end, x_end;
2840
2841
0
                sl = &h->slice_ctx[i];
2842
0
                y_end = FFMIN(sl->mb_y + 1, h->mb_height);
2843
0
                x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
2844
2845
0
                for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
2846
0
                    sl->mb_y = j;
2847
0
                    loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
2848
0
                                j == y_end - 1 ? x_end : h->mb_width);
2849
0
                }
2850
0
            }
2851
0
        }
2852
0
    }
2853
2854
2.37M
finish:
2855
2.37M
    h->nb_slice_ctx_queued = 0;
2856
2.37M
    return ret;
2857
2.37M
}