GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/hevc_ps.c Lines: 850 1097 77.5 %
Date: 2021-01-21 13:05:02 Branches: 506 739 68.5 %

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
3210
static void remove_pps(HEVCParamSets *s, int id)
82
{
83

3210
    if (s->pps_list[id] && s->pps == (const HEVCPPS*)s->pps_list[id]->data)
84
1785
        s->pps = NULL;
85
3210
    av_buffer_unref(&s->pps_list[id]);
86
3210
}
87
88
583
static void remove_sps(HEVCParamSets *s, int id)
89
{
90
    int i;
91
583
    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
583
    av_buffer_unref(&s->sps_list[id]);
103
583
}
104
105
570
static void remove_vps(HEVCParamSets *s, int id)
106
{
107
    int i;
108
570
    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
570
    av_buffer_unref(&s->vps_list[id]);
117
570
}
118
119
12258
int ff_hevc_decode_short_term_rps(GetBitContext *gb, AVCodecContext *avctx,
120
                                  ShortTermRPS *rps, const HEVCSPS *sps, int is_slice_header)
121
{
122
12258
    uint8_t rps_predict = 0;
123
    int delta_poc;
124
12258
    int k0 = 0;
125
12258
    int k1 = 0;
126
12258
    int k  = 0;
127
    int i;
128
129

12258
    if (rps != sps->st_rps && sps->nb_st_rps)
130
11107
        rps_predict = get_bits1(gb);
131
132
12258
    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
4899
        rps->num_negative_pics = get_ue_golomb_long(gb);
223
4899
        nb_positive_pics       = get_ue_golomb_long(gb);
224
225

4899
        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
4899
        rps->num_delta_pocs = rps->num_negative_pics + nb_positive_pics;
232
4899
        if (rps->num_delta_pocs) {
233
4582
            prev = 0;
234
18412
            for (i = 0; i < rps->num_negative_pics; i++) {
235
13830
                delta_poc = get_ue_golomb_long(gb) + 1;
236

13830
                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
13830
                prev -= delta_poc;
243
13830
                rps->delta_poc[i] = prev;
244
13830
                rps->used[i]      = get_bits1(gb);
245
            }
246
4582
            prev = 0;
247
5759
            for (i = 0; i < nb_positive_pics; i++) {
248
1177
                delta_poc = get_ue_golomb_long(gb) + 1;
249

1177
                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
1177
                prev += delta_poc;
256
1177
                rps->delta_poc[rps->num_negative_pics + i] = prev;
257
1177
                rps->used[rps->num_negative_pics + i]      = get_bits1(gb);
258
            }
259
        }
260
    }
261
12258
    return 0;
262
}
263
264
265
2049
static int decode_profile_tier_level(GetBitContext *gb, AVCodecContext *avctx,
266
                                      PTLCommon *ptl)
267
{
268
    int i;
269
270
2049
    if (get_bits_left(gb) < 2+1+5 + 32 + 4 + 43 + 1)
271
        return -1;
272
273
2049
    ptl->profile_space = get_bits(gb, 2);
274
2049
    ptl->tier_flag     = get_bits1(gb);
275
2049
    ptl->profile_idc   = get_bits(gb, 5);
276
2049
    if (ptl->profile_idc == FF_PROFILE_HEVC_MAIN)
277
1751
        av_log(avctx, AV_LOG_DEBUG, "Main profile bitstream\n");
278
298
    else if (ptl->profile_idc == FF_PROFILE_HEVC_MAIN_10)
279
120
        av_log(avctx, AV_LOG_DEBUG, "Main 10 profile bitstream\n");
280
178
    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
170
    else if (ptl->profile_idc == FF_PROFILE_HEVC_REXT)
283
130
        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
67617
    for (i = 0; i < 32; i++) {
288
65568
        ptl->profile_compatibility_flag[i] = get_bits1(gb);
289
290

65568
        if (ptl->profile_idc == 0 && i > 0 && ptl->profile_compatibility_flag[i])
291
40
            ptl->profile_idc = i;
292
    }
293
2049
    ptl->progressive_source_flag    = get_bits1(gb);
294
2049
    ptl->interlaced_source_flag     = get_bits1(gb);
295
2049
    ptl->non_packed_constraint_flag = get_bits1(gb);
296
2049
    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



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



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

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



130
        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
130
            skip_bits_long(gb, 34); // XXX_reserved_zero_34bits[0..33]
320
        }
321

1919
    } else if (check_profile_idc(2)) {
322
1607
        skip_bits(gb, 7);
323
1607
        ptl->one_picture_only_constraint_flag = get_bits1(gb);
324
1607
        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



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



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

3994
    if (decode_profile_tier_level(gb, avctx, &ptl->general_ptl) < 0 ||
344
1997
        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
1997
    ptl->general_ptl.level_idc = get_bits(gb, 8);
350
351
2465
    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
1997
    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
2465
    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
1997
    return 0;
377
}
378
379
97
static void decode_sublayer_hrd(GetBitContext *gb, unsigned int nb_cpb,
380
                                int subpic_params_present)
381
{
382
    int i;
383
384
194
    for (i = 0; i < nb_cpb; i++) {
385
97
        get_ue_golomb_long(gb); // bit_rate_value_minus1
386
97
        get_ue_golomb_long(gb); // cpb_size_value_minus1
387
388
97
        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
97
        skip_bits1(gb); // cbr_flag
393
    }
394
97
}
395
396
51
static int decode_hrd(GetBitContext *gb, int common_inf_present,
397
                       int max_sublayers)
398
{
399
51
    int nal_params_present = 0, vcl_params_present = 0;
400
51
    int subpic_params_present = 0;
401
    int i;
402
403
51
    if (common_inf_present) {
404
51
        nal_params_present = get_bits1(gb);
405
51
        vcl_params_present = get_bits1(gb);
406
407

51
        if (nal_params_present || vcl_params_present) {
408
51
            subpic_params_present = get_bits1(gb);
409
410
51
            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
51
            skip_bits(gb, 4); // bit_rate_scale
418
51
            skip_bits(gb, 4); // cpb_size_scale
419
420
51
            if (subpic_params_present)
421
13
                skip_bits(gb, 4);  // cpb_size_du_scale
422
423
51
            skip_bits(gb, 5); // initial_cpb_removal_delay_length_minus1
424
51
            skip_bits(gb, 5); // au_cpb_removal_delay_length_minus1
425
51
            skip_bits(gb, 5); // dpb_output_delay_length_minus1
426
        }
427
    }
428
429
102
    for (i = 0; i < max_sublayers; i++) {
430
51
        int low_delay = 0;
431
51
        unsigned int nb_cpb = 1;
432
51
        int fixed_rate = get_bits1(gb);
433
434
51
        if (!fixed_rate)
435
23
            fixed_rate = get_bits1(gb);
436
437
51
        if (fixed_rate)
438
28
            get_ue_golomb_long(gb);  // elemental_duration_in_tc_minus1
439
        else
440
23
            low_delay = get_bits1(gb);
441
442
51
        if (!low_delay) {
443
51
            nb_cpb = get_ue_golomb_long(gb) + 1;
444

51
            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
51
        if (nal_params_present)
451
51
            decode_sublayer_hrd(gb, nb_cpb, subpic_params_present);
452
51
        if (vcl_params_present)
453
46
            decode_sublayer_hrd(gb, nb_cpb, subpic_params_present);
454
    }
455
51
    return 0;
456
}
457
458
1002
int ff_hevc_decode_nal_vps(GetBitContext *gb, AVCodecContext *avctx,
459
                           HEVCParamSets *ps)
460
{
461
    int i,j;
462
1002
    int vps_id = 0;
463
    ptrdiff_t nal_size;
464
    HEVCVPS *vps;
465
1002
    AVBufferRef *vps_buf = av_buffer_allocz(sizeof(*vps));
466
467
1002
    if (!vps_buf)
468
        return AVERROR(ENOMEM);
469
1002
    vps = (HEVCVPS*)vps_buf->data;
470
471
1002
    av_log(avctx, AV_LOG_DEBUG, "Decoding VPS\n");
472
473
1002
    nal_size = gb->buffer_end - gb->buffer;
474
1002
    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
1002
        vps->data_size = nal_size;
481
    }
482
1002
    memcpy(vps->data, gb->buffer, vps->data_size);
483
484
1002
    vps_id = get_bits(gb, 4);
485
486
1002
    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
1002
    vps->vps_max_layers               = get_bits(gb, 6) + 1;
492
1002
    vps->vps_max_sub_layers           = get_bits(gb, 3) + 1;
493
1002
    vps->vps_temporal_id_nesting_flag = get_bits1(gb);
494
495
1002
    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
1002
    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
1002
    if (parse_ptl(gb, avctx, &vps->ptl, vps->vps_max_sub_layers) < 0)
507
        goto err;
508
509
1002
    vps->vps_sub_layer_ordering_info_present_flag = get_bits1(gb);
510
511
1002
    i = vps->vps_sub_layer_ordering_info_present_flag ? 0 : vps->vps_max_sub_layers - 1;
512
2151
    for (; i < vps->vps_max_sub_layers; i++) {
513
1149
        vps->vps_max_dec_pic_buffering[i] = get_ue_golomb_long(gb) + 1;
514
1149
        vps->vps_num_reorder_pics[i]      = get_ue_golomb_long(gb);
515
1149
        vps->vps_max_latency_increase[i]  = get_ue_golomb_long(gb) - 1;
516
517

1149
        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
1149
        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
1002
    vps->vps_max_layer_id   = get_bits(gb, 6);
531
1002
    vps->vps_num_layer_sets = get_ue_golomb_long(gb) + 1;
532

1002
    if (vps->vps_num_layer_sets < 1 || vps->vps_num_layer_sets > 1024 ||
533
1002
        (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
1002
    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
1002
    vps->vps_timing_info_present_flag = get_bits1(gb);
543
1002
    if (vps->vps_timing_info_present_flag) {
544
38
        vps->vps_num_units_in_tick               = get_bits_long(gb, 32);
545
38
        vps->vps_time_scale                      = get_bits_long(gb, 32);
546
38
        vps->vps_poc_proportional_to_timing_flag = get_bits1(gb);
547
38
        if (vps->vps_poc_proportional_to_timing_flag)
548
38
            vps->vps_num_ticks_poc_diff_one = get_ue_golomb_long(gb) + 1;
549
38
        vps->vps_num_hrd_parameters = get_ue_golomb_long(gb);
550
38
        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
43
        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
1002
    get_bits1(gb); /* vps_extension_flag */
565
566
1002
    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
1002
    if (ps->vps_list[vps_id] &&
574
435
        !memcmp(ps->vps_list[vps_id]->data, vps_buf->data, vps_buf->size)) {
575
432
        av_buffer_unref(&vps_buf);
576
    } else {
577
570
        remove_vps(ps, vps_id);
578
570
        ps->vps_list[vps_id] = vps_buf;
579
    }
580
581
1002
    return 0;
582
583
err:
584
    av_buffer_unref(&vps_buf);
585
    return AVERROR_INVALIDDATA;
586
}
587
588
224
static void decode_vui(GetBitContext *gb, AVCodecContext *avctx,
589
                       int apply_defdispwin, HEVCSPS *sps)
590
{
591
224
    VUI backup_vui, *vui = &sps->vui;
592
    GetBitContext backup;
593
224
    int sar_present, alt = 0;
594
595
224
    av_log(avctx, AV_LOG_DEBUG, "Decoding VUI\n");
596
597
224
    sar_present = get_bits1(gb);
598
224
    if (sar_present) {
599
108
        uint8_t sar_idx = get_bits(gb, 8);
600
108
        if (sar_idx < FF_ARRAY_ELEMS(vui_sar))
601
108
            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
224
    vui->overscan_info_present_flag = get_bits1(gb);
611
224
    if (vui->overscan_info_present_flag)
612
        vui->overscan_appropriate_flag = get_bits1(gb);
613
614
224
    vui->video_signal_type_present_flag = get_bits1(gb);
615
224
    if (vui->video_signal_type_present_flag) {
616
22
        vui->video_format                    = get_bits(gb, 3);
617
22
        vui->video_full_range_flag           = get_bits1(gb);
618
22
        vui->colour_description_present_flag = get_bits1(gb);
619

22
        if (vui->video_full_range_flag && sps->pix_fmt == AV_PIX_FMT_YUV420P)
620
5
            sps->pix_fmt = AV_PIX_FMT_YUVJ420P;
621
22
        if (vui->colour_description_present_flag) {
622
17
            vui->colour_primaries        = get_bits(gb, 8);
623
17
            vui->transfer_characteristic = get_bits(gb, 8);
624
17
            vui->matrix_coeffs           = get_bits(gb, 8);
625
626
            // Set invalid values to "unspecified"
627
17
            if (!av_color_primaries_name(vui->colour_primaries))
628
                vui->colour_primaries = AVCOL_PRI_UNSPECIFIED;
629
17
            if (!av_color_transfer_name(vui->transfer_characteristic))
630
                vui->transfer_characteristic = AVCOL_TRC_UNSPECIFIED;
631
17
            if (!av_color_space_name(vui->matrix_coeffs))
632
                vui->matrix_coeffs = AVCOL_SPC_UNSPECIFIED;
633
17
            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
224
            }
646
        }
647
    }
648
649
224
    vui->chroma_loc_info_present_flag = get_bits1(gb);
650
224
    if (vui->chroma_loc_info_present_flag) {
651
13
        vui->chroma_sample_loc_type_top_field    = get_ue_golomb_long(gb);
652
13
        vui->chroma_sample_loc_type_bottom_field = get_ue_golomb_long(gb);
653
    }
654
655
224
    vui->neutra_chroma_indication_flag = get_bits1(gb);
656
224
    vui->field_seq_flag                = get_bits1(gb);
657
224
    vui->frame_field_info_present_flag = get_bits1(gb);
658
659
    // Backup context in case an alternate header is detected
660
224
    memcpy(&backup, gb, sizeof(backup));
661
224
    memcpy(&backup_vui, vui, sizeof(backup_vui));
662

224
    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
224
        vui->default_display_window_flag = get_bits1(gb);
667
668
224
    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
224
timing_info:
694
224
    vui->vui_timing_info_present_flag = get_bits1(gb);
695
696
224
    if (vui->vui_timing_info_present_flag) {
697

70
        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
70
        vui->vui_num_units_in_tick               = get_bits_long(gb, 32);
708
70
        vui->vui_time_scale                      = get_bits_long(gb, 32);
709
70
        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
70
        vui->vui_poc_proportional_to_timing_flag = get_bits1(gb);
714
70
        if (vui->vui_poc_proportional_to_timing_flag)
715
38
            vui->vui_num_ticks_poc_diff_one_minus1 = get_ue_golomb_long(gb);
716
70
        vui->vui_hrd_parameters_present_flag = get_bits1(gb);
717
70
        if (vui->vui_hrd_parameters_present_flag)
718
46
            decode_hrd(gb, 1, sps->max_sub_layers);
719
    }
720
721
224
    vui->bitstream_restriction_flag = get_bits1(gb);
722
224
    if (vui->bitstream_restriction_flag) {
723

112
        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
112
        vui->tiles_fixed_structure_flag              = get_bits1(gb);
733
112
        vui->motion_vectors_over_pic_boundaries_flag = get_bits1(gb);
734
112
        vui->restricted_ref_pic_lists_flag           = get_bits1(gb);
735
112
        vui->min_spatial_segmentation_idc            = get_ue_golomb_long(gb);
736
112
        vui->max_bytes_per_pic_denom                 = get_ue_golomb_long(gb);
737
112
        vui->max_bits_per_min_cu_denom               = get_ue_golomb_long(gb);
738
112
        vui->log2_max_mv_length_horizontal           = get_ue_golomb_long(gb);
739
112
        vui->log2_max_mv_length_vertical             = get_ue_golomb_long(gb);
740
    }
741
742

224
    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
224
}
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
    uint8_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
                    int scaling_list_coeff_minus8 = get_se_golomb(gb);
820

3340
                    if (scaling_list_coeff_minus8 < -7 ||
821
                        scaling_list_coeff_minus8 > 247)
822
                        return AVERROR_INVALIDDATA;
823
3340
                    scaling_list_dc_coef[size_id - 2][matrix_id] = scaling_list_coeff_minus8 + 8;
824
3340
                    next_coef = scaling_list_dc_coef[size_id - 2][matrix_id];
825
3340
                    sl->sl_dc[size_id - 2][matrix_id] = next_coef;
826
                }
827
315114
                for (i = 0; i < coef_num; i++) {
828
309312
                    if (size_id == 0)
829
20672
                        pos = 4 * ff_hevc_diag_scan4x4_y[i] +
830
20672
                                  ff_hevc_diag_scan4x4_x[i];
831
                    else
832
288640
                        pos = 8 * ff_hevc_diag_scan8x8_y[i] +
833
288640
                                  ff_hevc_diag_scan8x8_x[i];
834
835
309312
                    scaling_list_delta_coef = get_se_golomb(gb);
836
309312
                    next_coef = (next_coef + 256U + scaling_list_delta_coef) % 256;
837
309312
                    sl->sl[size_id][matrix_id][pos] = next_coef;
838
                }
839
            }
840
        }
841
842
489
    if (sps->chroma_format_idc == 3) {
843
2795
        for (i = 0; i < 64; i++) {
844
2752
            sl->sl[3][1][i] = sl->sl[2][1][i];
845
2752
            sl->sl[3][2][i] = sl->sl[2][2][i];
846
2752
            sl->sl[3][4][i] = sl->sl[2][4][i];
847
2752
            sl->sl[3][5][i] = sl->sl[2][5][i];
848
        }
849
43
        sl->sl_dc[1][1] = sl->sl_dc[0][1];
850
43
        sl->sl_dc[1][2] = sl->sl_dc[0][2];
851
43
        sl->sl_dc[1][4] = sl->sl_dc[0][4];
852
43
        sl->sl_dc[1][5] = sl->sl_dc[0][5];
853
    }
854
855
856
489
    return 0;
857
}
858
859
995
static int map_pixel_format(AVCodecContext *avctx, HEVCSPS *sps)
860
{
861
    const AVPixFmtDescriptor *desc;
862

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

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

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

995
    if (sps->log2_min_cb_size < 3 || sps->log2_min_cb_size > 30) {
1048
        av_log(avctx, AV_LOG_ERROR, "Invalid value %d for log2_min_cb_size", sps->log2_min_cb_size);
1049
        return AVERROR_INVALIDDATA;
1050
    }
1051
1052
995
    if (sps->log2_diff_max_min_coding_block_size > 30) {
1053
        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);
1054
        return AVERROR_INVALIDDATA;
1055
    }
1056
1057

995
    if (sps->log2_min_tb_size >= sps->log2_min_cb_size || sps->log2_min_tb_size < 2) {
1058
        av_log(avctx, AV_LOG_ERROR, "Invalid value for log2_min_tb_size");
1059
        return AVERROR_INVALIDDATA;
1060
    }
1061
1062

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

3199
    if (!pps->col_bd || !pps->row_bd || !pps->col_idxX)
1379
        return AVERROR(ENOMEM);
1380
1381
3199
    if (pps->uniform_spacing_flag) {
1382
2667
        if (!pps->column_width) {
1383
2291
            pps->column_width = av_malloc_array(pps->num_tile_columns, sizeof(*pps->column_width));
1384
2291
            pps->row_height   = av_malloc_array(pps->num_tile_rows,    sizeof(*pps->row_height));
1385
        }
1386

2667
        if (!pps->column_width || !pps->row_height)
1387
            return AVERROR(ENOMEM);
1388
1389
5601
        for (i = 0; i < pps->num_tile_columns; i++) {
1390
2934
            pps->column_width[i] = ((i + 1) * sps->ctb_width) / pps->num_tile_columns -
1391
2934
                                   (i * sps->ctb_width) / pps->num_tile_columns;
1392
        }
1393
1394
5632
        for (i = 0; i < pps->num_tile_rows; i++) {
1395
2965
            pps->row_height[i] = ((i + 1) * sps->ctb_height) / pps->num_tile_rows -
1396
2965
                                 (i * sps->ctb_height) / pps->num_tile_rows;
1397
        }
1398
    }
1399
1400
3199
    pps->col_bd[0] = 0;
1401
8741
    for (i = 0; i < pps->num_tile_columns; i++)
1402
5542
        pps->col_bd[i + 1] = pps->col_bd[i] + pps->column_width[i];
1403
1404
3199
    pps->row_bd[0] = 0;
1405
8758
    for (i = 0; i < pps->num_tile_rows; i++)
1406
5559
        pps->row_bd[i + 1] = pps->row_bd[i] + pps->row_height[i];
1407
1408
57962
    for (i = 0, j = 0; i < sps->ctb_width; i++) {
1409
54763
        if (i > pps->col_bd[j])
1410
5528
            j++;
1411
54763
        pps->col_idxX[i] = j;
1412
    }
1413
1414
    /**
1415
     * 6.5
1416
     */
1417
3199
    pic_area_in_ctbs     = sps->ctb_width    * sps->ctb_height;
1418
1419
3199
    pps->ctb_addr_rs_to_ts = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->ctb_addr_rs_to_ts));
1420
3199
    pps->ctb_addr_ts_to_rs = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->ctb_addr_ts_to_rs));
1421
3199
    pps->tile_id           = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->tile_id));
1422
3199
    pps->min_tb_addr_zs_tab = av_malloc_array((sps->tb_mask+2) * (sps->tb_mask+2), sizeof(*pps->min_tb_addr_zs_tab));
1423

3199
    if (!pps->ctb_addr_rs_to_ts || !pps->ctb_addr_ts_to_rs ||
1424

3199
        !pps->tile_id || !pps->min_tb_addr_zs_tab) {
1425
        return AVERROR(ENOMEM);
1426
    }
1427
1428
764986
    for (ctb_addr_rs = 0; ctb_addr_rs < pic_area_in_ctbs; ctb_addr_rs++) {
1429
761787
        int tb_x   = ctb_addr_rs % sps->ctb_width;
1430
761787
        int tb_y   = ctb_addr_rs / sps->ctb_width;
1431
761787
        int tile_x = 0;
1432
761787
        int tile_y = 0;
1433
761787
        int val    = 0;
1434
1435
1332521
        for (i = 0; i < pps->num_tile_columns; i++) {
1436
1332521
            if (tb_x < pps->col_bd[i + 1]) {
1437
761787
                tile_x = i;
1438
761787
                break;
1439
            }
1440
        }
1441
1442
1181253
        for (i = 0; i < pps->num_tile_rows; i++) {
1443
1181253
            if (tb_y < pps->row_bd[i + 1]) {
1444
761787
                tile_y = i;
1445
761787
                break;
1446
            }
1447
        }
1448
1449
1332521
        for (i = 0; i < tile_x; i++)
1450
570734
            val += pps->row_height[tile_y] * pps->column_width[i];
1451
1181253
        for (i = 0; i < tile_y; i++)
1452
419466
            val += sps->ctb_width * pps->row_height[i];
1453
1454
761787
        val += (tb_y - pps->row_bd[tile_y]) * pps->column_width[tile_x] +
1455
761787
               tb_x - pps->col_bd[tile_x];
1456
1457
761787
        pps->ctb_addr_rs_to_ts[ctb_addr_rs] = val;
1458
761787
        pps->ctb_addr_ts_to_rs[val]         = ctb_addr_rs;
1459
    }
1460
1461
8758
    for (j = 0, tile_id = 0; j < pps->num_tile_rows; j++)
1462
21762
        for (i = 0; i < pps->num_tile_columns; i++, tile_id++)
1463
93660
            for (y = pps->row_bd[j]; y < pps->row_bd[j + 1]; y++)
1464
839244
                for (x = pps->col_bd[i]; x < pps->col_bd[i + 1]; x++)
1465
761787
                    pps->tile_id[pps->ctb_addr_rs_to_ts[y * sps->ctb_width + x]] = tile_id;
1466
1467
3199
    pps->tile_pos_rs = av_malloc_array(tile_id, sizeof(*pps->tile_pos_rs));
1468
3199
    if (!pps->tile_pos_rs)
1469
        return AVERROR(ENOMEM);
1470
1471
8758
    for (j = 0; j < pps->num_tile_rows; j++)
1472
21762
        for (i = 0; i < pps->num_tile_columns; i++)
1473
16203
            pps->tile_pos_rs[j * pps->num_tile_columns + i] =
1474
16203
                pps->row_bd[j] * sps->ctb_width + pps->col_bd[i];
1475
1476
3199
    log2_diff = sps->log2_ctb_size - sps->log2_min_tb_size;
1477
3199
    pps->min_tb_addr_zs = &pps->min_tb_addr_zs_tab[1*(sps->tb_mask+2)+1];
1478
56430
    for (y = 0; y < sps->tb_mask+2; y++) {
1479
53231
        pps->min_tb_addr_zs_tab[y*(sps->tb_mask+2)] = -1;
1480
53231
        pps->min_tb_addr_zs_tab[y]    = -1;
1481
    }
1482
53231
    for (y = 0; y < sps->tb_mask+1; y++) {
1483
843632
        for (x = 0; x < sps->tb_mask+1; x++) {
1484
793600
            int tb_x = x >> log2_diff;
1485
793600
            int tb_y = y >> log2_diff;
1486
793600
            int rs   = sps->ctb_width * tb_y + tb_x;
1487
793600
            int val  = pps->ctb_addr_rs_to_ts[rs] << (log2_diff * 2);
1488
3961856
            for (i = 0; i < log2_diff; i++) {
1489
3168256
                int m = 1 << i;
1490

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

3199
    if (pps->cb_qp_offset < -12 || pps->cb_qp_offset > 12) {
1595
        av_log(avctx, AV_LOG_ERROR, "pps_cb_qp_offset out of range: %d\n",
1596
               pps->cb_qp_offset);
1597
        ret = AVERROR_INVALIDDATA;
1598
        goto err;
1599
    }
1600
3199
    pps->cr_qp_offset = get_se_golomb(gb);
1601

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

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

861
            if (beta_offset_div2 < -6 || beta_offset_div2 > 6) {
1683
                av_log(avctx, AV_LOG_ERROR, "pps_beta_offset_div2 out of range: %d\n",
1684
                       beta_offset_div2);
1685
                ret = AVERROR_INVALIDDATA;
1686
                goto err;
1687
            }
1688

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

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

30271
    if (poc_lsb < prev_poc_lsb && prev_poc_lsb - poc_lsb >= max_poc_lsb / 2)
1771
40
        poc_msb = prev_poc_msb + max_poc_lsb;
1772

30231
    else if (poc_lsb > prev_poc_lsb && poc_lsb - prev_poc_lsb > max_poc_lsb / 2)
1773
252
        poc_msb = prev_poc_msb - max_poc_lsb;
1774
    else
1775
29979
        poc_msb = prev_poc_msb;
1776
1777
    // For BLA picture types, POCmsb is set to 0.
1778

30271
    if (nal_unit_type == HEVC_NAL_BLA_W_LP   ||
1779
30250
        nal_unit_type == HEVC_NAL_BLA_W_RADL ||
1780
        nal_unit_type == HEVC_NAL_BLA_N_LP)
1781
24
        poc_msb = 0;
1782
1783
30271
    return poc_msb + poc_lsb;
1784
}