GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/hevc_ps.c Lines: 848 1094 77.5 %
Date: 2020-04-02 13:49:07 Branches: 501 735 68.2 %

Line Branch Exec Source
1
/*
2
 * HEVC Parameter Set decoding
3
 *
4
 * Copyright (C) 2012 - 2103 Guillaume Martres
5
 * Copyright (C) 2012 - 2103 Mickael Raulet
6
 * Copyright (C) 2012 - 2013 Gildas Cocherel
7
 * Copyright (C) 2013 Vittorio Giovara
8
 *
9
 * This file is part of FFmpeg.
10
 *
11
 * FFmpeg is free software; you can redistribute it and/or
12
 * modify it under the terms of the GNU Lesser General Public
13
 * License as published by the Free Software Foundation; either
14
 * version 2.1 of the License, or (at your option) any later version.
15
 *
16
 * FFmpeg is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19
 * Lesser General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Lesser General Public
22
 * License along with FFmpeg; if not, write to the Free Software
23
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24
 */
25
26
#include "libavutil/imgutils.h"
27
#include "golomb.h"
28
#include "hevc_data.h"
29
#include "hevc_ps.h"
30
31
static const uint8_t default_scaling_list_intra[] = {
32
    16, 16, 16, 16, 17, 18, 21, 24,
33
    16, 16, 16, 16, 17, 19, 22, 25,
34
    16, 16, 17, 18, 20, 22, 25, 29,
35
    16, 16, 18, 21, 24, 27, 31, 36,
36
    17, 17, 20, 24, 30, 35, 41, 47,
37
    18, 19, 22, 27, 35, 44, 54, 65,
38
    21, 22, 25, 31, 41, 54, 70, 88,
39
    24, 25, 29, 36, 47, 65, 88, 115
40
};
41
42
static const uint8_t default_scaling_list_inter[] = {
43
    16, 16, 16, 16, 17, 18, 20, 24,
44
    16, 16, 16, 17, 18, 20, 24, 25,
45
    16, 16, 17, 18, 20, 24, 25, 28,
46
    16, 17, 18, 20, 24, 25, 28, 33,
47
    17, 18, 20, 24, 25, 28, 33, 41,
48
    18, 20, 24, 25, 28, 33, 41, 54,
49
    20, 24, 25, 28, 33, 41, 54, 71,
50
    24, 25, 28, 33, 41, 54, 71, 91
51
};
52
53
static const AVRational vui_sar[] = {
54
    {  0,   1 },
55
    {  1,   1 },
56
    { 12,  11 },
57
    { 10,  11 },
58
    { 16,  11 },
59
    { 40,  33 },
60
    { 24,  11 },
61
    { 20,  11 },
62
    { 32,  11 },
63
    { 80,  33 },
64
    { 18,  11 },
65
    { 15,  11 },
66
    { 64,  33 },
67
    { 160, 99 },
68
    {  4,   3 },
69
    {  3,   2 },
70
    {  2,   1 },
71
};
72
73
static const uint8_t hevc_sub_width_c[] = {
74
    1, 2, 2, 1
75
};
76
77
static const uint8_t hevc_sub_height_c[] = {
78
    1, 2, 1, 1
79
};
80
81
3201
static void remove_pps(HEVCParamSets *s, int id)
82
{
83

3201
    if (s->pps_list[id] && s->pps == (const HEVCPPS*)s->pps_list[id]->data)
84
1784
        s->pps = NULL;
85
3201
    av_buffer_unref(&s->pps_list[id]);
86
3201
}
87
88
577
static void remove_sps(HEVCParamSets *s, int id)
89
{
90
    int i;
91
577
    if (s->sps_list[id]) {
92
11
        if (s->sps == (const HEVCSPS*)s->sps_list[id]->data)
93
11
            s->sps = NULL;
94
95
        /* drop all PPS that depend on this SPS */
96
715
        for (i = 0; i < FF_ARRAY_ELEMS(s->pps_list); i++)
97

704
            if (s->pps_list[i] && ((HEVCPPS*)s->pps_list[i]->data)->sps_id == id)
98
11
                remove_pps(s, i);
99
100

11
        av_assert0(!(s->sps_list[id] && s->sps == (HEVCSPS*)s->sps_list[id]->data));
101
    }
102
577
    av_buffer_unref(&s->sps_list[id]);
103
577
}
104
105
564
static void remove_vps(HEVCParamSets *s, int id)
106
{
107
    int i;
108
564
    if (s->vps_list[id]) {
109
3
        if (s->vps == (const HEVCVPS*)s->vps_list[id]->data)
110
3
            s->vps = NULL;
111
112
51
        for (i = 0; i < FF_ARRAY_ELEMS(s->sps_list); i++)
113

48
            if (s->sps_list[i] && ((HEVCSPS*)s->sps_list[i]->data)->vps_id == id)
114
3
                remove_sps(s, i);
115
    }
116
564
    av_buffer_unref(&s->vps_list[id]);
117
564
}
118
119
12190
int ff_hevc_decode_short_term_rps(GetBitContext *gb, AVCodecContext *avctx,
120
                                  ShortTermRPS *rps, const HEVCSPS *sps, int is_slice_header)
121
{
122
12190
    uint8_t rps_predict = 0;
123
    int delta_poc;
124
12190
    int k0 = 0;
125
12190
    int k1 = 0;
126
12190
    int k  = 0;
127
    int i;
128
129

12190
    if (rps != sps->st_rps && sps->nb_st_rps)
130
11107
        rps_predict = get_bits1(gb);
131
132
12190
    if (rps_predict) {
133
        const ShortTermRPS *rps_ridx;
134
        int delta_rps;
135
        unsigned abs_delta_rps;
136
7359
        uint8_t use_delta_flag = 0;
137
        uint8_t delta_rps_sign;
138
139
7359
        if (is_slice_header) {
140
619
            unsigned int delta_idx = get_ue_golomb_long(gb) + 1;
141
619
            if (delta_idx > sps->nb_st_rps) {
142
                av_log(avctx, AV_LOG_ERROR,
143
                       "Invalid value of delta_idx in slice header RPS: %d > %d.\n",
144
                       delta_idx, sps->nb_st_rps);
145
                return AVERROR_INVALIDDATA;
146
            }
147
619
            rps_ridx = &sps->st_rps[sps->nb_st_rps - delta_idx];
148
619
            rps->rps_idx_num_delta_pocs = rps_ridx->num_delta_pocs;
149
        } else
150
6740
            rps_ridx = &sps->st_rps[rps - sps->st_rps - 1];
151
152
7359
        delta_rps_sign = get_bits1(gb);
153
7359
        abs_delta_rps  = get_ue_golomb_long(gb) + 1;
154

7359
        if (abs_delta_rps < 1 || abs_delta_rps > 32768) {
155
            av_log(avctx, AV_LOG_ERROR,
156
                   "Invalid value of abs_delta_rps: %d\n",
157
                   abs_delta_rps);
158
            return AVERROR_INVALIDDATA;
159
        }
160
7359
        delta_rps      = (1 - (delta_rps_sign << 1)) * abs_delta_rps;
161
39260
        for (i = 0; i <= rps_ridx->num_delta_pocs; i++) {
162
31901
            int used = rps->used[k] = get_bits1(gb);
163
164
31901
            if (!used)
165
6341
                use_delta_flag = get_bits1(gb);
166
167

31901
            if (used || use_delta_flag) {
168
25610
                if (i < rps_ridx->num_delta_pocs)
169
20187
                    delta_poc = delta_rps + rps_ridx->delta_poc[i];
170
                else
171
5423
                    delta_poc = delta_rps;
172
25610
                rps->delta_poc[k] = delta_poc;
173
25610
                if (delta_poc < 0)
174
17731
                    k0++;
175
                else
176
7879
                    k1++;
177
25610
                k++;
178
            }
179
        }
180
181
7359
        if (k >= FF_ARRAY_ELEMS(rps->used)) {
182
            av_log(avctx, AV_LOG_ERROR,
183
                   "Invalid num_delta_pocs: %d\n", k);
184
            return AVERROR_INVALIDDATA;
185
        }
186
187
7359
        rps->num_delta_pocs    = k;
188
7359
        rps->num_negative_pics = k0;
189
        // sort in increasing order (smallest first)
190
7359
        if (rps->num_delta_pocs != 0) {
191
            int used, tmp;
192
25610
            for (i = 1; i < rps->num_delta_pocs; i++) {
193
18251
                delta_poc = rps->delta_poc[i];
194
18251
                used      = rps->used[i];
195
52239
                for (k = i - 1; k >= 0; k--) {
196
33988
                    tmp = rps->delta_poc[k];
197
33988
                    if (delta_poc < tmp) {
198
10843
                        rps->delta_poc[k + 1] = tmp;
199
10843
                        rps->used[k + 1]      = rps->used[k];
200
10843
                        rps->delta_poc[k]     = delta_poc;
201
10843
                        rps->used[k]          = used;
202
                    }
203
                }
204
            }
205
        }
206
7359
        if ((rps->num_negative_pics >> 1) != 0) {
207
            int used;
208
5580
            k = rps->num_negative_pics - 1;
209
            // flip the negative values to largest first
210
12888
            for (i = 0; i < rps->num_negative_pics >> 1; i++) {
211
7308
                delta_poc         = rps->delta_poc[i];
212
7308
                used              = rps->used[i];
213
7308
                rps->delta_poc[i] = rps->delta_poc[k];
214
7308
                rps->used[i]      = rps->used[k];
215
7308
                rps->delta_poc[k] = delta_poc;
216
7308
                rps->used[k]      = used;
217
7308
                k--;
218
            }
219
        }
220
    } else {
221
        unsigned int prev, nb_positive_pics;
222
4831
        rps->num_negative_pics = get_ue_golomb_long(gb);
223
4831
        nb_positive_pics       = get_ue_golomb_long(gb);
224
225

4831
        if (rps->num_negative_pics >= HEVC_MAX_REFS ||
226
            nb_positive_pics >= HEVC_MAX_REFS) {
227
            av_log(avctx, AV_LOG_ERROR, "Too many refs in a short term RPS.\n");
228
            return AVERROR_INVALIDDATA;
229
        }
230
231
4831
        rps->num_delta_pocs = rps->num_negative_pics + nb_positive_pics;
232
4831
        if (rps->num_delta_pocs) {
233
4514
            prev = 0;
234
18192
            for (i = 0; i < rps->num_negative_pics; i++) {
235
13678
                delta_poc = get_ue_golomb_long(gb) + 1;
236

13678
                if (delta_poc < 1 || delta_poc > 32768) {
237
                    av_log(avctx, AV_LOG_ERROR,
238
                        "Invalid value of delta_poc: %d\n",
239
                        delta_poc);
240
                    return AVERROR_INVALIDDATA;
241
                }
242
13678
                prev -= delta_poc;
243
13678
                rps->delta_poc[i] = prev;
244
13678
                rps->used[i]      = get_bits1(gb);
245
            }
246
4514
            prev = 0;
247
5567
            for (i = 0; i < nb_positive_pics; i++) {
248
1053
                delta_poc = get_ue_golomb_long(gb) + 1;
249

1053
                if (delta_poc < 1 || delta_poc > 32768) {
250
                    av_log(avctx, AV_LOG_ERROR,
251
                        "Invalid value of delta_poc: %d\n",
252
                        delta_poc);
253
                    return AVERROR_INVALIDDATA;
254
                }
255
1053
                prev += delta_poc;
256
1053
                rps->delta_poc[rps->num_negative_pics + i] = prev;
257
1053
                rps->used[rps->num_negative_pics + i]      = get_bits1(gb);
258
            }
259
        }
260
    }
261
12190
    return 0;
262
}
263
264
265
2031
static int decode_profile_tier_level(GetBitContext *gb, AVCodecContext *avctx,
266
                                      PTLCommon *ptl)
267
{
268
    int i;
269
270
2031
    if (get_bits_left(gb) < 2+1+5 + 32 + 4 + 43 + 1)
271
        return -1;
272
273
2031
    ptl->profile_space = get_bits(gb, 2);
274
2031
    ptl->tier_flag     = get_bits1(gb);
275
2031
    ptl->profile_idc   = get_bits(gb, 5);
276
2031
    if (ptl->profile_idc == FF_PROFILE_HEVC_MAIN)
277
1751
        av_log(avctx, AV_LOG_DEBUG, "Main profile bitstream\n");
278
280
    else if (ptl->profile_idc == FF_PROFILE_HEVC_MAIN_10)
279
112
        av_log(avctx, AV_LOG_DEBUG, "Main 10 profile bitstream\n");
280
168
    else if (ptl->profile_idc == FF_PROFILE_HEVC_MAIN_STILL_PICTURE)
281
8
        av_log(avctx, AV_LOG_DEBUG, "Main Still Picture profile bitstream\n");
282
160
    else if (ptl->profile_idc == FF_PROFILE_HEVC_REXT)
283
120
        av_log(avctx, AV_LOG_DEBUG, "Range Extension profile bitstream\n");
284
    else
285
40
        av_log(avctx, AV_LOG_WARNING, "Unknown HEVC profile: %d\n", ptl->profile_idc);
286
287
67023
    for (i = 0; i < 32; i++) {
288
64992
        ptl->profile_compatibility_flag[i] = get_bits1(gb);
289
290

64992
        if (ptl->profile_idc == 0 && i > 0 && ptl->profile_compatibility_flag[i])
291
40
            ptl->profile_idc = i;
292
    }
293
2031
    ptl->progressive_source_flag    = get_bits1(gb);
294
2031
    ptl->interlaced_source_flag     = get_bits1(gb);
295
2031
    ptl->non_packed_constraint_flag = get_bits1(gb);
296
2031
    ptl->frame_only_constraint_flag = get_bits1(gb);
297
298
#define check_profile_idc(idc) \
299
        ptl->profile_idc == idc || ptl->profile_compatibility_flag[idc]
300
301



2031
    if (check_profile_idc(4) || check_profile_idc(5) || check_profile_idc(6) ||
302



1911
        check_profile_idc(7) || check_profile_idc(8) || check_profile_idc(9) ||
303

1911
        check_profile_idc(10)) {
304
305
120
        ptl->max_12bit_constraint_flag        = get_bits1(gb);
306
120
        ptl->max_10bit_constraint_flag        = get_bits1(gb);
307
120
        ptl->max_8bit_constraint_flag         = get_bits1(gb);
308
120
        ptl->max_422chroma_constraint_flag    = get_bits1(gb);
309
120
        ptl->max_420chroma_constraint_flag    = get_bits1(gb);
310
120
        ptl->max_monochrome_constraint_flag   = get_bits1(gb);
311
120
        ptl->intra_constraint_flag            = get_bits1(gb);
312
120
        ptl->one_picture_only_constraint_flag = get_bits1(gb);
313
120
        ptl->lower_bit_rate_constraint_flag   = get_bits1(gb);
314
315



120
        if (check_profile_idc(5) || check_profile_idc(9) || check_profile_idc(10)) {
316
            ptl->max_14bit_constraint_flag    = get_bits1(gb);
317
            skip_bits_long(gb, 33); // XXX_reserved_zero_33bits[0..32]
318
        } else {
319
120
            skip_bits_long(gb, 34); // XXX_reserved_zero_34bits[0..33]
320
        }
321

1911
    } else if (check_profile_idc(2)) {
322
1599
        skip_bits(gb, 7);
323
1599
        ptl->one_picture_only_constraint_flag = get_bits1(gb);
324
1599
        skip_bits_long(gb, 35); // XXX_reserved_zero_35bits[0..34]
325
    } else {
326
312
        skip_bits_long(gb, 43); // XXX_reserved_zero_43bits[0..42]
327
    }
328
329



2031
    if (check_profile_idc(1) || check_profile_idc(2) || check_profile_idc(3) ||
330



120
        check_profile_idc(4) || check_profile_idc(5) || check_profile_idc(9))
331
2031
        ptl->inbld_flag = get_bits1(gb);
332
    else
333
        skip_bits1(gb);
334
#undef check_profile_idc
335
336
2031
    return 0;
337
}
338
339
1979
static int parse_ptl(GetBitContext *gb, AVCodecContext *avctx,
340
                      PTL *ptl, int max_num_sub_layers)
341
{
342
    int i;
343

3958
    if (decode_profile_tier_level(gb, avctx, &ptl->general_ptl) < 0 ||
344
1979
        get_bits_left(gb) < 8 + (8*2 * (max_num_sub_layers - 1 > 0))) {
345
        av_log(avctx, AV_LOG_ERROR, "PTL information too short\n");
346
        return -1;
347
    }
348
349
1979
    ptl->general_ptl.level_idc = get_bits(gb, 8);
350
351
2447
    for (i = 0; i < max_num_sub_layers - 1; i++) {
352
468
        ptl->sub_layer_profile_present_flag[i] = get_bits1(gb);
353
468
        ptl->sub_layer_level_present_flag[i]   = get_bits1(gb);
354
    }
355
356
1979
    if (max_num_sub_layers - 1> 0)
357
1656
        for (i = max_num_sub_layers - 1; i < 8; i++)
358
1420
            skip_bits(gb, 2); // reserved_zero_2bits[i]
359
2447
    for (i = 0; i < max_num_sub_layers - 1; i++) {
360

520
        if (ptl->sub_layer_profile_present_flag[i] &&
361
52
            decode_profile_tier_level(gb, avctx, &ptl->sub_layer_ptl[i]) < 0) {
362
            av_log(avctx, AV_LOG_ERROR,
363
                   "PTL information for sublayer %i too short\n", i);
364
            return -1;
365
        }
366
468
        if (ptl->sub_layer_level_present_flag[i]) {
367
52
            if (get_bits_left(gb) < 8) {
368
                av_log(avctx, AV_LOG_ERROR,
369
                       "Not enough data for sublayer %i level_idc\n", i);
370
                return -1;
371
            } else
372
52
                ptl->sub_layer_ptl[i].level_idc = get_bits(gb, 8);
373
        }
374
    }
375
376
1979
    return 0;
377
}
378
379
92
static void decode_sublayer_hrd(GetBitContext *gb, unsigned int nb_cpb,
380
                                int subpic_params_present)
381
{
382
    int i;
383
384
184
    for (i = 0; i < nb_cpb; i++) {
385
92
        get_ue_golomb_long(gb); // bit_rate_value_minus1
386
92
        get_ue_golomb_long(gb); // cpb_size_value_minus1
387
388
92
        if (subpic_params_present) {
389
26
            get_ue_golomb_long(gb); // cpb_size_du_value_minus1
390
26
            get_ue_golomb_long(gb); // bit_rate_du_value_minus1
391
        }
392
92
        skip_bits1(gb); // cbr_flag
393
    }
394
92
}
395
396
46
static int decode_hrd(GetBitContext *gb, int common_inf_present,
397
                       int max_sublayers)
398
{
399
46
    int nal_params_present = 0, vcl_params_present = 0;
400
46
    int subpic_params_present = 0;
401
    int i;
402
403
46
    if (common_inf_present) {
404
46
        nal_params_present = get_bits1(gb);
405
46
        vcl_params_present = get_bits1(gb);
406
407

46
        if (nal_params_present || vcl_params_present) {
408
46
            subpic_params_present = get_bits1(gb);
409
410
46
            if (subpic_params_present) {
411
13
                skip_bits(gb, 8); // tick_divisor_minus2
412
13
                skip_bits(gb, 5); // du_cpb_removal_delay_increment_length_minus1
413
13
                skip_bits(gb, 1); // sub_pic_cpb_params_in_pic_timing_sei_flag
414
13
                skip_bits(gb, 5); // dpb_output_delay_du_length_minus1
415
            }
416
417
46
            skip_bits(gb, 4); // bit_rate_scale
418
46
            skip_bits(gb, 4); // cpb_size_scale
419
420
46
            if (subpic_params_present)
421
13
                skip_bits(gb, 4);  // cpb_size_du_scale
422
423
46
            skip_bits(gb, 5); // initial_cpb_removal_delay_length_minus1
424
46
            skip_bits(gb, 5); // au_cpb_removal_delay_length_minus1
425
46
            skip_bits(gb, 5); // dpb_output_delay_length_minus1
426
        }
427
    }
428
429
92
    for (i = 0; i < max_sublayers; i++) {
430
46
        int low_delay = 0;
431
46
        unsigned int nb_cpb = 1;
432
46
        int fixed_rate = get_bits1(gb);
433
434
46
        if (!fixed_rate)
435
23
            fixed_rate = get_bits1(gb);
436
437
46
        if (fixed_rate)
438
23
            get_ue_golomb_long(gb);  // elemental_duration_in_tc_minus1
439
        else
440
23
            low_delay = get_bits1(gb);
441
442
46
        if (!low_delay) {
443
46
            nb_cpb = get_ue_golomb_long(gb) + 1;
444

46
            if (nb_cpb < 1 || nb_cpb > 32) {
445
                av_log(NULL, AV_LOG_ERROR, "nb_cpb %d invalid\n", nb_cpb);
446
                return AVERROR_INVALIDDATA;
447
            }
448
        }
449
450
46
        if (nal_params_present)
451
46
            decode_sublayer_hrd(gb, nb_cpb, subpic_params_present);
452
46
        if (vcl_params_present)
453
46
            decode_sublayer_hrd(gb, nb_cpb, subpic_params_present);
454
    }
455
46
    return 0;
456
}
457
458
993
int ff_hevc_decode_nal_vps(GetBitContext *gb, AVCodecContext *avctx,
459
                           HEVCParamSets *ps)
460
{
461
    int i,j;
462
993
    int vps_id = 0;
463
    ptrdiff_t nal_size;
464
    HEVCVPS *vps;
465
993
    AVBufferRef *vps_buf = av_buffer_allocz(sizeof(*vps));
466
467
993
    if (!vps_buf)
468
        return AVERROR(ENOMEM);
469
993
    vps = (HEVCVPS*)vps_buf->data;
470
471
993
    av_log(avctx, AV_LOG_DEBUG, "Decoding VPS\n");
472
473
993
    nal_size = gb->buffer_end - gb->buffer;
474
993
    if (nal_size > sizeof(vps->data)) {
475
        av_log(avctx, AV_LOG_WARNING, "Truncating likely oversized VPS "
476
               "(%"PTRDIFF_SPECIFIER" > %"SIZE_SPECIFIER")\n",
477
               nal_size, sizeof(vps->data));
478
        vps->data_size = sizeof(vps->data);
479
    } else {
480
993
        vps->data_size = nal_size;
481
    }
482
993
    memcpy(vps->data, gb->buffer, vps->data_size);
483
484
993
    vps_id = get_bits(gb, 4);
485
486
993
    if (get_bits(gb, 2) != 3) { // vps_reserved_three_2bits
487
        av_log(avctx, AV_LOG_ERROR, "vps_reserved_three_2bits is not three\n");
488
        goto err;
489
    }
490
491
993
    vps->vps_max_layers               = get_bits(gb, 6) + 1;
492
993
    vps->vps_max_sub_layers           = get_bits(gb, 3) + 1;
493
993
    vps->vps_temporal_id_nesting_flag = get_bits1(gb);
494
495
993
    if (get_bits(gb, 16) != 0xffff) { // vps_reserved_ffff_16bits
496
        av_log(avctx, AV_LOG_ERROR, "vps_reserved_ffff_16bits is not 0xffff\n");
497
        goto err;
498
    }
499
500
993
    if (vps->vps_max_sub_layers > HEVC_MAX_SUB_LAYERS) {
501
        av_log(avctx, AV_LOG_ERROR, "vps_max_sub_layers out of range: %d\n",
502
               vps->vps_max_sub_layers);
503
        goto err;
504
    }
505
506
993
    if (parse_ptl(gb, avctx, &vps->ptl, vps->vps_max_sub_layers) < 0)
507
        goto err;
508
509
993
    vps->vps_sub_layer_ordering_info_present_flag = get_bits1(gb);
510
511
993
    i = vps->vps_sub_layer_ordering_info_present_flag ? 0 : vps->vps_max_sub_layers - 1;
512
2133
    for (; i < vps->vps_max_sub_layers; i++) {
513
1140
        vps->vps_max_dec_pic_buffering[i] = get_ue_golomb_long(gb) + 1;
514
1140
        vps->vps_num_reorder_pics[i]      = get_ue_golomb_long(gb);
515
1140
        vps->vps_max_latency_increase[i]  = get_ue_golomb_long(gb) - 1;
516
517

1140
        if (vps->vps_max_dec_pic_buffering[i] > HEVC_MAX_DPB_SIZE || !vps->vps_max_dec_pic_buffering[i]) {
518
            av_log(avctx, AV_LOG_ERROR, "vps_max_dec_pic_buffering_minus1 out of range: %d\n",
519
                   vps->vps_max_dec_pic_buffering[i] - 1);
520
            goto err;
521
        }
522
1140
        if (vps->vps_num_reorder_pics[i] > vps->vps_max_dec_pic_buffering[i] - 1) {
523
            av_log(avctx, AV_LOG_WARNING, "vps_max_num_reorder_pics out of range: %d\n",
524
                   vps->vps_num_reorder_pics[i]);
525
            if (avctx->err_recognition & AV_EF_EXPLODE)
526
                goto err;
527
        }
528
    }
529
530
993
    vps->vps_max_layer_id   = get_bits(gb, 6);
531
993
    vps->vps_num_layer_sets = get_ue_golomb_long(gb) + 1;
532

993
    if (vps->vps_num_layer_sets < 1 || vps->vps_num_layer_sets > 1024 ||
533
993
        (vps->vps_num_layer_sets - 1LL) * (vps->vps_max_layer_id + 1LL) > get_bits_left(gb)) {
534
        av_log(avctx, AV_LOG_ERROR, "too many layer_id_included_flags\n");
535
        goto err;
536
    }
537
538
993
    for (i = 1; i < vps->vps_num_layer_sets; i++)
539
        for (j = 0; j <= vps->vps_max_layer_id; j++)
540
            skip_bits(gb, 1);  // layer_id_included_flag[i][j]
541
542
993
    vps->vps_timing_info_present_flag = get_bits1(gb);
543
993
    if (vps->vps_timing_info_present_flag) {
544
33
        vps->vps_num_units_in_tick               = get_bits_long(gb, 32);
545
33
        vps->vps_time_scale                      = get_bits_long(gb, 32);
546
33
        vps->vps_poc_proportional_to_timing_flag = get_bits1(gb);
547
33
        if (vps->vps_poc_proportional_to_timing_flag)
548
33
            vps->vps_num_ticks_poc_diff_one = get_ue_golomb_long(gb) + 1;
549
33
        vps->vps_num_hrd_parameters = get_ue_golomb_long(gb);
550
33
        if (vps->vps_num_hrd_parameters > (unsigned)vps->vps_num_layer_sets) {
551
            av_log(avctx, AV_LOG_ERROR,
552
                   "vps_num_hrd_parameters %d is invalid\n", vps->vps_num_hrd_parameters);
553
            goto err;
554
        }
555
38
        for (i = 0; i < vps->vps_num_hrd_parameters; i++) {
556
5
            int common_inf_present = 1;
557
558
5
            get_ue_golomb_long(gb); // hrd_layer_set_idx
559
5
            if (i)
560
                common_inf_present = get_bits1(gb);
561
5
            decode_hrd(gb, common_inf_present, vps->vps_max_sub_layers);
562
        }
563
    }
564
993
    get_bits1(gb); /* vps_extension_flag */
565
566
993
    if (get_bits_left(gb) < 0) {
567
        av_log(avctx, AV_LOG_ERROR,
568
               "Overread VPS by %d bits\n", -get_bits_left(gb));
569
        if (ps->vps_list[vps_id])
570
            goto err;
571
    }
572
573
993
    if (ps->vps_list[vps_id] &&
574
432
        !memcmp(ps->vps_list[vps_id]->data, vps_buf->data, vps_buf->size)) {
575
429
        av_buffer_unref(&vps_buf);
576
    } else {
577
564
        remove_vps(ps, vps_id);
578
564
        ps->vps_list[vps_id] = vps_buf;
579
    }
580
581
993
    return 0;
582
583
err:
584
    av_buffer_unref(&vps_buf);
585
    return AVERROR_INVALIDDATA;
586
}
587
588
215
static void decode_vui(GetBitContext *gb, AVCodecContext *avctx,
589
                       int apply_defdispwin, HEVCSPS *sps)
590
{
591
215
    VUI backup_vui, *vui = &sps->vui;
592
    GetBitContext backup;
593
215
    int sar_present, alt = 0;
594
595
215
    av_log(avctx, AV_LOG_DEBUG, "Decoding VUI\n");
596
597
215
    sar_present = get_bits1(gb);
598
215
    if (sar_present) {
599
103
        uint8_t sar_idx = get_bits(gb, 8);
600
103
        if (sar_idx < FF_ARRAY_ELEMS(vui_sar))
601
103
            vui->sar = vui_sar[sar_idx];
602
        else if (sar_idx == 255) {
603
            vui->sar.num = get_bits(gb, 16);
604
            vui->sar.den = get_bits(gb, 16);
605
        } else
606
            av_log(avctx, AV_LOG_WARNING,
607
                   "Unknown SAR index: %u.\n", sar_idx);
608
    }
609
610
215
    vui->overscan_info_present_flag = get_bits1(gb);
611
215
    if (vui->overscan_info_present_flag)
612
        vui->overscan_appropriate_flag = get_bits1(gb);
613
614
215
    vui->video_signal_type_present_flag = get_bits1(gb);
615
215
    if (vui->video_signal_type_present_flag) {
616
13
        vui->video_format                    = get_bits(gb, 3);
617
13
        vui->video_full_range_flag           = get_bits1(gb);
618
13
        vui->colour_description_present_flag = get_bits1(gb);
619

13
        if (vui->video_full_range_flag && sps->pix_fmt == AV_PIX_FMT_YUV420P)
620
5
            sps->pix_fmt = AV_PIX_FMT_YUVJ420P;
621
13
        if (vui->colour_description_present_flag) {
622
13
            vui->colour_primaries        = get_bits(gb, 8);
623
13
            vui->transfer_characteristic = get_bits(gb, 8);
624
13
            vui->matrix_coeffs           = get_bits(gb, 8);
625
626
            // Set invalid values to "unspecified"
627
13
            if (!av_color_primaries_name(vui->colour_primaries))
628
                vui->colour_primaries = AVCOL_PRI_UNSPECIFIED;
629
13
            if (!av_color_transfer_name(vui->transfer_characteristic))
630
                vui->transfer_characteristic = AVCOL_TRC_UNSPECIFIED;
631
13
            if (!av_color_space_name(vui->matrix_coeffs))
632
                vui->matrix_coeffs = AVCOL_SPC_UNSPECIFIED;
633
13
            if (vui->matrix_coeffs == AVCOL_SPC_RGB) {
634
                switch (sps->pix_fmt) {
635
                case AV_PIX_FMT_YUV444P:
636
                    sps->pix_fmt = AV_PIX_FMT_GBRP;
637
                    break;
638
                case AV_PIX_FMT_YUV444P10:
639
                    sps->pix_fmt = AV_PIX_FMT_GBRP10;
640
                    break;
641
                case AV_PIX_FMT_YUV444P12:
642
                    sps->pix_fmt = AV_PIX_FMT_GBRP12;
643
                    break;
644
                }
645
215
            }
646
        }
647
    }
648
649
215
    vui->chroma_loc_info_present_flag = get_bits1(gb);
650
215
    if (vui->chroma_loc_info_present_flag) {
651
8
        vui->chroma_sample_loc_type_top_field    = get_ue_golomb_long(gb);
652
8
        vui->chroma_sample_loc_type_bottom_field = get_ue_golomb_long(gb);
653
    }
654
655
215
    vui->neutra_chroma_indication_flag = get_bits1(gb);
656
215
    vui->field_seq_flag                = get_bits1(gb);
657
215
    vui->frame_field_info_present_flag = get_bits1(gb);
658
659
    // Backup context in case an alternate header is detected
660
215
    memcpy(&backup, gb, sizeof(backup));
661
215
    memcpy(&backup_vui, vui, sizeof(backup_vui));
662

215
    if (get_bits_left(gb) >= 68 && show_bits_long(gb, 21) == 0x100000) {
663
        vui->default_display_window_flag = 0;
664
        av_log(avctx, AV_LOG_WARNING, "Invalid default display window\n");
665
    } else
666
215
        vui->default_display_window_flag = get_bits1(gb);
667
668
215
    if (vui->default_display_window_flag) {
669
91
        int vert_mult  = hevc_sub_height_c[sps->chroma_format_idc];
670
91
        int horiz_mult = hevc_sub_width_c[sps->chroma_format_idc];
671
91
        vui->def_disp_win.left_offset   = get_ue_golomb_long(gb) * horiz_mult;
672
91
        vui->def_disp_win.right_offset  = get_ue_golomb_long(gb) * horiz_mult;
673
91
        vui->def_disp_win.top_offset    = get_ue_golomb_long(gb) *  vert_mult;
674
91
        vui->def_disp_win.bottom_offset = get_ue_golomb_long(gb) *  vert_mult;
675
676
91
        if (apply_defdispwin &&
677
40
            avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {
678
            av_log(avctx, AV_LOG_DEBUG,
679
                   "discarding vui default display window, "
680
                   "original values are l:%u r:%u t:%u b:%u\n",
681
                   vui->def_disp_win.left_offset,
682
                   vui->def_disp_win.right_offset,
683
                   vui->def_disp_win.top_offset,
684
                   vui->def_disp_win.bottom_offset);
685
686
            vui->def_disp_win.left_offset   =
687
            vui->def_disp_win.right_offset  =
688
            vui->def_disp_win.top_offset    =
689
            vui->def_disp_win.bottom_offset = 0;
690
        }
691
    }
692
693
215
timing_info:
694
215
    vui->vui_timing_info_present_flag = get_bits1(gb);
695
696
215
    if (vui->vui_timing_info_present_flag) {
697

65
        if( get_bits_left(gb) < 66 && !alt) {
698
            // The alternate syntax seem to have timing info located
699
            // at where def_disp_win is normally located
700
            av_log(avctx, AV_LOG_WARNING,
701
                   "Strange VUI timing information, retrying...\n");
702
            memcpy(vui, &backup_vui, sizeof(backup_vui));
703
            memcpy(gb, &backup, sizeof(backup));
704
            alt = 1;
705
            goto timing_info;
706
        }
707
65
        vui->vui_num_units_in_tick               = get_bits_long(gb, 32);
708
65
        vui->vui_time_scale                      = get_bits_long(gb, 32);
709
65
        if (alt) {
710
            av_log(avctx, AV_LOG_INFO, "Retry got %"PRIu32"/%"PRIu32" fps\n",
711
                   vui->vui_time_scale, vui->vui_num_units_in_tick);
712
        }
713
65
        vui->vui_poc_proportional_to_timing_flag = get_bits1(gb);
714
65
        if (vui->vui_poc_proportional_to_timing_flag)
715
33
            vui->vui_num_ticks_poc_diff_one_minus1 = get_ue_golomb_long(gb);
716
65
        vui->vui_hrd_parameters_present_flag = get_bits1(gb);
717
65
        if (vui->vui_hrd_parameters_present_flag)
718
41
            decode_hrd(gb, 1, sps->max_sub_layers);
719
    }
720
721
215
    vui->bitstream_restriction_flag = get_bits1(gb);
722
215
    if (vui->bitstream_restriction_flag) {
723

103
        if (get_bits_left(gb) < 8 && !alt) {
724
            av_log(avctx, AV_LOG_WARNING,
725
                   "Strange VUI bitstream restriction information, retrying"
726
                   " from timing information...\n");
727
            memcpy(vui, &backup_vui, sizeof(backup_vui));
728
            memcpy(gb, &backup, sizeof(backup));
729
            alt = 1;
730
            goto timing_info;
731
        }
732
103
        vui->tiles_fixed_structure_flag              = get_bits1(gb);
733
103
        vui->motion_vectors_over_pic_boundaries_flag = get_bits1(gb);
734
103
        vui->restricted_ref_pic_lists_flag           = get_bits1(gb);
735
103
        vui->min_spatial_segmentation_idc            = get_ue_golomb_long(gb);
736
103
        vui->max_bytes_per_pic_denom                 = get_ue_golomb_long(gb);
737
103
        vui->max_bits_per_min_cu_denom               = get_ue_golomb_long(gb);
738
103
        vui->log2_max_mv_length_horizontal           = get_ue_golomb_long(gb);
739
103
        vui->log2_max_mv_length_vertical             = get_ue_golomb_long(gb);
740
    }
741
742

215
    if (get_bits_left(gb) < 1 && !alt) {
743
        // XXX: Alternate syntax when sps_range_extension_flag != 0?
744
        av_log(avctx, AV_LOG_WARNING,
745
               "Overread in VUI, retrying from timing information...\n");
746
        memcpy(vui, &backup_vui, sizeof(backup_vui));
747
        memcpy(gb, &backup, sizeof(backup));
748
        alt = 1;
749
        goto timing_info;
750
    }
751
215
}
752
753
499
static void set_default_scaling_list_data(ScalingList *sl)
754
{
755
    int matrixId;
756
757
3493
    for (matrixId = 0; matrixId < 6; matrixId++) {
758
        // 4x4 default is 16
759
2994
        memset(sl->sl[0][matrixId], 16, 16);
760
2994
        sl->sl_dc[0][matrixId] = 16; // default for 16x16
761
2994
        sl->sl_dc[1][matrixId] = 16; // default for 32x32
762
    }
763
499
    memcpy(sl->sl[1][0], default_scaling_list_intra, 64);
764
499
    memcpy(sl->sl[1][1], default_scaling_list_intra, 64);
765
499
    memcpy(sl->sl[1][2], default_scaling_list_intra, 64);
766
499
    memcpy(sl->sl[1][3], default_scaling_list_inter, 64);
767
499
    memcpy(sl->sl[1][4], default_scaling_list_inter, 64);
768
499
    memcpy(sl->sl[1][5], default_scaling_list_inter, 64);
769
499
    memcpy(sl->sl[2][0], default_scaling_list_intra, 64);
770
499
    memcpy(sl->sl[2][1], default_scaling_list_intra, 64);
771
499
    memcpy(sl->sl[2][2], default_scaling_list_intra, 64);
772
499
    memcpy(sl->sl[2][3], default_scaling_list_inter, 64);
773
499
    memcpy(sl->sl[2][4], default_scaling_list_inter, 64);
774
499
    memcpy(sl->sl[2][5], default_scaling_list_inter, 64);
775
499
    memcpy(sl->sl[3][0], default_scaling_list_intra, 64);
776
499
    memcpy(sl->sl[3][1], default_scaling_list_intra, 64);
777
499
    memcpy(sl->sl[3][2], default_scaling_list_intra, 64);
778
499
    memcpy(sl->sl[3][3], default_scaling_list_inter, 64);
779
499
    memcpy(sl->sl[3][4], default_scaling_list_inter, 64);
780
499
    memcpy(sl->sl[3][5], default_scaling_list_inter, 64);
781
499
}
782
783
489
static int scaling_list_data(GetBitContext *gb, AVCodecContext *avctx, ScalingList *sl, HEVCSPS *sps)
784
{
785
    uint8_t scaling_list_pred_mode_flag;
786
    int32_t scaling_list_dc_coef[2][6];
787
    int size_id, matrix_id, pos;
788
    int i;
789
790
2445
    for (size_id = 0; size_id < 4; size_id++)
791

11736
        for (matrix_id = 0; matrix_id < 6; matrix_id += ((size_id == 3) ? 3 : 1)) {
792
9780
            scaling_list_pred_mode_flag = get_bits1(gb);
793
9780
            if (!scaling_list_pred_mode_flag) {
794
3978
                unsigned int delta = get_ue_golomb_long(gb);
795
                /* Only need to handle non-zero delta. Zero means default,
796
                 * which should already be in the arrays. */
797
3978
                if (delta) {
798
                    // Copy from previous array.
799
3852
                    delta *= (size_id == 3) ? 3 : 1;
800
3852
                    if (matrix_id < delta) {
801
                        av_log(avctx, AV_LOG_ERROR,
802
                               "Invalid delta in scaling list data: %d.\n", delta);
803
                        return AVERROR_INVALIDDATA;
804
                    }
805
806
3852
                    memcpy(sl->sl[size_id][matrix_id],
807
3852
                           sl->sl[size_id][matrix_id - delta],
808
                           size_id > 0 ? 64 : 16);
809
3852
                    if (size_id > 1)
810
530
                        sl->sl_dc[size_id - 2][matrix_id] = sl->sl_dc[size_id - 2][matrix_id - delta];
811
                }
812
            } else {
813
                int next_coef, coef_num;
814
                int32_t scaling_list_delta_coef;
815
816
5802
                next_coef = 8;
817
5802
                coef_num  = FFMIN(64, 1 << (4 + (size_id << 1)));
818
5802
                if (size_id > 1) {
819
3340
                    scaling_list_dc_coef[size_id - 2][matrix_id] = get_se_golomb(gb) + 8;
820
3340
                    next_coef = scaling_list_dc_coef[size_id - 2][matrix_id];
821
3340
                    sl->sl_dc[size_id - 2][matrix_id] = next_coef;
822
                }
823
315114
                for (i = 0; i < coef_num; i++) {
824
309312
                    if (size_id == 0)
825
20672
                        pos = 4 * ff_hevc_diag_scan4x4_y[i] +
826
20672
                                  ff_hevc_diag_scan4x4_x[i];
827
                    else
828
288640
                        pos = 8 * ff_hevc_diag_scan8x8_y[i] +
829
288640
                                  ff_hevc_diag_scan8x8_x[i];
830
831
309312
                    scaling_list_delta_coef = get_se_golomb(gb);
832
309312
                    next_coef = (next_coef + 256U + scaling_list_delta_coef) % 256;
833
309312
                    sl->sl[size_id][matrix_id][pos] = next_coef;
834
                }
835
            }
836
        }
837
838
489
    if (sps->chroma_format_idc == 3) {
839
2795
        for (i = 0; i < 64; i++) {
840
2752
            sl->sl[3][1][i] = sl->sl[2][1][i];
841
2752
            sl->sl[3][2][i] = sl->sl[2][2][i];
842
2752
            sl->sl[3][4][i] = sl->sl[2][4][i];
843
2752
            sl->sl[3][5][i] = sl->sl[2][5][i];
844
        }
845
43
        sl->sl_dc[1][1] = sl->sl_dc[0][1];
846
43
        sl->sl_dc[1][2] = sl->sl_dc[0][2];
847
43
        sl->sl_dc[1][4] = sl->sl_dc[0][4];
848
43
        sl->sl_dc[1][5] = sl->sl_dc[0][5];
849
    }
850
851
852
489
    return 0;
853
}
854
855
986
static int map_pixel_format(AVCodecContext *avctx, HEVCSPS *sps)
856
{
857
    const AVPixFmtDescriptor *desc;
858

986
    switch (sps->bit_depth) {
859
883
    case 8:
860
883
        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY8;
861
883
        if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P;
862
883
        if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P;
863
883
        if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P;
864
883
       break;
865
    case 9:
866
        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY9;
867
        if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P9;
868
        if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P9;
869
        if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P9;
870
        break;
871
80
    case 10:
872
80
        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY10;
873
80
        if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P10;
874
80
        if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P10;
875
80
        if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P10;
876
80
        break;
877
23
    case 12:
878
23
        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY12;
879
23
        if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P12;
880
23
        if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P12;
881
23
        if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P12;
882
23
        break;
883
    default:
884
        av_log(avctx, AV_LOG_ERROR,
885
               "The following bit-depths are currently specified: 8, 9, 10 and 12 bits, "
886
               "chroma_format_idc is %d, depth is %d\n",
887
               sps->chroma_format_idc, sps->bit_depth);
888
        return AVERROR_INVALIDDATA;
889
    }
890
891
986
    desc = av_pix_fmt_desc_get(sps->pix_fmt);
892
986
    if (!desc)
893
        return AVERROR(EINVAL);
894
895
986
    sps->hshift[0] = sps->vshift[0] = 0;
896
986
    sps->hshift[2] = sps->hshift[1] = desc->log2_chroma_w;
897
986
    sps->vshift[2] = sps->vshift[1] = desc->log2_chroma_h;
898
899
986
    sps->pixel_shift = sps->bit_depth > 8;
900
901
986
    return 0;
902
}
903
904
986
int ff_hevc_parse_sps(HEVCSPS *sps, GetBitContext *gb, unsigned int *sps_id,
905
                      int apply_defdispwin, AVBufferRef **vps_list, AVCodecContext *avctx)
906
{
907
    HEVCWindow *ow;
908
986
    int ret = 0;
909
    int log2_diff_max_min_transform_block_size;
910
    int bit_depth_chroma, start, vui_present, sublayer_ordering_info;
911
    int i;
912
913
    // Coded parameters
914
915
986
    sps->vps_id = get_bits(gb, 4);
916
917

986
    if (vps_list && !vps_list[sps->vps_id]) {
918
        av_log(avctx, AV_LOG_ERROR, "VPS %d does not exist\n",
919
               sps->vps_id);
920
        return AVERROR_INVALIDDATA;
921
    }
922
923
986
    sps->max_sub_layers = get_bits(gb, 3) + 1;
924
986
    if (sps->max_sub_layers > HEVC_MAX_SUB_LAYERS) {
925
        av_log(avctx, AV_LOG_ERROR, "sps_max_sub_layers out of range: %d\n",
926
               sps->max_sub_layers);
927
        return AVERROR_INVALIDDATA;
928
    }
929
930
986
    sps->temporal_id_nesting_flag = get_bits(gb, 1);
931
932
986
    if ((ret = parse_ptl(gb, avctx, &sps->ptl, sps->max_sub_layers)) < 0)
933
        return ret;
934
935
986
    *sps_id = get_ue_golomb_long(gb);
936
986
    if (*sps_id >= HEVC_MAX_SPS_COUNT) {
937
        av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", *sps_id);
938
        return AVERROR_INVALIDDATA;
939
    }
940
941
986
    sps->chroma_format_idc = get_ue_golomb_long(gb);
942
986
    if (sps->chroma_format_idc > 3U) {
943
        av_log(avctx, AV_LOG_ERROR, "chroma_format_idc %d is invalid\n", sps->chroma_format_idc);
944
        return AVERROR_INVALIDDATA;
945
    }
946
947
986
    if (sps->chroma_format_idc == 3)
948
32
        sps->separate_colour_plane_flag = get_bits1(gb);
949
950
986
    if (sps->separate_colour_plane_flag)
951
        sps->chroma_format_idc = 0;
952
953
986
    sps->width  = get_ue_golomb_long(gb);
954
986
    sps->height = get_ue_golomb_long(gb);
955
986
    if ((ret = av_image_check_size(sps->width,
956
986
                                   sps->height, 0, avctx)) < 0)
957
        return ret;
958
959
986
    if (get_bits1(gb)) { // pic_conformance_flag
960
823
        int vert_mult  = hevc_sub_height_c[sps->chroma_format_idc];
961
823
        int horiz_mult = hevc_sub_width_c[sps->chroma_format_idc];
962
823
        sps->pic_conf_win.left_offset   = get_ue_golomb_long(gb) * horiz_mult;
963
823
        sps->pic_conf_win.right_offset  = get_ue_golomb_long(gb) * horiz_mult;
964
823
        sps->pic_conf_win.top_offset    = get_ue_golomb_long(gb) *  vert_mult;
965
823
        sps->pic_conf_win.bottom_offset = get_ue_golomb_long(gb) *  vert_mult;
966
967
823
        if (avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {
968
            av_log(avctx, AV_LOG_DEBUG,
969
                   "discarding sps conformance window, "
970
                   "original values are l:%u r:%u t:%u b:%u\n",
971
                   sps->pic_conf_win.left_offset,
972
                   sps->pic_conf_win.right_offset,
973
                   sps->pic_conf_win.top_offset,
974
                   sps->pic_conf_win.bottom_offset);
975
976
            sps->pic_conf_win.left_offset   =
977
            sps->pic_conf_win.right_offset  =
978
            sps->pic_conf_win.top_offset    =
979
            sps->pic_conf_win.bottom_offset = 0;
980
        }
981
823
        sps->output_window = sps->pic_conf_win;
982
    }
983
984
986
    sps->bit_depth   = get_ue_golomb_long(gb) + 8;
985
986
    bit_depth_chroma = get_ue_golomb_long(gb) + 8;
986

986
    if (sps->chroma_format_idc && bit_depth_chroma != sps->bit_depth) {
987
        av_log(avctx, AV_LOG_ERROR,
988
               "Luma bit depth (%d) is different from chroma bit depth (%d), "
989
               "this is unsupported.\n",
990
               sps->bit_depth, bit_depth_chroma);
991
        return AVERROR_INVALIDDATA;
992
    }
993
986
    sps->bit_depth_chroma = bit_depth_chroma;
994
995
986
    ret = map_pixel_format(avctx, sps);
996
986
    if (ret < 0)
997
        return ret;
998
999
986
    sps->log2_max_poc_lsb = get_ue_golomb_long(gb) + 4;
1000
986
    if (sps->log2_max_poc_lsb > 16) {
1001
        av_log(avctx, AV_LOG_ERROR, "log2_max_pic_order_cnt_lsb_minus4 out range: %d\n",
1002
               sps->log2_max_poc_lsb - 4);
1003
        return AVERROR_INVALIDDATA;
1004
    }
1005
1006
986
    sublayer_ordering_info = get_bits1(gb);
1007
986
    start = sublayer_ordering_info ? 0 : sps->max_sub_layers - 1;
1008
2119
    for (i = start; i < sps->max_sub_layers; i++) {
1009
1133
        sps->temporal_layer[i].max_dec_pic_buffering = get_ue_golomb_long(gb) + 1;
1010
1133
        sps->temporal_layer[i].num_reorder_pics      = get_ue_golomb_long(gb);
1011
1133
        sps->temporal_layer[i].max_latency_increase  = get_ue_golomb_long(gb) - 1;
1012
1133
        if (sps->temporal_layer[i].max_dec_pic_buffering > (unsigned)HEVC_MAX_DPB_SIZE) {
1013
            av_log(avctx, AV_LOG_ERROR, "sps_max_dec_pic_buffering_minus1 out of range: %d\n",
1014
                   sps->temporal_layer[i].max_dec_pic_buffering - 1U);
1015
            return AVERROR_INVALIDDATA;
1016
        }
1017
1133
        if (sps->temporal_layer[i].num_reorder_pics > sps->temporal_layer[i].max_dec_pic_buffering - 1) {
1018
            av_log(avctx, AV_LOG_WARNING, "sps_max_num_reorder_pics out of range: %d\n",
1019
                   sps->temporal_layer[i].num_reorder_pics);
1020
            if (avctx->err_recognition & AV_EF_EXPLODE ||
1021
                sps->temporal_layer[i].num_reorder_pics > HEVC_MAX_DPB_SIZE - 1) {
1022
                return AVERROR_INVALIDDATA;
1023
            }
1024
            sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[i].num_reorder_pics + 1;
1025
        }
1026
    }
1027
1028
986
    if (!sublayer_ordering_info) {
1029
211
        for (i = 0; i < start; i++) {
1030
82
            sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[start].max_dec_pic_buffering;
1031
82
            sps->temporal_layer[i].num_reorder_pics      = sps->temporal_layer[start].num_reorder_pics;
1032
82
            sps->temporal_layer[i].max_latency_increase  = sps->temporal_layer[start].max_latency_increase;
1033
        }
1034
    }
1035
1036
986
    sps->log2_min_cb_size                    = get_ue_golomb_long(gb) + 3;
1037
986
    sps->log2_diff_max_min_coding_block_size = get_ue_golomb_long(gb);
1038
986
    sps->log2_min_tb_size                    = get_ue_golomb_long(gb) + 2;
1039
986
    log2_diff_max_min_transform_block_size   = get_ue_golomb_long(gb);
1040
986
    sps->log2_max_trafo_size                 = log2_diff_max_min_transform_block_size +
1041
986
                                               sps->log2_min_tb_size;
1042
1043

986
    if (sps->log2_min_cb_size < 3 || sps->log2_min_cb_size > 30) {
1044
        av_log(avctx, AV_LOG_ERROR, "Invalid value %d for log2_min_cb_size", sps->log2_min_cb_size);
1045
        return AVERROR_INVALIDDATA;
1046
    }
1047
1048
986
    if (sps->log2_diff_max_min_coding_block_size > 30) {
1049
        av_log(avctx, AV_LOG_ERROR, "Invalid value %d for log2_diff_max_min_coding_block_size", sps->log2_diff_max_min_coding_block_size);
1050
        return AVERROR_INVALIDDATA;
1051
    }
1052
1053

986
    if (sps->log2_min_tb_size >= sps->log2_min_cb_size || sps->log2_min_tb_size < 2) {
1054
        av_log(avctx, AV_LOG_ERROR, "Invalid value for log2_min_tb_size");
1055
        return AVERROR_INVALIDDATA;
1056
    }
1057
1058

986
    if (log2_diff_max_min_transform_block_size < 0 || log2_diff_max_min_transform_block_size > 30) {
1059
        av_log(avctx, AV_LOG_ERROR, "Invalid value %d for log2_diff_max_min_transform_block_size", log2_diff_max_min_transform_block_size);
1060
        return AVERROR_INVALIDDATA;
1061
    }
1062
1063
986
    sps->max_transform_hierarchy_depth_inter = get_ue_golomb_long(gb);
1064
986
    sps->max_transform_hierarchy_depth_intra = get_ue_golomb_long(gb);
1065
1066
986
    sps->scaling_list_enable_flag = get_bits1(gb);
1067
986
    if (sps->scaling_list_enable_flag) {
1068
36
        set_default_scaling_list_data(&sps->scaling_list);
1069
1070
36
        if (get_bits1(gb)) {
1071
26
            ret = scaling_list_data(gb, avctx, &sps->scaling_list, sps);
1072
26
            if (ret < 0)
1073
                return ret;
1074
        }
1075
    }
1076
1077
986
    sps->amp_enabled_flag = get_bits1(gb);
1078
986
    sps->sao_enabled      = get_bits1(gb);
1079
1080
986
    sps->pcm_enabled_flag = get_bits1(gb);
1081
986
    if (sps->pcm_enabled_flag) {
1082
75
        sps->pcm.bit_depth   = get_bits(gb, 4) + 1;
1083
75
        sps->pcm.bit_depth_chroma = get_bits(gb, 4) + 1;
1084
75
        sps->pcm.log2_min_pcm_cb_size = get_ue_golomb_long(gb) + 3;
1085
150
        sps->pcm.log2_max_pcm_cb_size = sps->pcm.log2_min_pcm_cb_size +
1086
75
                                        get_ue_golomb_long(gb);
1087
75
        if (FFMAX(sps->pcm.bit_depth, sps->pcm.bit_depth_chroma) > sps->bit_depth) {
1088
            av_log(avctx, AV_LOG_ERROR,
1089
                   "PCM bit depth (%d, %d) is greater than normal bit depth (%d)\n",
1090
                   sps->pcm.bit_depth, sps->pcm.bit_depth_chroma, sps->bit_depth);
1091
            return AVERROR_INVALIDDATA;
1092
        }
1093
1094
75
        sps->pcm.loop_filter_disable_flag = get_bits1(gb);
1095
    }
1096
1097
986
    sps->nb_st_rps = get_ue_golomb_long(gb);
1098
986
    if (sps->nb_st_rps > HEVC_MAX_SHORT_TERM_REF_PIC_SETS) {
1099
        av_log(avctx, AV_LOG_ERROR, "Too many short term RPS: %d.\n",
1100
               sps->nb_st_rps);
1101
        return AVERROR_INVALIDDATA;
1102
    }
1103
10027
    for (i = 0; i < sps->nb_st_rps; i++) {
1104
9041
        if ((ret = ff_hevc_decode_short_term_rps(gb, avctx, &sps->st_rps[i],
1105
                                                 sps, 0)) < 0)
1106
            return ret;
1107
    }
1108
1109
986
    sps->long_term_ref_pics_present_flag = get_bits1(gb);
1110
986
    if (sps->long_term_ref_pics_present_flag) {
1111
101
        sps->num_long_term_ref_pics_sps = get_ue_golomb_long(gb);
1112
101
        if (sps->num_long_term_ref_pics_sps > HEVC_MAX_LONG_TERM_REF_PICS) {
1113
            av_log(avctx, AV_LOG_ERROR, "Too many long term ref pics: %d.\n",
1114
                   sps->num_long_term_ref_pics_sps);
1115
            return AVERROR_INVALIDDATA;
1116
        }
1117
165
        for (i = 0; i < sps->num_long_term_ref_pics_sps; i++) {
1118
64
            sps->lt_ref_pic_poc_lsb_sps[i]       = get_bits(gb, sps->log2_max_poc_lsb);
1119
64
            sps->used_by_curr_pic_lt_sps_flag[i] = get_bits1(gb);
1120
        }
1121
    }
1122
1123
986
    sps->sps_temporal_mvp_enabled_flag          = get_bits1(gb);
1124
986
    sps->sps_strong_intra_smoothing_enable_flag = get_bits1(gb);
1125
986
    sps->vui.sar = (AVRational){0, 1};
1126
986
    vui_present = get_bits1(gb);
1127
986
    if (vui_present)
1128
215
        decode_vui(gb, avctx, apply_defdispwin, sps);
1129
1130
986
    if (get_bits1(gb)) { // sps_extension_flag
1131
71
        sps->sps_range_extension_flag = get_bits1(gb);
1132
71
        skip_bits(gb, 7); //sps_extension_7bits = get_bits(gb, 7);
1133
71
        if (sps->sps_range_extension_flag) {
1134
51
            sps->transform_skip_rotation_enabled_flag = get_bits1(gb);
1135
51
            sps->transform_skip_context_enabled_flag  = get_bits1(gb);
1136
51
            sps->implicit_rdpcm_enabled_flag = get_bits1(gb);
1137
1138
51
            sps->explicit_rdpcm_enabled_flag = get_bits1(gb);
1139
1140
51
            sps->extended_precision_processing_flag = get_bits1(gb);
1141
51
            if (sps->extended_precision_processing_flag)
1142
                av_log(avctx, AV_LOG_WARNING,
1143
                   "extended_precision_processing_flag not yet implemented\n");
1144
1145
51
            sps->intra_smoothing_disabled_flag       = get_bits1(gb);
1146
51
            sps->high_precision_offsets_enabled_flag = get_bits1(gb);
1147
51
            if (sps->high_precision_offsets_enabled_flag)
1148
33
                av_log(avctx, AV_LOG_WARNING,
1149
                   "high_precision_offsets_enabled_flag not yet implemented\n");
1150
1151
51
            sps->persistent_rice_adaptation_enabled_flag = get_bits1(gb);
1152
1153
51
            sps->cabac_bypass_alignment_enabled_flag  = get_bits1(gb);
1154
51
            if (sps->cabac_bypass_alignment_enabled_flag)
1155
                av_log(avctx, AV_LOG_WARNING,
1156
                   "cabac_bypass_alignment_enabled_flag not yet implemented\n");
1157
        }
1158
    }
1159
986
    if (apply_defdispwin) {
1160
410
        sps->output_window.left_offset   += sps->vui.def_disp_win.left_offset;
1161
410
        sps->output_window.right_offset  += sps->vui.def_disp_win.right_offset;
1162
410
        sps->output_window.top_offset    += sps->vui.def_disp_win.top_offset;
1163
410
        sps->output_window.bottom_offset += sps->vui.def_disp_win.bottom_offset;
1164
    }
1165
1166
986
    ow = &sps->output_window;
1167
986
    if (ow->left_offset >= INT_MAX - ow->right_offset     ||
1168
986
        ow->top_offset  >= INT_MAX - ow->bottom_offset    ||
1169
986
        ow->left_offset + ow->right_offset  >= sps->width ||
1170
986
        ow->top_offset  + ow->bottom_offset >= sps->height) {
1171
        av_log(avctx, AV_LOG_WARNING, "Invalid cropping offsets: %u/%u/%u/%u\n",
1172
               ow->left_offset, ow->right_offset, ow->top_offset, ow->bottom_offset);
1173
        if (avctx->err_recognition & AV_EF_EXPLODE) {
1174
            return AVERROR_INVALIDDATA;
1175
        }
1176
        av_log(avctx, AV_LOG_WARNING,
1177
               "Displaying the whole video surface.\n");
1178
        memset(ow, 0, sizeof(*ow));
1179
        memset(&sps->pic_conf_win, 0, sizeof(sps->pic_conf_win));
1180
    }
1181
1182
    // Inferred parameters
1183
986
    sps->log2_ctb_size = sps->log2_min_cb_size +
1184
986
                         sps->log2_diff_max_min_coding_block_size;
1185
986
    sps->log2_min_pu_size = sps->log2_min_cb_size - 1;
1186
1187
986
    if (sps->log2_ctb_size > HEVC_MAX_LOG2_CTB_SIZE) {
1188
        av_log(avctx, AV_LOG_ERROR, "CTB size out of range: 2^%d\n", sps->log2_ctb_size);
1189
        return AVERROR_INVALIDDATA;
1190
    }
1191
986
    if (sps->log2_ctb_size < 4) {
1192
        av_log(avctx,
1193
               AV_LOG_ERROR,
1194
               "log2_ctb_size %d differs from the bounds of any known profile\n",
1195
               sps->log2_ctb_size);
1196
        avpriv_request_sample(avctx, "log2_ctb_size %d", sps->log2_ctb_size);
1197
        return AVERROR_INVALIDDATA;
1198
    }
1199
1200
986
    sps->ctb_width  = (sps->width  + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size;
1201
986
    sps->ctb_height = (sps->height + (1 << sps->log2_ctb_size) - 1) >> sps->log2_ctb_size;
1202
986
    sps->ctb_size   = sps->ctb_width * sps->ctb_height;
1203
1204
986
    sps->min_cb_width  = sps->width  >> sps->log2_min_cb_size;
1205
986
    sps->min_cb_height = sps->height >> sps->log2_min_cb_size;
1206
986
    sps->min_tb_width  = sps->width  >> sps->log2_min_tb_size;
1207
986
    sps->min_tb_height = sps->height >> sps->log2_min_tb_size;
1208
986
    sps->min_pu_width  = sps->width  >> sps->log2_min_pu_size;
1209
986
    sps->min_pu_height = sps->height >> sps->log2_min_pu_size;
1210
986
    sps->tb_mask       = (1 << (sps->log2_ctb_size - sps->log2_min_tb_size)) - 1;
1211
1212
986
    sps->qp_bd_offset = 6 * (sps->bit_depth - 8);
1213
1214
986
    if (av_mod_uintp2(sps->width, sps->log2_min_cb_size) ||
1215
986
        av_mod_uintp2(sps->height, sps->log2_min_cb_size)) {
1216
        av_log(avctx, AV_LOG_ERROR, "Invalid coded frame dimensions.\n");
1217
        return AVERROR_INVALIDDATA;
1218
    }
1219
1220
986
    if (sps->max_transform_hierarchy_depth_inter > sps->log2_ctb_size - sps->log2_min_tb_size) {
1221
        av_log(avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_inter out of range: %d\n",
1222
               sps->max_transform_hierarchy_depth_inter);
1223
        return AVERROR_INVALIDDATA;
1224
    }
1225
986
    if (sps->max_transform_hierarchy_depth_intra > sps->log2_ctb_size - sps->log2_min_tb_size) {
1226
        av_log(avctx, AV_LOG_ERROR, "max_transform_hierarchy_depth_intra out of range: %d\n",
1227
               sps->max_transform_hierarchy_depth_intra);
1228
        return AVERROR_INVALIDDATA;
1229
    }
1230
986
    if (sps->log2_max_trafo_size > FFMIN(sps->log2_ctb_size, 5)) {
1231
        av_log(avctx, AV_LOG_ERROR,
1232
               "max transform block size out of range: %d\n",
1233
               sps->log2_max_trafo_size);
1234
        return AVERROR_INVALIDDATA;
1235
    }
1236
1237
986
    if (get_bits_left(gb) < 0) {
1238
        av_log(avctx, AV_LOG_ERROR,
1239
               "Overread SPS by %d bits\n", -get_bits_left(gb));
1240
        return AVERROR_INVALIDDATA;
1241
    }
1242
1243
986
    return 0;
1244
}
1245
1246
986
int ff_hevc_decode_nal_sps(GetBitContext *gb, AVCodecContext *avctx,
1247
                           HEVCParamSets *ps, int apply_defdispwin)
1248
{
1249
    HEVCSPS *sps;
1250
986
    AVBufferRef *sps_buf = av_buffer_allocz(sizeof(*sps));
1251
    unsigned int sps_id;
1252
    int ret;
1253
    ptrdiff_t nal_size;
1254
1255
986
    if (!sps_buf)
1256
        return AVERROR(ENOMEM);
1257
986
    sps = (HEVCSPS*)sps_buf->data;
1258
1259
986
    av_log(avctx, AV_LOG_DEBUG, "Decoding SPS\n");
1260
1261
986
    nal_size = gb->buffer_end - gb->buffer;
1262
986
    if (nal_size > sizeof(sps->data)) {
1263
        av_log(avctx, AV_LOG_WARNING, "Truncating likely oversized SPS "
1264
               "(%"PTRDIFF_SPECIFIER" > %"SIZE_SPECIFIER")\n",
1265
               nal_size, sizeof(sps->data));
1266
        sps->data_size = sizeof(sps->data);
1267
    } else {
1268
986
        sps->data_size = nal_size;
1269
    }
1270
986
    memcpy(sps->data, gb->buffer, sps->data_size);
1271
1272
986
    ret = ff_hevc_parse_sps(sps, gb, &sps_id,
1273
                            apply_defdispwin,
1274
986
                            ps->vps_list, avctx);
1275
986
    if (ret < 0) {
1276
        av_buffer_unref(&sps_buf);
1277
        return ret;
1278
    }
1279
1280
986
    if (avctx->debug & FF_DEBUG_BITSTREAM) {
1281
        av_log(avctx, AV_LOG_DEBUG,
1282
               "Parsed SPS: id %d; coded wxh: %dx%d; "
1283
               "cropped wxh: %dx%d; pix_fmt: %s.\n",
1284
               sps_id, sps->width, sps->height,
1285
               sps->width - (sps->output_window.left_offset + sps->output_window.right_offset),
1286
               sps->height - (sps->output_window.top_offset + sps->output_window.bottom_offset),
1287
               av_get_pix_fmt_name(sps->pix_fmt));
1288
    }
1289
1290
    /* check if this is a repeat of an already parsed SPS, then keep the
1291
     * original one.
1292
     * otherwise drop all PPSes that depend on it */
1293
986
    if (ps->sps_list[sps_id] &&
1294
420
        !memcmp(ps->sps_list[sps_id]->data, sps_buf->data, sps_buf->size)) {
1295
412
        av_buffer_unref(&sps_buf);
1296
    } else {
1297
574
        remove_sps(ps, sps_id);
1298
574
        ps->sps_list[sps_id] = sps_buf;
1299
    }
1300
1301
986
    return 0;
1302
}
1303
1304
3194
static void hevc_pps_free(void *opaque, uint8_t *data)
1305
{
1306
3194
    HEVCPPS *pps = (HEVCPPS*)data;
1307
1308
3194
    av_freep(&pps->column_width);
1309
3194
    av_freep(&pps->row_height);
1310
3194
    av_freep(&pps->col_bd);
1311
3194
    av_freep(&pps->row_bd);
1312
3194
    av_freep(&pps->col_idxX);
1313
3194
    av_freep(&pps->ctb_addr_rs_to_ts);
1314
3194
    av_freep(&pps->ctb_addr_ts_to_rs);
1315
3194
    av_freep(&pps->tile_pos_rs);
1316
3194
    av_freep(&pps->tile_id);
1317
3194
    av_freep(&pps->min_tb_addr_zs_tab);
1318
1319
3194
    av_freep(&pps);
1320
3194
}
1321
1322
76
static int pps_range_extensions(GetBitContext *gb, AVCodecContext *avctx,
1323
                                HEVCPPS *pps, HEVCSPS *sps) {
1324
    int i;
1325
1326
76
    if (pps->transform_skip_enabled_flag) {
1327
76
        pps->log2_max_transform_skip_block_size = get_ue_golomb_long(gb) + 2;
1328
    }
1329
76
    pps->cross_component_prediction_enabled_flag = get_bits1(gb);
1330
76
    pps->chroma_qp_offset_list_enabled_flag = get_bits1(gb);
1331
76
    if (pps->chroma_qp_offset_list_enabled_flag) {
1332
10
        pps->diff_cu_chroma_qp_offset_depth = get_ue_golomb_long(gb);
1333
10
        pps->chroma_qp_offset_list_len_minus1 = get_ue_golomb_long(gb);
1334
10
        if (pps->chroma_qp_offset_list_len_minus1 > 5) {
1335
            av_log(avctx, AV_LOG_ERROR,
1336
                   "chroma_qp_offset_list_len_minus1 shall be in the range [0, 5].\n");
1337
            return AVERROR_INVALIDDATA;
1338
        }
1339
20
        for (i = 0; i <= pps->chroma_qp_offset_list_len_minus1; i++) {
1340
10
            pps->cb_qp_offset_list[i] = get_se_golomb_long(gb);
1341
10
            if (pps->cb_qp_offset_list[i]) {
1342
10
                av_log(avctx, AV_LOG_WARNING,
1343
                       "cb_qp_offset_list not tested yet.\n");
1344
            }
1345
10
            pps->cr_qp_offset_list[i] = get_se_golomb_long(gb);
1346
10
            if (pps->cr_qp_offset_list[i]) {
1347
10
                av_log(avctx, AV_LOG_WARNING,
1348
                       "cb_qp_offset_list not tested yet.\n");
1349
            }
1350
        }
1351
    }
1352
76
    pps->log2_sao_offset_scale_luma = get_ue_golomb_long(gb);
1353
76
    pps->log2_sao_offset_scale_chroma = get_ue_golomb_long(gb);
1354
1355
76
    if (   pps->log2_sao_offset_scale_luma   > FFMAX(sps->bit_depth        - 10, 0)
1356
76
        || pps->log2_sao_offset_scale_chroma > FFMAX(sps->bit_depth_chroma - 10, 0)
1357
    )
1358
        return AVERROR_INVALIDDATA;
1359
1360
76
    return(0);
1361
}
1362
1363
3190
static inline int setup_pps(AVCodecContext *avctx, GetBitContext *gb,
1364
                            HEVCPPS *pps, HEVCSPS *sps)
1365
{
1366
    int log2_diff;
1367
    int pic_area_in_ctbs;
1368
    int i, j, x, y, ctb_addr_rs, tile_id;
1369
1370
    // Inferred parameters
1371
3190
    pps->col_bd   = av_malloc_array(pps->num_tile_columns + 1, sizeof(*pps->col_bd));
1372
3190
    pps->row_bd   = av_malloc_array(pps->num_tile_rows + 1,    sizeof(*pps->row_bd));
1373
3190
    pps->col_idxX = av_malloc_array(sps->ctb_width,    sizeof(*pps->col_idxX));
1374

3190
    if (!pps->col_bd || !pps->row_bd || !pps->col_idxX)
1375
        return AVERROR(ENOMEM);
1376
1377
3190
    if (pps->uniform_spacing_flag) {
1378
2662
        if (!pps->column_width) {
1379
2291
            pps->column_width = av_malloc_array(pps->num_tile_columns, sizeof(*pps->column_width));
1380
2291
            pps->row_height   = av_malloc_array(pps->num_tile_rows,    sizeof(*pps->row_height));
1381
        }
1382

2662
        if (!pps->column_width || !pps->row_height)
1383
            return AVERROR(ENOMEM);
1384
1385
5576
        for (i = 0; i < pps->num_tile_columns; i++) {
1386
2914
            pps->column_width[i] = ((i + 1) * sps->ctb_width) / pps->num_tile_columns -
1387
2914
                                   (i * sps->ctb_width) / pps->num_tile_columns;
1388
        }
1389
1390
5607
        for (i = 0; i < pps->num_tile_rows; i++) {
1391
2945
            pps->row_height[i] = ((i + 1) * sps->ctb_height) / pps->num_tile_rows -
1392
2945
                                 (i * sps->ctb_height) / pps->num_tile_rows;
1393
        }
1394
    }
1395
1396
3190
    pps->col_bd[0] = 0;
1397
8704
    for (i = 0; i < pps->num_tile_columns; i++)
1398
5514
        pps->col_bd[i + 1] = pps->col_bd[i] + pps->column_width[i];
1399
1400
3190
    pps->row_bd[0] = 0;
1401
8725
    for (i = 0; i < pps->num_tile_rows; i++)
1402
5535
        pps->row_bd[i + 1] = pps->row_bd[i] + pps->row_height[i];
1403
1404
57193
    for (i = 0, j = 0; i < sps->ctb_width; i++) {
1405
54003
        if (i > pps->col_bd[j])
1406
5500
            j++;
1407
54003
        pps->col_idxX[i] = j;
1408
    }
1409
1410
    /**
1411
     * 6.5
1412
     */
1413
3190
    pic_area_in_ctbs     = sps->ctb_width    * sps->ctb_height;
1414
1415
3190
    pps->ctb_addr_rs_to_ts = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->ctb_addr_rs_to_ts));
1416
3190
    pps->ctb_addr_ts_to_rs = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->ctb_addr_ts_to_rs));
1417
3190
    pps->tile_id           = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->tile_id));
1418
3190
    pps->min_tb_addr_zs_tab = av_malloc_array((sps->tb_mask+2) * (sps->tb_mask+2), sizeof(*pps->min_tb_addr_zs_tab));
1419

3190
    if (!pps->ctb_addr_rs_to_ts || !pps->ctb_addr_ts_to_rs ||
1420

3190
        !pps->tile_id || !pps->min_tb_addr_zs_tab) {
1421
        return AVERROR(ENOMEM);
1422
    }
1423
1424
720497
    for (ctb_addr_rs = 0; ctb_addr_rs < pic_area_in_ctbs; ctb_addr_rs++) {
1425
717307
        int tb_x   = ctb_addr_rs % sps->ctb_width;
1426
717307
        int tb_y   = ctb_addr_rs / sps->ctb_width;
1427
717307
        int tile_x = 0;
1428
717307
        int tile_y = 0;
1429
717307
        int val    = 0;
1430
1431
1225369
        for (i = 0; i < pps->num_tile_columns; i++) {
1432
1225369
            if (tb_x < pps->col_bd[i + 1]) {
1433
717307
                tile_x = i;
1434
717307
                break;
1435
            }
1436
        }
1437
1438
1075573
        for (i = 0; i < pps->num_tile_rows; i++) {
1439
1075573
            if (tb_y < pps->row_bd[i + 1]) {
1440
717307
                tile_y = i;
1441
717307
                break;
1442
            }
1443
        }
1444
1445
1225369
        for (i = 0; i < tile_x; i++)
1446
508062
            val += pps->row_height[tile_y] * pps->column_width[i];
1447
1075573
        for (i = 0; i < tile_y; i++)
1448
358266
            val += sps->ctb_width * pps->row_height[i];
1449
1450
717307
        val += (tb_y - pps->row_bd[tile_y]) * pps->column_width[tile_x] +
1451
717307
               tb_x - pps->col_bd[tile_x];
1452
1453
717307
        pps->ctb_addr_rs_to_ts[ctb_addr_rs] = val;
1454
717307
        pps->ctb_addr_ts_to_rs[val]         = ctb_addr_rs;
1455
    }
1456
1457
8725
    for (j = 0, tile_id = 0; j < pps->num_tile_rows; j++)
1458
21650
        for (i = 0; i < pps->num_tile_columns; i++, tile_id++)
1459
92028
            for (y = pps->row_bd[j]; y < pps->row_bd[j + 1]; y++)
1460
793220
                for (x = pps->col_bd[i]; x < pps->col_bd[i + 1]; x++)
1461
717307
                    pps->tile_id[pps->ctb_addr_rs_to_ts[y * sps->ctb_width + x]] = tile_id;
1462
1463
3190
    pps->tile_pos_rs = av_malloc_array(tile_id, sizeof(*pps->tile_pos_rs));
1464
3190
    if (!pps->tile_pos_rs)
1465
        return AVERROR(ENOMEM);
1466
1467
8725
    for (j = 0; j < pps->num_tile_rows; j++)
1468
21650
        for (i = 0; i < pps->num_tile_columns; i++)
1469
16115
            pps->tile_pos_rs[j * pps->num_tile_columns + i] =
1470
16115
                pps->row_bd[j] * sps->ctb_width + pps->col_bd[i];
1471
1472
3190
    log2_diff = sps->log2_ctb_size - sps->log2_min_tb_size;
1473
3190
    pps->min_tb_addr_zs = &pps->min_tb_addr_zs_tab[1*(sps->tb_mask+2)+1];
1474
56360
    for (y = 0; y < sps->tb_mask+2; y++) {
1475
53170
        pps->min_tb_addr_zs_tab[y*(sps->tb_mask+2)] = -1;
1476
53170
        pps->min_tb_addr_zs_tab[y]    = -1;
1477
    }
1478
53170
    for (y = 0; y < sps->tb_mask+1; y++) {
1479
843244
        for (x = 0; x < sps->tb_mask+1; x++) {
1480
793264
            int tb_x = x >> log2_diff;
1481
793264
            int tb_y = y >> log2_diff;
1482
793264
            int rs   = sps->ctb_width * tb_y + tb_x;
1483
793264
            int val  = pps->ctb_addr_rs_to_ts[rs] << (log2_diff * 2);
1484
3960592
            for (i = 0; i < log2_diff; i++) {
1485
3167328
                int m = 1 << i;
1486

3167328
                val += (m & x ? m * m : 0) + (m & y ? 2 * m * m : 0);
1487
            }
1488
793264
            pps->min_tb_addr_zs[y * (sps->tb_mask+2) + x] = val;
1489
        }
1490
    }
1491
1492
3190
    return 0;
1493
}
1494
1495
3194
int ff_hevc_decode_nal_pps(GetBitContext *gb, AVCodecContext *avctx,
1496
                           HEVCParamSets *ps)
1497
{
1498
3194
    HEVCSPS      *sps = NULL;
1499
3194
    int i, ret = 0;
1500
3194
    unsigned int pps_id = 0;
1501
    ptrdiff_t nal_size;
1502
    unsigned log2_parallel_merge_level_minus2;
1503
1504
    AVBufferRef *pps_buf;
1505
3194
    HEVCPPS *pps = av_mallocz(sizeof(*pps));
1506
1507
3194
    if (!pps)
1508
        return AVERROR(ENOMEM);
1509
1510
3194
    pps_buf = av_buffer_create((uint8_t *)pps, sizeof(*pps),
1511
                               hevc_pps_free, NULL, 0);
1512
3194
    if (!pps_buf) {
1513
        av_freep(&pps);
1514
        return AVERROR(ENOMEM);
1515
    }
1516
1517
3194
    av_log(avctx, AV_LOG_DEBUG, "Decoding PPS\n");
1518
1519
3194
    nal_size = gb->buffer_end - gb->buffer;
1520
3194
    if (nal_size > sizeof(pps->data)) {
1521
        av_log(avctx, AV_LOG_WARNING, "Truncating likely oversized PPS "
1522
               "(%"PTRDIFF_SPECIFIER" > %"SIZE_SPECIFIER")\n",
1523
               nal_size, sizeof(pps->data));
1524
        pps->data_size = sizeof(pps->data);
1525
    } else {
1526
3194
        pps->data_size = nal_size;
1527
    }
1528
3194
    memcpy(pps->data, gb->buffer, pps->data_size);
1529
1530
    // Default values
1531
3194
    pps->loop_filter_across_tiles_enabled_flag = 1;
1532
3194
    pps->num_tile_columns                      = 1;
1533
3194
    pps->num_tile_rows                         = 1;
1534
3194
    pps->uniform_spacing_flag                  = 1;
1535
3194
    pps->disable_dbf                           = 0;
1536
3194
    pps->beta_offset                           = 0;
1537
3194
    pps->tc_offset                             = 0;
1538
3194
    pps->log2_max_transform_skip_block_size    = 2;
1539
1540
    // Coded parameters
1541
3194
    pps_id = get_ue_golomb_long(gb);
1542
3194
    if (pps_id >= HEVC_MAX_PPS_COUNT) {
1543
        av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", pps_id);
1544
        ret = AVERROR_INVALIDDATA;
1545
        goto err;
1546
    }
1547
3194
    pps->sps_id = get_ue_golomb_long(gb);
1548
3194
    if (pps->sps_id >= HEVC_MAX_SPS_COUNT) {
1549
        av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", pps->sps_id);
1550
        ret = AVERROR_INVALIDDATA;
1551
        goto err;
1552
    }
1553
3194
    if (!ps->sps_list[pps->sps_id]) {
1554
4
        av_log(avctx, AV_LOG_ERROR, "SPS %u does not exist.\n", pps->sps_id);
1555
4
        ret = AVERROR_INVALIDDATA;
1556
4
        goto err;
1557
    }
1558
3190
    sps = (HEVCSPS *)ps->sps_list[pps->sps_id]->data;
1559
1560
3190
    pps->dependent_slice_segments_enabled_flag = get_bits1(gb);
1561
3190
    pps->output_flag_present_flag              = get_bits1(gb);
1562
3190
    pps->num_extra_slice_header_bits           = get_bits(gb, 3);
1563
1564
3190
    pps->sign_data_hiding_flag = get_bits1(gb);
1565
1566
3190
    pps->cabac_init_present_flag = get_bits1(gb);
1567
1568
3190
    pps->num_ref_idx_l0_default_active = get_ue_golomb_long(gb) + 1;
1569
3190
    pps->num_ref_idx_l1_default_active = get_ue_golomb_long(gb) + 1;
1570
1571
3190
    pps->pic_init_qp_minus26 = get_se_golomb(gb);
1572
1573
3190
    pps->constrained_intra_pred_flag = get_bits1(gb);
1574
3190
    pps->transform_skip_enabled_flag = get_bits1(gb);
1575
1576
3190
    pps->cu_qp_delta_enabled_flag = get_bits1(gb);
1577
3190
    pps->diff_cu_qp_delta_depth   = 0;
1578
3190
    if (pps->cu_qp_delta_enabled_flag)
1579
476
        pps->diff_cu_qp_delta_depth = get_ue_golomb_long(gb);
1580
1581
3190
    if (pps->diff_cu_qp_delta_depth < 0 ||
1582
3190
        pps->diff_cu_qp_delta_depth > sps->log2_diff_max_min_coding_block_size) {
1583
        av_log(avctx, AV_LOG_ERROR, "diff_cu_qp_delta_depth %d is invalid\n",
1584
               pps->diff_cu_qp_delta_depth);
1585
        ret = AVERROR_INVALIDDATA;
1586
        goto err;
1587
    }
1588
1589
3190
    pps->cb_qp_offset = get_se_golomb(gb);
1590

3190
    if (pps->cb_qp_offset < -12 || pps->cb_qp_offset > 12) {
1591
        av_log(avctx, AV_LOG_ERROR, "pps_cb_qp_offset out of range: %d\n",
1592
               pps->cb_qp_offset);
1593
        ret = AVERROR_INVALIDDATA;
1594
        goto err;
1595
    }
1596
3190
    pps->cr_qp_offset = get_se_golomb(gb);
1597

3190
    if (pps->cr_qp_offset < -12 || pps->cr_qp_offset > 12) {
1598
        av_log(avctx, AV_LOG_ERROR, "pps_cr_qp_offset out of range: %d\n",
1599
               pps->cr_qp_offset);
1600
        ret = AVERROR_INVALIDDATA;
1601
        goto err;
1602
    }
1603
3190
    pps->pic_slice_level_chroma_qp_offsets_present_flag = get_bits1(gb);
1604
1605
3190
    pps->weighted_pred_flag   = get_bits1(gb);
1606
3190
    pps->weighted_bipred_flag = get_bits1(gb);
1607
1608
3190
    pps->transquant_bypass_enable_flag    = get_bits1(gb);
1609
3190
    pps->tiles_enabled_flag               = get_bits1(gb);
1610
3190
    pps->entropy_coding_sync_enabled_flag = get_bits1(gb);
1611
1612
3190
    if (pps->tiles_enabled_flag) {
1613
899
        int num_tile_columns_minus1 = get_ue_golomb(gb);
1614
899
        int num_tile_rows_minus1    = get_ue_golomb(gb);
1615
1616
899
        if (num_tile_columns_minus1 < 0 ||
1617
899
            num_tile_columns_minus1 >= sps->ctb_width) {
1618
            av_log(avctx, AV_LOG_ERROR, "num_tile_columns_minus1 out of range: %d\n",
1619
                   num_tile_columns_minus1);
1620
            ret = num_tile_columns_minus1 < 0 ? num_tile_columns_minus1 : AVERROR_INVALIDDATA;
1621
            goto err;
1622
        }
1623
899
        if (num_tile_rows_minus1 < 0 ||
1624
899
            num_tile_rows_minus1 >= sps->ctb_height) {
1625
            av_log(avctx, AV_LOG_ERROR, "num_tile_rows_minus1 out of range: %d\n",
1626
                   num_tile_rows_minus1);
1627
            ret = num_tile_rows_minus1 < 0 ? num_tile_rows_minus1 : AVERROR_INVALIDDATA;
1628
            goto err;
1629
        }
1630
899
        pps->num_tile_columns = num_tile_columns_minus1 + 1;
1631
899
        pps->num_tile_rows    = num_tile_rows_minus1    + 1;
1632
1633
899
        pps->column_width = av_malloc_array(pps->num_tile_columns, sizeof(*pps->column_width));
1634
899
        pps->row_height   = av_malloc_array(pps->num_tile_rows,    sizeof(*pps->row_height));
1635

899
        if (!pps->column_width || !pps->row_height) {
1636
            ret = AVERROR(ENOMEM);
1637
            goto err;
1638
        }
1639
1640
899
        pps->uniform_spacing_flag = get_bits1(gb);
1641
899
        if (!pps->uniform_spacing_flag) {
1642
528
            uint64_t sum = 0;
1643
2600
            for (i = 0; i < pps->num_tile_columns - 1; i++) {
1644
2072
                pps->column_width[i] = get_ue_golomb_long(gb) + 1;
1645
2072
                sum                 += pps->column_width[i];
1646
            }
1647
528
            if (sum >= sps->ctb_width) {
1648
                av_log(avctx, AV_LOG_ERROR, "Invalid tile widths.\n");
1649
                ret = AVERROR_INVALIDDATA;
1650
                goto err;
1651
            }
1652
528
            pps->column_width[pps->num_tile_columns - 1] = sps->ctb_width - sum;
1653
1654
528
            sum = 0;
1655
2590
            for (i = 0; i < pps->num_tile_rows - 1; i++) {
1656
2062
                pps->row_height[i] = get_ue_golomb_long(gb) + 1;
1657
2062
                sum               += pps->row_height[i];
1658
            }
1659
528
            if (sum >= sps->ctb_height) {
1660
                av_log(avctx, AV_LOG_ERROR, "Invalid tile heights.\n");
1661
                ret = AVERROR_INVALIDDATA;
1662
                goto err;
1663
            }
1664
528
            pps->row_height[pps->num_tile_rows - 1] = sps->ctb_height - sum;
1665
        }
1666
899
        pps->loop_filter_across_tiles_enabled_flag = get_bits1(gb);
1667
    }
1668
1669
3190
    pps->seq_loop_filter_across_slices_enabled_flag = get_bits1(gb);
1670
1671
3190
    pps->deblocking_filter_control_present_flag = get_bits1(gb);
1672
3190
    if (pps->deblocking_filter_control_present_flag) {
1673
994
        pps->deblocking_filter_override_enabled_flag = get_bits1(gb);
1674
994
        pps->disable_dbf                             = get_bits1(gb);
1675
994
        if (!pps->disable_dbf) {
1676
852
            int beta_offset_div2 = get_se_golomb(gb);
1677
852
            int tc_offset_div2   = get_se_golomb(gb) ;
1678

852
            if (beta_offset_div2 < -6 || beta_offset_div2 > 6) {
1679
                av_log(avctx, AV_LOG_ERROR, "pps_beta_offset_div2 out of range: %d\n",
1680
                       beta_offset_div2);
1681
                ret = AVERROR_INVALIDDATA;
1682
                goto err;
1683
            }
1684

852
            if (tc_offset_div2 < -6 || tc_offset_div2 > 6) {
1685
                av_log(avctx, AV_LOG_ERROR, "pps_tc_offset_div2 out of range: %d\n",
1686
                       tc_offset_div2);
1687
                ret = AVERROR_INVALIDDATA;
1688
                goto err;
1689
            }
1690
852
            pps->beta_offset = 2 * beta_offset_div2;
1691
852
            pps->tc_offset   = 2 *   tc_offset_div2;
1692
        }
1693
    }
1694
1695
3190
    pps->scaling_list_data_present_flag = get_bits1(gb);
1696
3190
    if (pps->scaling_list_data_present_flag) {
1697
463
        set_default_scaling_list_data(&pps->scaling_list);
1698
463
        ret = scaling_list_data(gb, avctx, &pps->scaling_list, sps);
1699
463
        if (ret < 0)
1700
            goto err;
1701
    }
1702
3190
    pps->lists_modification_present_flag = get_bits1(gb);
1703
3190
    log2_parallel_merge_level_minus2     = get_ue_golomb_long(gb);
1704
3190
    if (log2_parallel_merge_level_minus2 > sps->log2_ctb_size) {
1705
        av_log(avctx, AV_LOG_ERROR, "log2_parallel_merge_level_minus2 out of range: %d\n",
1706
               log2_parallel_merge_level_minus2);
1707
        ret = AVERROR_INVALIDDATA;
1708
        goto err;
1709
    }
1710
3190
    pps->log2_parallel_merge_level       = log2_parallel_merge_level_minus2 + 2;
1711
1712
3190
    pps->slice_header_extension_present_flag = get_bits1(gb);
1713
1714
3190
    if (get_bits1(gb)) { // pps_extension_present_flag
1715
91
        pps->pps_range_extensions_flag = get_bits1(gb);
1716
91
        skip_bits(gb, 7); // pps_extension_7bits
1717

91
        if (sps->ptl.general_ptl.profile_idc == FF_PROFILE_HEVC_REXT && pps->pps_range_extensions_flag) {
1718
76
            if ((ret = pps_range_extensions(gb, avctx, pps, sps)) < 0)
1719
                goto err;
1720
        }
1721
    }
1722
1723
3190
    ret = setup_pps(avctx, gb, pps, sps);
1724
3190
    if (ret < 0)
1725
        goto err;
1726
1727
3190
    if (get_bits_left(gb) < 0) {
1728
        av_log(avctx, AV_LOG_ERROR,
1729
               "Overread PPS by %d bits\n", -get_bits_left(gb));
1730
        goto err;
1731
    }
1732
1733
3190
    remove_pps(ps, pps_id);
1734
3190
    ps->pps_list[pps_id] = pps_buf;
1735
1736
3190
    return 0;
1737
1738
4
err:
1739
4
    av_buffer_unref(&pps_buf);
1740
4
    return ret;
1741
}
1742
1743
561
void ff_hevc_ps_uninit(HEVCParamSets *ps)
1744
{
1745
    int i;
1746
1747
9537
    for (i = 0; i < FF_ARRAY_ELEMS(ps->vps_list); i++)
1748
8976
        av_buffer_unref(&ps->vps_list[i]);
1749
9537
    for (i = 0; i < FF_ARRAY_ELEMS(ps->sps_list); i++)
1750
8976
        av_buffer_unref(&ps->sps_list[i]);
1751
36465
    for (i = 0; i < FF_ARRAY_ELEMS(ps->pps_list); i++)
1752
35904
        av_buffer_unref(&ps->pps_list[i]);
1753
1754
561
    ps->sps = NULL;
1755
561
    ps->pps = NULL;
1756
561
    ps->vps = NULL;
1757
561
}
1758
1759
30192
int ff_hevc_compute_poc(const HEVCSPS *sps, int pocTid0, int poc_lsb, int nal_unit_type)
1760
{
1761
30192
    int max_poc_lsb  = 1 << sps->log2_max_poc_lsb;
1762
30192
    int prev_poc_lsb = pocTid0 % max_poc_lsb;
1763
30192
    int prev_poc_msb = pocTid0 - prev_poc_lsb;
1764
    int poc_msb;
1765
1766

30192
    if (poc_lsb < prev_poc_lsb && prev_poc_lsb - poc_lsb >= max_poc_lsb / 2)
1767
40
        poc_msb = prev_poc_msb + max_poc_lsb;
1768

30152
    else if (poc_lsb > prev_poc_lsb && poc_lsb - prev_poc_lsb > max_poc_lsb / 2)
1769
252
        poc_msb = prev_poc_msb - max_poc_lsb;
1770
    else
1771
29900
        poc_msb = prev_poc_msb;
1772
1773
    // For BLA picture types, POCmsb is set to 0.
1774

30192
    if (nal_unit_type == HEVC_NAL_BLA_W_LP   ||
1775
30171
        nal_unit_type == HEVC_NAL_BLA_W_RADL ||
1776
        nal_unit_type == HEVC_NAL_BLA_N_LP)
1777
24
        poc_msb = 0;
1778
1779
30192
    return poc_msb + poc_lsb;
1780
}