GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/hevc_ps.c Lines: 829 1072 77.3 %
Date: 2019-11-22 03:34:36 Branches: 466 667 69.9 %

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

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

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

4823
        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
4823
        rps->num_delta_pocs = rps->num_negative_pics + nb_positive_pics;
232
4823
        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
12182
    return 0;
262
}
263
264
265
2023
static int decode_profile_tier_level(GetBitContext *gb, AVCodecContext *avctx,
266
                                      PTLCommon *ptl)
267
{
268
    int i;
269
270
2023
    if (get_bits_left(gb) < 2+1+5 + 32 + 4 + 16 + 16 + 12)
271
        return -1;
272
273
2023
    ptl->profile_space = get_bits(gb, 2);
274
2023
    ptl->tier_flag     = get_bits1(gb);
275
2023
    ptl->profile_idc   = get_bits(gb, 5);
276
2023
    if (ptl->profile_idc == FF_PROFILE_HEVC_MAIN)
277
1751
        av_log(avctx, AV_LOG_DEBUG, "Main profile bitstream\n");
278
272
    else if (ptl->profile_idc == FF_PROFILE_HEVC_MAIN_10)
279
112
        av_log(avctx, AV_LOG_DEBUG, "Main 10 profile bitstream\n");
280
160
    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
152
    else if (ptl->profile_idc == FF_PROFILE_HEVC_REXT)
283
112
        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
66759
    for (i = 0; i < 32; i++) {
288
64736
        ptl->profile_compatibility_flag[i] = get_bits1(gb);
289
290

64736
        if (ptl->profile_idc == 0 && i > 0 && ptl->profile_compatibility_flag[i])
291
40
            ptl->profile_idc = i;
292
    }
293
2023
    ptl->progressive_source_flag    = get_bits1(gb);
294
2023
    ptl->interlaced_source_flag     = get_bits1(gb);
295
2023
    ptl->non_packed_constraint_flag = get_bits1(gb);
296
2023
    ptl->frame_only_constraint_flag = get_bits1(gb);
297
298
2023
    skip_bits(gb, 16); // XXX_reserved_zero_44bits[0..15]
299
2023
    skip_bits(gb, 16); // XXX_reserved_zero_44bits[16..31]
300
2023
    skip_bits(gb, 12); // XXX_reserved_zero_44bits[32..43]
301
302
2023
    return 0;
303
}
304
305
1971
static int parse_ptl(GetBitContext *gb, AVCodecContext *avctx,
306
                      PTL *ptl, int max_num_sub_layers)
307
{
308
    int i;
309

3942
    if (decode_profile_tier_level(gb, avctx, &ptl->general_ptl) < 0 ||
310
1971
        get_bits_left(gb) < 8 + (8*2 * (max_num_sub_layers - 1 > 0))) {
311
        av_log(avctx, AV_LOG_ERROR, "PTL information too short\n");
312
        return -1;
313
    }
314
315
1971
    ptl->general_ptl.level_idc = get_bits(gb, 8);
316
317
2439
    for (i = 0; i < max_num_sub_layers - 1; i++) {
318
468
        ptl->sub_layer_profile_present_flag[i] = get_bits1(gb);
319
468
        ptl->sub_layer_level_present_flag[i]   = get_bits1(gb);
320
    }
321
322
1971
    if (max_num_sub_layers - 1> 0)
323
1656
        for (i = max_num_sub_layers - 1; i < 8; i++)
324
1420
            skip_bits(gb, 2); // reserved_zero_2bits[i]
325
2439
    for (i = 0; i < max_num_sub_layers - 1; i++) {
326

520
        if (ptl->sub_layer_profile_present_flag[i] &&
327
52
            decode_profile_tier_level(gb, avctx, &ptl->sub_layer_ptl[i]) < 0) {
328
            av_log(avctx, AV_LOG_ERROR,
329
                   "PTL information for sublayer %i too short\n", i);
330
            return -1;
331
        }
332
468
        if (ptl->sub_layer_level_present_flag[i]) {
333
52
            if (get_bits_left(gb) < 8) {
334
                av_log(avctx, AV_LOG_ERROR,
335
                       "Not enough data for sublayer %i level_idc\n", i);
336
                return -1;
337
            } else
338
52
                ptl->sub_layer_ptl[i].level_idc = get_bits(gb, 8);
339
        }
340
    }
341
342
1971
    return 0;
343
}
344
345
92
static void decode_sublayer_hrd(GetBitContext *gb, unsigned int nb_cpb,
346
                                int subpic_params_present)
347
{
348
    int i;
349
350
184
    for (i = 0; i < nb_cpb; i++) {
351
92
        get_ue_golomb_long(gb); // bit_rate_value_minus1
352
92
        get_ue_golomb_long(gb); // cpb_size_value_minus1
353
354
92
        if (subpic_params_present) {
355
26
            get_ue_golomb_long(gb); // cpb_size_du_value_minus1
356
26
            get_ue_golomb_long(gb); // bit_rate_du_value_minus1
357
        }
358
92
        skip_bits1(gb); // cbr_flag
359
    }
360
92
}
361
362
46
static int decode_hrd(GetBitContext *gb, int common_inf_present,
363
                       int max_sublayers)
364
{
365
46
    int nal_params_present = 0, vcl_params_present = 0;
366
46
    int subpic_params_present = 0;
367
    int i;
368
369
46
    if (common_inf_present) {
370
46
        nal_params_present = get_bits1(gb);
371
46
        vcl_params_present = get_bits1(gb);
372
373

46
        if (nal_params_present || vcl_params_present) {
374
46
            subpic_params_present = get_bits1(gb);
375
376
46
            if (subpic_params_present) {
377
13
                skip_bits(gb, 8); // tick_divisor_minus2
378
13
                skip_bits(gb, 5); // du_cpb_removal_delay_increment_length_minus1
379
13
                skip_bits(gb, 1); // sub_pic_cpb_params_in_pic_timing_sei_flag
380
13
                skip_bits(gb, 5); // dpb_output_delay_du_length_minus1
381
            }
382
383
46
            skip_bits(gb, 4); // bit_rate_scale
384
46
            skip_bits(gb, 4); // cpb_size_scale
385
386
46
            if (subpic_params_present)
387
13
                skip_bits(gb, 4);  // cpb_size_du_scale
388
389
46
            skip_bits(gb, 5); // initial_cpb_removal_delay_length_minus1
390
46
            skip_bits(gb, 5); // au_cpb_removal_delay_length_minus1
391
46
            skip_bits(gb, 5); // dpb_output_delay_length_minus1
392
        }
393
    }
394
395
92
    for (i = 0; i < max_sublayers; i++) {
396
46
        int low_delay = 0;
397
46
        unsigned int nb_cpb = 1;
398
46
        int fixed_rate = get_bits1(gb);
399
400
46
        if (!fixed_rate)
401
23
            fixed_rate = get_bits1(gb);
402
403
46
        if (fixed_rate)
404
23
            get_ue_golomb_long(gb);  // elemental_duration_in_tc_minus1
405
        else
406
23
            low_delay = get_bits1(gb);
407
408
46
        if (!low_delay) {
409
46
            nb_cpb = get_ue_golomb_long(gb) + 1;
410

46
            if (nb_cpb < 1 || nb_cpb > 32) {
411
                av_log(NULL, AV_LOG_ERROR, "nb_cpb %d invalid\n", nb_cpb);
412
                return AVERROR_INVALIDDATA;
413
            }
414
        }
415
416
46
        if (nal_params_present)
417
46
            decode_sublayer_hrd(gb, nb_cpb, subpic_params_present);
418
46
        if (vcl_params_present)
419
46
            decode_sublayer_hrd(gb, nb_cpb, subpic_params_present);
420
    }
421
46
    return 0;
422
}
423
424
989
int ff_hevc_decode_nal_vps(GetBitContext *gb, AVCodecContext *avctx,
425
                           HEVCParamSets *ps)
426
{
427
    int i,j;
428
989
    int vps_id = 0;
429
    ptrdiff_t nal_size;
430
    HEVCVPS *vps;
431
989
    AVBufferRef *vps_buf = av_buffer_allocz(sizeof(*vps));
432
433
989
    if (!vps_buf)
434
        return AVERROR(ENOMEM);
435
989
    vps = (HEVCVPS*)vps_buf->data;
436
437
989
    av_log(avctx, AV_LOG_DEBUG, "Decoding VPS\n");
438
439
989
    nal_size = gb->buffer_end - gb->buffer;
440
989
    if (nal_size > sizeof(vps->data)) {
441
        av_log(avctx, AV_LOG_WARNING, "Truncating likely oversized VPS "
442
               "(%"PTRDIFF_SPECIFIER" > %"SIZE_SPECIFIER")\n",
443
               nal_size, sizeof(vps->data));
444
        vps->data_size = sizeof(vps->data);
445
    } else {
446
989
        vps->data_size = nal_size;
447
    }
448
989
    memcpy(vps->data, gb->buffer, vps->data_size);
449
450
989
    vps_id = get_bits(gb, 4);
451
452
989
    if (get_bits(gb, 2) != 3) { // vps_reserved_three_2bits
453
        av_log(avctx, AV_LOG_ERROR, "vps_reserved_three_2bits is not three\n");
454
        goto err;
455
    }
456
457
989
    vps->vps_max_layers               = get_bits(gb, 6) + 1;
458
989
    vps->vps_max_sub_layers           = get_bits(gb, 3) + 1;
459
989
    vps->vps_temporal_id_nesting_flag = get_bits1(gb);
460
461
989
    if (get_bits(gb, 16) != 0xffff) { // vps_reserved_ffff_16bits
462
        av_log(avctx, AV_LOG_ERROR, "vps_reserved_ffff_16bits is not 0xffff\n");
463
        goto err;
464
    }
465
466
989
    if (vps->vps_max_sub_layers > HEVC_MAX_SUB_LAYERS) {
467
        av_log(avctx, AV_LOG_ERROR, "vps_max_sub_layers out of range: %d\n",
468
               vps->vps_max_sub_layers);
469
        goto err;
470
    }
471
472
989
    if (parse_ptl(gb, avctx, &vps->ptl, vps->vps_max_sub_layers) < 0)
473
        goto err;
474
475
989
    vps->vps_sub_layer_ordering_info_present_flag = get_bits1(gb);
476
477
989
    i = vps->vps_sub_layer_ordering_info_present_flag ? 0 : vps->vps_max_sub_layers - 1;
478
2125
    for (; i < vps->vps_max_sub_layers; i++) {
479
1136
        vps->vps_max_dec_pic_buffering[i] = get_ue_golomb_long(gb) + 1;
480
1136
        vps->vps_num_reorder_pics[i]      = get_ue_golomb_long(gb);
481
1136
        vps->vps_max_latency_increase[i]  = get_ue_golomb_long(gb) - 1;
482
483

1136
        if (vps->vps_max_dec_pic_buffering[i] > HEVC_MAX_DPB_SIZE || !vps->vps_max_dec_pic_buffering[i]) {
484
            av_log(avctx, AV_LOG_ERROR, "vps_max_dec_pic_buffering_minus1 out of range: %d\n",
485
                   vps->vps_max_dec_pic_buffering[i] - 1);
486
            goto err;
487
        }
488
1136
        if (vps->vps_num_reorder_pics[i] > vps->vps_max_dec_pic_buffering[i] - 1) {
489
            av_log(avctx, AV_LOG_WARNING, "vps_max_num_reorder_pics out of range: %d\n",
490
                   vps->vps_num_reorder_pics[i]);
491
            if (avctx->err_recognition & AV_EF_EXPLODE)
492
                goto err;
493
        }
494
    }
495
496
989
    vps->vps_max_layer_id   = get_bits(gb, 6);
497
989
    vps->vps_num_layer_sets = get_ue_golomb_long(gb) + 1;
498

989
    if (vps->vps_num_layer_sets < 1 || vps->vps_num_layer_sets > 1024 ||
499
989
        (vps->vps_num_layer_sets - 1LL) * (vps->vps_max_layer_id + 1LL) > get_bits_left(gb)) {
500
        av_log(avctx, AV_LOG_ERROR, "too many layer_id_included_flags\n");
501
        goto err;
502
    }
503
504
989
    for (i = 1; i < vps->vps_num_layer_sets; i++)
505
        for (j = 0; j <= vps->vps_max_layer_id; j++)
506
            skip_bits(gb, 1);  // layer_id_included_flag[i][j]
507
508
989
    vps->vps_timing_info_present_flag = get_bits1(gb);
509
989
    if (vps->vps_timing_info_present_flag) {
510
33
        vps->vps_num_units_in_tick               = get_bits_long(gb, 32);
511
33
        vps->vps_time_scale                      = get_bits_long(gb, 32);
512
33
        vps->vps_poc_proportional_to_timing_flag = get_bits1(gb);
513
33
        if (vps->vps_poc_proportional_to_timing_flag)
514
33
            vps->vps_num_ticks_poc_diff_one = get_ue_golomb_long(gb) + 1;
515
33
        vps->vps_num_hrd_parameters = get_ue_golomb_long(gb);
516
33
        if (vps->vps_num_hrd_parameters > (unsigned)vps->vps_num_layer_sets) {
517
            av_log(avctx, AV_LOG_ERROR,
518
                   "vps_num_hrd_parameters %d is invalid\n", vps->vps_num_hrd_parameters);
519
            goto err;
520
        }
521
38
        for (i = 0; i < vps->vps_num_hrd_parameters; i++) {
522
5
            int common_inf_present = 1;
523
524
5
            get_ue_golomb_long(gb); // hrd_layer_set_idx
525
5
            if (i)
526
                common_inf_present = get_bits1(gb);
527
5
            decode_hrd(gb, common_inf_present, vps->vps_max_sub_layers);
528
        }
529
    }
530
989
    get_bits1(gb); /* vps_extension_flag */
531
532
989
    if (get_bits_left(gb) < 0) {
533
        av_log(avctx, AV_LOG_ERROR,
534
               "Overread VPS by %d bits\n", -get_bits_left(gb));
535
        if (ps->vps_list[vps_id])
536
            goto err;
537
    }
538
539
989
    if (ps->vps_list[vps_id] &&
540
431
        !memcmp(ps->vps_list[vps_id]->data, vps_buf->data, vps_buf->size)) {
541
428
        av_buffer_unref(&vps_buf);
542
    } else {
543
561
        remove_vps(ps, vps_id);
544
561
        ps->vps_list[vps_id] = vps_buf;
545
    }
546
547
989
    return 0;
548
549
err:
550
    av_buffer_unref(&vps_buf);
551
    return AVERROR_INVALIDDATA;
552
}
553
554
215
static void decode_vui(GetBitContext *gb, AVCodecContext *avctx,
555
                       int apply_defdispwin, HEVCSPS *sps)
556
{
557
215
    VUI backup_vui, *vui = &sps->vui;
558
    GetBitContext backup;
559
215
    int sar_present, alt = 0;
560
561
215
    av_log(avctx, AV_LOG_DEBUG, "Decoding VUI\n");
562
563
215
    sar_present = get_bits1(gb);
564
215
    if (sar_present) {
565
103
        uint8_t sar_idx = get_bits(gb, 8);
566
103
        if (sar_idx < FF_ARRAY_ELEMS(vui_sar))
567
103
            vui->sar = vui_sar[sar_idx];
568
        else if (sar_idx == 255) {
569
            vui->sar.num = get_bits(gb, 16);
570
            vui->sar.den = get_bits(gb, 16);
571
        } else
572
            av_log(avctx, AV_LOG_WARNING,
573
                   "Unknown SAR index: %u.\n", sar_idx);
574
    }
575
576
215
    vui->overscan_info_present_flag = get_bits1(gb);
577
215
    if (vui->overscan_info_present_flag)
578
        vui->overscan_appropriate_flag = get_bits1(gb);
579
580
215
    vui->video_signal_type_present_flag = get_bits1(gb);
581
215
    if (vui->video_signal_type_present_flag) {
582
13
        vui->video_format                    = get_bits(gb, 3);
583
13
        vui->video_full_range_flag           = get_bits1(gb);
584
13
        vui->colour_description_present_flag = get_bits1(gb);
585

13
        if (vui->video_full_range_flag && sps->pix_fmt == AV_PIX_FMT_YUV420P)
586
5
            sps->pix_fmt = AV_PIX_FMT_YUVJ420P;
587
13
        if (vui->colour_description_present_flag) {
588
13
            vui->colour_primaries        = get_bits(gb, 8);
589
13
            vui->transfer_characteristic = get_bits(gb, 8);
590
13
            vui->matrix_coeffs           = get_bits(gb, 8);
591
592
            // Set invalid values to "unspecified"
593
13
            if (!av_color_primaries_name(vui->colour_primaries))
594
                vui->colour_primaries = AVCOL_PRI_UNSPECIFIED;
595
13
            if (!av_color_transfer_name(vui->transfer_characteristic))
596
                vui->transfer_characteristic = AVCOL_TRC_UNSPECIFIED;
597
13
            if (!av_color_space_name(vui->matrix_coeffs))
598
                vui->matrix_coeffs = AVCOL_SPC_UNSPECIFIED;
599
13
            if (vui->matrix_coeffs == AVCOL_SPC_RGB) {
600
                switch (sps->pix_fmt) {
601
                case AV_PIX_FMT_YUV444P:
602
                    sps->pix_fmt = AV_PIX_FMT_GBRP;
603
                    break;
604
                case AV_PIX_FMT_YUV444P10:
605
                    sps->pix_fmt = AV_PIX_FMT_GBRP10;
606
                    break;
607
                case AV_PIX_FMT_YUV444P12:
608
                    sps->pix_fmt = AV_PIX_FMT_GBRP12;
609
                    break;
610
                }
611
215
            }
612
        }
613
    }
614
615
215
    vui->chroma_loc_info_present_flag = get_bits1(gb);
616
215
    if (vui->chroma_loc_info_present_flag) {
617
8
        vui->chroma_sample_loc_type_top_field    = get_ue_golomb_long(gb);
618
8
        vui->chroma_sample_loc_type_bottom_field = get_ue_golomb_long(gb);
619
    }
620
621
215
    vui->neutra_chroma_indication_flag = get_bits1(gb);
622
215
    vui->field_seq_flag                = get_bits1(gb);
623
215
    vui->frame_field_info_present_flag = get_bits1(gb);
624
625
    // Backup context in case an alternate header is detected
626
215
    memcpy(&backup, gb, sizeof(backup));
627
215
    memcpy(&backup_vui, vui, sizeof(backup_vui));
628

215
    if (get_bits_left(gb) >= 68 && show_bits_long(gb, 21) == 0x100000) {
629
        vui->default_display_window_flag = 0;
630
        av_log(avctx, AV_LOG_WARNING, "Invalid default display window\n");
631
    } else
632
215
        vui->default_display_window_flag = get_bits1(gb);
633
634
215
    if (vui->default_display_window_flag) {
635
91
        int vert_mult  = hevc_sub_height_c[sps->chroma_format_idc];
636
91
        int horiz_mult = hevc_sub_width_c[sps->chroma_format_idc];
637
91
        vui->def_disp_win.left_offset   = get_ue_golomb_long(gb) * horiz_mult;
638
91
        vui->def_disp_win.right_offset  = get_ue_golomb_long(gb) * horiz_mult;
639
91
        vui->def_disp_win.top_offset    = get_ue_golomb_long(gb) *  vert_mult;
640
91
        vui->def_disp_win.bottom_offset = get_ue_golomb_long(gb) *  vert_mult;
641
642
91
        if (apply_defdispwin &&
643
40
            avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {
644
            av_log(avctx, AV_LOG_DEBUG,
645
                   "discarding vui default display window, "
646
                   "original values are l:%u r:%u t:%u b:%u\n",
647
                   vui->def_disp_win.left_offset,
648
                   vui->def_disp_win.right_offset,
649
                   vui->def_disp_win.top_offset,
650
                   vui->def_disp_win.bottom_offset);
651
652
            vui->def_disp_win.left_offset   =
653
            vui->def_disp_win.right_offset  =
654
            vui->def_disp_win.top_offset    =
655
            vui->def_disp_win.bottom_offset = 0;
656
        }
657
    }
658
659
215
timing_info:
660
215
    vui->vui_timing_info_present_flag = get_bits1(gb);
661
662
215
    if (vui->vui_timing_info_present_flag) {
663

65
        if( get_bits_left(gb) < 66 && !alt) {
664
            // The alternate syntax seem to have timing info located
665
            // at where def_disp_win is normally located
666
            av_log(avctx, AV_LOG_WARNING,
667
                   "Strange VUI timing information, retrying...\n");
668
            memcpy(vui, &backup_vui, sizeof(backup_vui));
669
            memcpy(gb, &backup, sizeof(backup));
670
            alt = 1;
671
            goto timing_info;
672
        }
673
65
        vui->vui_num_units_in_tick               = get_bits_long(gb, 32);
674
65
        vui->vui_time_scale                      = get_bits_long(gb, 32);
675
65
        if (alt) {
676
            av_log(avctx, AV_LOG_INFO, "Retry got %"PRIu32"/%"PRIu32" fps\n",
677
                   vui->vui_time_scale, vui->vui_num_units_in_tick);
678
        }
679
65
        vui->vui_poc_proportional_to_timing_flag = get_bits1(gb);
680
65
        if (vui->vui_poc_proportional_to_timing_flag)
681
33
            vui->vui_num_ticks_poc_diff_one_minus1 = get_ue_golomb_long(gb);
682
65
        vui->vui_hrd_parameters_present_flag = get_bits1(gb);
683
65
        if (vui->vui_hrd_parameters_present_flag)
684
41
            decode_hrd(gb, 1, sps->max_sub_layers);
685
    }
686
687
215
    vui->bitstream_restriction_flag = get_bits1(gb);
688
215
    if (vui->bitstream_restriction_flag) {
689

103
        if (get_bits_left(gb) < 8 && !alt) {
690
            av_log(avctx, AV_LOG_WARNING,
691
                   "Strange VUI bitstream restriction information, retrying"
692
                   " from timing information...\n");
693
            memcpy(vui, &backup_vui, sizeof(backup_vui));
694
            memcpy(gb, &backup, sizeof(backup));
695
            alt = 1;
696
            goto timing_info;
697
        }
698
103
        vui->tiles_fixed_structure_flag              = get_bits1(gb);
699
103
        vui->motion_vectors_over_pic_boundaries_flag = get_bits1(gb);
700
103
        vui->restricted_ref_pic_lists_flag           = get_bits1(gb);
701
103
        vui->min_spatial_segmentation_idc            = get_ue_golomb_long(gb);
702
103
        vui->max_bytes_per_pic_denom                 = get_ue_golomb_long(gb);
703
103
        vui->max_bits_per_min_cu_denom               = get_ue_golomb_long(gb);
704
103
        vui->log2_max_mv_length_horizontal           = get_ue_golomb_long(gb);
705
103
        vui->log2_max_mv_length_vertical             = get_ue_golomb_long(gb);
706
    }
707
708

215
    if (get_bits_left(gb) < 1 && !alt) {
709
        // XXX: Alternate syntax when sps_range_extension_flag != 0?
710
        av_log(avctx, AV_LOG_WARNING,
711
               "Overread in VUI, retrying from timing information...\n");
712
        memcpy(vui, &backup_vui, sizeof(backup_vui));
713
        memcpy(gb, &backup, sizeof(backup));
714
        alt = 1;
715
        goto timing_info;
716
    }
717
215
}
718
719
499
static void set_default_scaling_list_data(ScalingList *sl)
720
{
721
    int matrixId;
722
723
3493
    for (matrixId = 0; matrixId < 6; matrixId++) {
724
        // 4x4 default is 16
725
2994
        memset(sl->sl[0][matrixId], 16, 16);
726
2994
        sl->sl_dc[0][matrixId] = 16; // default for 16x16
727
2994
        sl->sl_dc[1][matrixId] = 16; // default for 32x32
728
    }
729
499
    memcpy(sl->sl[1][0], default_scaling_list_intra, 64);
730
499
    memcpy(sl->sl[1][1], default_scaling_list_intra, 64);
731
499
    memcpy(sl->sl[1][2], default_scaling_list_intra, 64);
732
499
    memcpy(sl->sl[1][3], default_scaling_list_inter, 64);
733
499
    memcpy(sl->sl[1][4], default_scaling_list_inter, 64);
734
499
    memcpy(sl->sl[1][5], default_scaling_list_inter, 64);
735
499
    memcpy(sl->sl[2][0], default_scaling_list_intra, 64);
736
499
    memcpy(sl->sl[2][1], default_scaling_list_intra, 64);
737
499
    memcpy(sl->sl[2][2], default_scaling_list_intra, 64);
738
499
    memcpy(sl->sl[2][3], default_scaling_list_inter, 64);
739
499
    memcpy(sl->sl[2][4], default_scaling_list_inter, 64);
740
499
    memcpy(sl->sl[2][5], default_scaling_list_inter, 64);
741
499
    memcpy(sl->sl[3][0], default_scaling_list_intra, 64);
742
499
    memcpy(sl->sl[3][1], default_scaling_list_intra, 64);
743
499
    memcpy(sl->sl[3][2], default_scaling_list_intra, 64);
744
499
    memcpy(sl->sl[3][3], default_scaling_list_inter, 64);
745
499
    memcpy(sl->sl[3][4], default_scaling_list_inter, 64);
746
499
    memcpy(sl->sl[3][5], default_scaling_list_inter, 64);
747
499
}
748
749
489
static int scaling_list_data(GetBitContext *gb, AVCodecContext *avctx, ScalingList *sl, HEVCSPS *sps)
750
{
751
    uint8_t scaling_list_pred_mode_flag;
752
    int32_t scaling_list_dc_coef[2][6];
753
    int size_id, matrix_id, pos;
754
    int i;
755
756
2445
    for (size_id = 0; size_id < 4; size_id++)
757

11736
        for (matrix_id = 0; matrix_id < 6; matrix_id += ((size_id == 3) ? 3 : 1)) {
758
9780
            scaling_list_pred_mode_flag = get_bits1(gb);
759
9780
            if (!scaling_list_pred_mode_flag) {
760
3978
                unsigned int delta = get_ue_golomb_long(gb);
761
                /* Only need to handle non-zero delta. Zero means default,
762
                 * which should already be in the arrays. */
763
3978
                if (delta) {
764
                    // Copy from previous array.
765
3852
                    delta *= (size_id == 3) ? 3 : 1;
766
3852
                    if (matrix_id < delta) {
767
                        av_log(avctx, AV_LOG_ERROR,
768
                               "Invalid delta in scaling list data: %d.\n", delta);
769
                        return AVERROR_INVALIDDATA;
770
                    }
771
772
3852
                    memcpy(sl->sl[size_id][matrix_id],
773
3852
                           sl->sl[size_id][matrix_id - delta],
774
                           size_id > 0 ? 64 : 16);
775
3852
                    if (size_id > 1)
776
530
                        sl->sl_dc[size_id - 2][matrix_id] = sl->sl_dc[size_id - 2][matrix_id - delta];
777
                }
778
            } else {
779
                int next_coef, coef_num;
780
                int32_t scaling_list_delta_coef;
781
782
5802
                next_coef = 8;
783
5802
                coef_num  = FFMIN(64, 1 << (4 + (size_id << 1)));
784
5802
                if (size_id > 1) {
785
3340
                    scaling_list_dc_coef[size_id - 2][matrix_id] = get_se_golomb(gb) + 8;
786
3340
                    next_coef = scaling_list_dc_coef[size_id - 2][matrix_id];
787
3340
                    sl->sl_dc[size_id - 2][matrix_id] = next_coef;
788
                }
789
315114
                for (i = 0; i < coef_num; i++) {
790
309312
                    if (size_id == 0)
791
20672
                        pos = 4 * ff_hevc_diag_scan4x4_y[i] +
792
20672
                                  ff_hevc_diag_scan4x4_x[i];
793
                    else
794
288640
                        pos = 8 * ff_hevc_diag_scan8x8_y[i] +
795
288640
                                  ff_hevc_diag_scan8x8_x[i];
796
797
309312
                    scaling_list_delta_coef = get_se_golomb(gb);
798
309312
                    next_coef = (next_coef + 256U + scaling_list_delta_coef) % 256;
799
309312
                    sl->sl[size_id][matrix_id][pos] = next_coef;
800
                }
801
            }
802
        }
803
804
489
    if (sps->chroma_format_idc == 3) {
805
2795
        for (i = 0; i < 64; i++) {
806
2752
            sl->sl[3][1][i] = sl->sl[2][1][i];
807
2752
            sl->sl[3][2][i] = sl->sl[2][2][i];
808
2752
            sl->sl[3][4][i] = sl->sl[2][4][i];
809
2752
            sl->sl[3][5][i] = sl->sl[2][5][i];
810
        }
811
43
        sl->sl_dc[1][1] = sl->sl_dc[0][1];
812
43
        sl->sl_dc[1][2] = sl->sl_dc[0][2];
813
43
        sl->sl_dc[1][4] = sl->sl_dc[0][4];
814
43
        sl->sl_dc[1][5] = sl->sl_dc[0][5];
815
    }
816
817
818
489
    return 0;
819
}
820
821
982
static int map_pixel_format(AVCodecContext *avctx, HEVCSPS *sps)
822
{
823
    const AVPixFmtDescriptor *desc;
824

982
    switch (sps->bit_depth) {
825
879
    case 8:
826
879
        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY8;
827
879
        if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P;
828
879
        if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P;
829
879
        if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P;
830
879
       break;
831
    case 9:
832
        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY9;
833
        if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P9;
834
        if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P9;
835
        if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P9;
836
        break;
837
80
    case 10:
838
80
        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY10;
839
80
        if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P10;
840
80
        if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P10;
841
80
        if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P10;
842
80
        break;
843
23
    case 12:
844
23
        if (sps->chroma_format_idc == 0) sps->pix_fmt = AV_PIX_FMT_GRAY12;
845
23
        if (sps->chroma_format_idc == 1) sps->pix_fmt = AV_PIX_FMT_YUV420P12;
846
23
        if (sps->chroma_format_idc == 2) sps->pix_fmt = AV_PIX_FMT_YUV422P12;
847
23
        if (sps->chroma_format_idc == 3) sps->pix_fmt = AV_PIX_FMT_YUV444P12;
848
23
        break;
849
    default:
850
        av_log(avctx, AV_LOG_ERROR,
851
               "The following bit-depths are currently specified: 8, 9, 10 and 12 bits, "
852
               "chroma_format_idc is %d, depth is %d\n",
853
               sps->chroma_format_idc, sps->bit_depth);
854
        return AVERROR_INVALIDDATA;
855
    }
856
857
982
    desc = av_pix_fmt_desc_get(sps->pix_fmt);
858
982
    if (!desc)
859
        return AVERROR(EINVAL);
860
861
982
    sps->hshift[0] = sps->vshift[0] = 0;
862
982
    sps->hshift[2] = sps->hshift[1] = desc->log2_chroma_w;
863
982
    sps->vshift[2] = sps->vshift[1] = desc->log2_chroma_h;
864
865
982
    sps->pixel_shift = sps->bit_depth > 8;
866
867
982
    return 0;
868
}
869
870
982
int ff_hevc_parse_sps(HEVCSPS *sps, GetBitContext *gb, unsigned int *sps_id,
871
                      int apply_defdispwin, AVBufferRef **vps_list, AVCodecContext *avctx)
872
{
873
    HEVCWindow *ow;
874
982
    int ret = 0;
875
    int log2_diff_max_min_transform_block_size;
876
    int bit_depth_chroma, start, vui_present, sublayer_ordering_info;
877
    int i;
878
879
    // Coded parameters
880
881
982
    sps->vps_id = get_bits(gb, 4);
882
883

982
    if (vps_list && !vps_list[sps->vps_id]) {
884
        av_log(avctx, AV_LOG_ERROR, "VPS %d does not exist\n",
885
               sps->vps_id);
886
        return AVERROR_INVALIDDATA;
887
    }
888
889
982
    sps->max_sub_layers = get_bits(gb, 3) + 1;
890
982
    if (sps->max_sub_layers > HEVC_MAX_SUB_LAYERS) {
891
        av_log(avctx, AV_LOG_ERROR, "sps_max_sub_layers out of range: %d\n",
892
               sps->max_sub_layers);
893
        return AVERROR_INVALIDDATA;
894
    }
895
896
982
    sps->temporal_id_nesting_flag = get_bits(gb, 1);
897
898
982
    if ((ret = parse_ptl(gb, avctx, &sps->ptl, sps->max_sub_layers)) < 0)
899
        return ret;
900
901
982
    *sps_id = get_ue_golomb_long(gb);
902
982
    if (*sps_id >= HEVC_MAX_SPS_COUNT) {
903
        av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", *sps_id);
904
        return AVERROR_INVALIDDATA;
905
    }
906
907
982
    sps->chroma_format_idc = get_ue_golomb_long(gb);
908
982
    if (sps->chroma_format_idc > 3U) {
909
        av_log(avctx, AV_LOG_ERROR, "chroma_format_idc %d is invalid\n", sps->chroma_format_idc);
910
        return AVERROR_INVALIDDATA;
911
    }
912
913
982
    if (sps->chroma_format_idc == 3)
914
28
        sps->separate_colour_plane_flag = get_bits1(gb);
915
916
982
    if (sps->separate_colour_plane_flag)
917
        sps->chroma_format_idc = 0;
918
919
982
    sps->width  = get_ue_golomb_long(gb);
920
982
    sps->height = get_ue_golomb_long(gb);
921
982
    if ((ret = av_image_check_size(sps->width,
922
982
                                   sps->height, 0, avctx)) < 0)
923
        return ret;
924
925
982
    if (get_bits1(gb)) { // pic_conformance_flag
926
819
        int vert_mult  = hevc_sub_height_c[sps->chroma_format_idc];
927
819
        int horiz_mult = hevc_sub_width_c[sps->chroma_format_idc];
928
819
        sps->pic_conf_win.left_offset   = get_ue_golomb_long(gb) * horiz_mult;
929
819
        sps->pic_conf_win.right_offset  = get_ue_golomb_long(gb) * horiz_mult;
930
819
        sps->pic_conf_win.top_offset    = get_ue_golomb_long(gb) *  vert_mult;
931
819
        sps->pic_conf_win.bottom_offset = get_ue_golomb_long(gb) *  vert_mult;
932
933
819
        if (avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {
934
            av_log(avctx, AV_LOG_DEBUG,
935
                   "discarding sps conformance window, "
936
                   "original values are l:%u r:%u t:%u b:%u\n",
937
                   sps->pic_conf_win.left_offset,
938
                   sps->pic_conf_win.right_offset,
939
                   sps->pic_conf_win.top_offset,
940
                   sps->pic_conf_win.bottom_offset);
941
942
            sps->pic_conf_win.left_offset   =
943
            sps->pic_conf_win.right_offset  =
944
            sps->pic_conf_win.top_offset    =
945
            sps->pic_conf_win.bottom_offset = 0;
946
        }
947
819
        sps->output_window = sps->pic_conf_win;
948
    }
949
950
982
    sps->bit_depth   = get_ue_golomb_long(gb) + 8;
951
982
    bit_depth_chroma = get_ue_golomb_long(gb) + 8;
952

982
    if (sps->chroma_format_idc && bit_depth_chroma != sps->bit_depth) {
953
        av_log(avctx, AV_LOG_ERROR,
954
               "Luma bit depth (%d) is different from chroma bit depth (%d), "
955
               "this is unsupported.\n",
956
               sps->bit_depth, bit_depth_chroma);
957
        return AVERROR_INVALIDDATA;
958
    }
959
982
    sps->bit_depth_chroma = bit_depth_chroma;
960
961
982
    ret = map_pixel_format(avctx, sps);
962
982
    if (ret < 0)
963
        return ret;
964
965
982
    sps->log2_max_poc_lsb = get_ue_golomb_long(gb) + 4;
966
982
    if (sps->log2_max_poc_lsb > 16) {
967
        av_log(avctx, AV_LOG_ERROR, "log2_max_pic_order_cnt_lsb_minus4 out range: %d\n",
968
               sps->log2_max_poc_lsb - 4);
969
        return AVERROR_INVALIDDATA;
970
    }
971
972
982
    sublayer_ordering_info = get_bits1(gb);
973
982
    start = sublayer_ordering_info ? 0 : sps->max_sub_layers - 1;
974
2111
    for (i = start; i < sps->max_sub_layers; i++) {
975
1129
        sps->temporal_layer[i].max_dec_pic_buffering = get_ue_golomb_long(gb) + 1;
976
1129
        sps->temporal_layer[i].num_reorder_pics      = get_ue_golomb_long(gb);
977
1129
        sps->temporal_layer[i].max_latency_increase  = get_ue_golomb_long(gb) - 1;
978
1129
        if (sps->temporal_layer[i].max_dec_pic_buffering > (unsigned)HEVC_MAX_DPB_SIZE) {
979
            av_log(avctx, AV_LOG_ERROR, "sps_max_dec_pic_buffering_minus1 out of range: %d\n",
980
                   sps->temporal_layer[i].max_dec_pic_buffering - 1U);
981
            return AVERROR_INVALIDDATA;
982
        }
983
1129
        if (sps->temporal_layer[i].num_reorder_pics > sps->temporal_layer[i].max_dec_pic_buffering - 1) {
984
            av_log(avctx, AV_LOG_WARNING, "sps_max_num_reorder_pics out of range: %d\n",
985
                   sps->temporal_layer[i].num_reorder_pics);
986
            if (avctx->err_recognition & AV_EF_EXPLODE ||
987
                sps->temporal_layer[i].num_reorder_pics > HEVC_MAX_DPB_SIZE - 1) {
988
                return AVERROR_INVALIDDATA;
989
            }
990
            sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[i].num_reorder_pics + 1;
991
        }
992
    }
993
994
982
    if (!sublayer_ordering_info) {
995
211
        for (i = 0; i < start; i++) {
996
82
            sps->temporal_layer[i].max_dec_pic_buffering = sps->temporal_layer[start].max_dec_pic_buffering;
997
82
            sps->temporal_layer[i].num_reorder_pics      = sps->temporal_layer[start].num_reorder_pics;
998
82
            sps->temporal_layer[i].max_latency_increase  = sps->temporal_layer[start].max_latency_increase;
999
        }
1000
    }
1001
1002
982
    sps->log2_min_cb_size                    = get_ue_golomb_long(gb) + 3;
1003
982
    sps->log2_diff_max_min_coding_block_size = get_ue_golomb_long(gb);
1004
982
    sps->log2_min_tb_size                    = get_ue_golomb_long(gb) + 2;
1005
982
    log2_diff_max_min_transform_block_size   = get_ue_golomb_long(gb);
1006
982
    sps->log2_max_trafo_size                 = log2_diff_max_min_transform_block_size +
1007
982
                                               sps->log2_min_tb_size;
1008
1009

982
    if (sps->log2_min_cb_size < 3 || sps->log2_min_cb_size > 30) {
1010
        av_log(avctx, AV_LOG_ERROR, "Invalid value %d for log2_min_cb_size", sps->log2_min_cb_size);
1011
        return AVERROR_INVALIDDATA;
1012
    }
1013
1014
982
    if (sps->log2_diff_max_min_coding_block_size > 30) {
1015
        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);
1016
        return AVERROR_INVALIDDATA;
1017
    }
1018
1019

982
    if (sps->log2_min_tb_size >= sps->log2_min_cb_size || sps->log2_min_tb_size < 2) {
1020
        av_log(avctx, AV_LOG_ERROR, "Invalid value for log2_min_tb_size");
1021
        return AVERROR_INVALIDDATA;
1022
    }
1023
1024

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

3186
    if (!pps->col_bd || !pps->row_bd || !pps->col_idxX)
1341
        return AVERROR(ENOMEM);
1342
1343
3186
    if (pps->uniform_spacing_flag) {
1344
2658
        if (!pps->column_width) {
1345
2287
            pps->column_width = av_malloc_array(pps->num_tile_columns, sizeof(*pps->column_width));
1346
2287
            pps->row_height   = av_malloc_array(pps->num_tile_rows,    sizeof(*pps->row_height));
1347
        }
1348

2658
        if (!pps->column_width || !pps->row_height)
1349
            return AVERROR(ENOMEM);
1350
1351
5568
        for (i = 0; i < pps->num_tile_columns; i++) {
1352
2910
            pps->column_width[i] = ((i + 1) * sps->ctb_width) / pps->num_tile_columns -
1353
2910
                                   (i * sps->ctb_width) / pps->num_tile_columns;
1354
        }
1355
1356
5599
        for (i = 0; i < pps->num_tile_rows; i++) {
1357
2941
            pps->row_height[i] = ((i + 1) * sps->ctb_height) / pps->num_tile_rows -
1358
2941
                                 (i * sps->ctb_height) / pps->num_tile_rows;
1359
        }
1360
    }
1361
1362
3186
    pps->col_bd[0] = 0;
1363
8696
    for (i = 0; i < pps->num_tile_columns; i++)
1364
5510
        pps->col_bd[i + 1] = pps->col_bd[i] + pps->column_width[i];
1365
1366
3186
    pps->row_bd[0] = 0;
1367
8717
    for (i = 0; i < pps->num_tile_rows; i++)
1368
5531
        pps->row_bd[i + 1] = pps->row_bd[i] + pps->row_height[i];
1369
1370
57185
    for (i = 0, j = 0; i < sps->ctb_width; i++) {
1371
53999
        if (i > pps->col_bd[j])
1372
5500
            j++;
1373
53999
        pps->col_idxX[i] = j;
1374
    }
1375
1376
    /**
1377
     * 6.5
1378
     */
1379
3186
    pic_area_in_ctbs     = sps->ctb_width    * sps->ctb_height;
1380
1381
3186
    pps->ctb_addr_rs_to_ts = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->ctb_addr_rs_to_ts));
1382
3186
    pps->ctb_addr_ts_to_rs = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->ctb_addr_ts_to_rs));
1383
3186
    pps->tile_id           = av_malloc_array(pic_area_in_ctbs,    sizeof(*pps->tile_id));
1384
3186
    pps->min_tb_addr_zs_tab = av_malloc_array((sps->tb_mask+2) * (sps->tb_mask+2), sizeof(*pps->min_tb_addr_zs_tab));
1385

3186
    if (!pps->ctb_addr_rs_to_ts || !pps->ctb_addr_ts_to_rs ||
1386

3186
        !pps->tile_id || !pps->min_tb_addr_zs_tab) {
1387
        return AVERROR(ENOMEM);
1388
    }
1389
1390
720489
    for (ctb_addr_rs = 0; ctb_addr_rs < pic_area_in_ctbs; ctb_addr_rs++) {
1391
717303
        int tb_x   = ctb_addr_rs % sps->ctb_width;
1392
717303
        int tb_y   = ctb_addr_rs / sps->ctb_width;
1393
717303
        int tile_x = 0;
1394
717303
        int tile_y = 0;
1395
717303
        int val    = 0;
1396
1397
1225365
        for (i = 0; i < pps->num_tile_columns; i++) {
1398
1225365
            if (tb_x < pps->col_bd[i + 1]) {
1399
717303
                tile_x = i;
1400
717303
                break;
1401
            }
1402
        }
1403
1404
1075569
        for (i = 0; i < pps->num_tile_rows; i++) {
1405
1075569
            if (tb_y < pps->row_bd[i + 1]) {
1406
717303
                tile_y = i;
1407
717303
                break;
1408
            }
1409
        }
1410
1411
1225365
        for (i = 0; i < tile_x; i++)
1412
508062
            val += pps->row_height[tile_y] * pps->column_width[i];
1413
1075569
        for (i = 0; i < tile_y; i++)
1414
358266
            val += sps->ctb_width * pps->row_height[i];
1415
1416
717303
        val += (tb_y - pps->row_bd[tile_y]) * pps->column_width[tile_x] +
1417
717303
               tb_x - pps->col_bd[tile_x];
1418
1419
717303
        pps->ctb_addr_rs_to_ts[ctb_addr_rs] = val;
1420
717303
        pps->ctb_addr_ts_to_rs[val]         = ctb_addr_rs;
1421
    }
1422
1423
8717
    for (j = 0, tile_id = 0; j < pps->num_tile_rows; j++)
1424
21642
        for (i = 0; i < pps->num_tile_columns; i++, tile_id++)
1425
92020
            for (y = pps->row_bd[j]; y < pps->row_bd[j + 1]; y++)
1426
793212
                for (x = pps->col_bd[i]; x < pps->col_bd[i + 1]; x++)
1427
717303
                    pps->tile_id[pps->ctb_addr_rs_to_ts[y * sps->ctb_width + x]] = tile_id;
1428
1429
3186
    pps->tile_pos_rs = av_malloc_array(tile_id, sizeof(*pps->tile_pos_rs));
1430
3186
    if (!pps->tile_pos_rs)
1431
        return AVERROR(ENOMEM);
1432
1433
8717
    for (j = 0; j < pps->num_tile_rows; j++)
1434
21642
        for (i = 0; i < pps->num_tile_columns; i++)
1435
16111
            pps->tile_pos_rs[j * pps->num_tile_columns + i] =
1436
16111
                pps->row_bd[j] * sps->ctb_width + pps->col_bd[i];
1437
1438
3186
    log2_diff = sps->log2_ctb_size - sps->log2_min_tb_size;
1439
3186
    pps->min_tb_addr_zs = &pps->min_tb_addr_zs_tab[1*(sps->tb_mask+2)+1];
1440
56288
    for (y = 0; y < sps->tb_mask+2; y++) {
1441
53102
        pps->min_tb_addr_zs_tab[y*(sps->tb_mask+2)] = -1;
1442
53102
        pps->min_tb_addr_zs_tab[y]    = -1;
1443
    }
1444
53102
    for (y = 0; y < sps->tb_mask+1; y++) {
1445
842156
        for (x = 0; x < sps->tb_mask+1; x++) {
1446
792240
            int tb_x = x >> log2_diff;
1447
792240
            int tb_y = y >> log2_diff;
1448
792240
            int rs   = sps->ctb_width * tb_y + tb_x;
1449
792240
            int val  = pps->ctb_addr_rs_to_ts[rs] << (log2_diff * 2);
1450
3955472
            for (i = 0; i < log2_diff; i++) {
1451
3163232
                int m = 1 << i;
1452

3163232
                val += (m & x ? m * m : 0) + (m & y ? 2 * m * m : 0);
1453
            }
1454
792240
            pps->min_tb_addr_zs[y * (sps->tb_mask+2) + x] = val;
1455
        }
1456
    }
1457
1458
3186
    return 0;
1459
}
1460
1461
3190
int ff_hevc_decode_nal_pps(GetBitContext *gb, AVCodecContext *avctx,
1462
                           HEVCParamSets *ps)
1463
{
1464
3190
    HEVCSPS      *sps = NULL;
1465
3190
    int i, ret = 0;
1466
3190
    unsigned int pps_id = 0;
1467
    ptrdiff_t nal_size;
1468
    unsigned log2_parallel_merge_level_minus2;
1469
1470
    AVBufferRef *pps_buf;
1471
3190
    HEVCPPS *pps = av_mallocz(sizeof(*pps));
1472
1473
3190
    if (!pps)
1474
        return AVERROR(ENOMEM);
1475
1476
3190
    pps_buf = av_buffer_create((uint8_t *)pps, sizeof(*pps),
1477
                               hevc_pps_free, NULL, 0);
1478
3190
    if (!pps_buf) {
1479
        av_freep(&pps);
1480
        return AVERROR(ENOMEM);
1481
    }
1482
1483
3190
    av_log(avctx, AV_LOG_DEBUG, "Decoding PPS\n");
1484
1485
3190
    nal_size = gb->buffer_end - gb->buffer;
1486
3190
    if (nal_size > sizeof(pps->data)) {
1487
        av_log(avctx, AV_LOG_WARNING, "Truncating likely oversized PPS "
1488
               "(%"PTRDIFF_SPECIFIER" > %"SIZE_SPECIFIER")\n",
1489
               nal_size, sizeof(pps->data));
1490
        pps->data_size = sizeof(pps->data);
1491
    } else {
1492
3190
        pps->data_size = nal_size;
1493
    }
1494
3190
    memcpy(pps->data, gb->buffer, pps->data_size);
1495
1496
    // Default values
1497
3190
    pps->loop_filter_across_tiles_enabled_flag = 1;
1498
3190
    pps->num_tile_columns                      = 1;
1499
3190
    pps->num_tile_rows                         = 1;
1500
3190
    pps->uniform_spacing_flag                  = 1;
1501
3190
    pps->disable_dbf                           = 0;
1502
3190
    pps->beta_offset                           = 0;
1503
3190
    pps->tc_offset                             = 0;
1504
3190
    pps->log2_max_transform_skip_block_size    = 2;
1505
1506
    // Coded parameters
1507
3190
    pps_id = get_ue_golomb_long(gb);
1508
3190
    if (pps_id >= HEVC_MAX_PPS_COUNT) {
1509
        av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", pps_id);
1510
        ret = AVERROR_INVALIDDATA;
1511
        goto err;
1512
    }
1513
3190
    pps->sps_id = get_ue_golomb_long(gb);
1514
3190
    if (pps->sps_id >= HEVC_MAX_SPS_COUNT) {
1515
        av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", pps->sps_id);
1516
        ret = AVERROR_INVALIDDATA;
1517
        goto err;
1518
    }
1519
3190
    if (!ps->sps_list[pps->sps_id]) {
1520
4
        av_log(avctx, AV_LOG_ERROR, "SPS %u does not exist.\n", pps->sps_id);
1521
4
        ret = AVERROR_INVALIDDATA;
1522
4
        goto err;
1523
    }
1524
3186
    sps = (HEVCSPS *)ps->sps_list[pps->sps_id]->data;
1525
1526
3186
    pps->dependent_slice_segments_enabled_flag = get_bits1(gb);
1527
3186
    pps->output_flag_present_flag              = get_bits1(gb);
1528
3186
    pps->num_extra_slice_header_bits           = get_bits(gb, 3);
1529
1530
3186
    pps->sign_data_hiding_flag = get_bits1(gb);
1531
1532
3186
    pps->cabac_init_present_flag = get_bits1(gb);
1533
1534
3186
    pps->num_ref_idx_l0_default_active = get_ue_golomb_long(gb) + 1;
1535
3186
    pps->num_ref_idx_l1_default_active = get_ue_golomb_long(gb) + 1;
1536
1537
3186
    pps->pic_init_qp_minus26 = get_se_golomb(gb);
1538
1539
3186
    pps->constrained_intra_pred_flag = get_bits1(gb);
1540
3186
    pps->transform_skip_enabled_flag = get_bits1(gb);
1541
1542
3186
    pps->cu_qp_delta_enabled_flag = get_bits1(gb);
1543
3186
    pps->diff_cu_qp_delta_depth   = 0;
1544
3186
    if (pps->cu_qp_delta_enabled_flag)
1545
476
        pps->diff_cu_qp_delta_depth = get_ue_golomb_long(gb);
1546
1547
3186
    if (pps->diff_cu_qp_delta_depth < 0 ||
1548
3186
        pps->diff_cu_qp_delta_depth > sps->log2_diff_max_min_coding_block_size) {
1549
        av_log(avctx, AV_LOG_ERROR, "diff_cu_qp_delta_depth %d is invalid\n",
1550
               pps->diff_cu_qp_delta_depth);
1551
        ret = AVERROR_INVALIDDATA;
1552
        goto err;
1553
    }
1554
1555
3186
    pps->cb_qp_offset = get_se_golomb(gb);
1556

3186
    if (pps->cb_qp_offset < -12 || pps->cb_qp_offset > 12) {
1557
        av_log(avctx, AV_LOG_ERROR, "pps_cb_qp_offset out of range: %d\n",
1558
               pps->cb_qp_offset);
1559
        ret = AVERROR_INVALIDDATA;
1560
        goto err;
1561
    }
1562
3186
    pps->cr_qp_offset = get_se_golomb(gb);
1563

3186
    if (pps->cr_qp_offset < -12 || pps->cr_qp_offset > 12) {
1564
        av_log(avctx, AV_LOG_ERROR, "pps_cr_qp_offset out of range: %d\n",
1565
               pps->cr_qp_offset);
1566
        ret = AVERROR_INVALIDDATA;
1567
        goto err;
1568
    }
1569
3186
    pps->pic_slice_level_chroma_qp_offsets_present_flag = get_bits1(gb);
1570
1571
3186
    pps->weighted_pred_flag   = get_bits1(gb);
1572
3186
    pps->weighted_bipred_flag = get_bits1(gb);
1573
1574
3186
    pps->transquant_bypass_enable_flag    = get_bits1(gb);
1575
3186
    pps->tiles_enabled_flag               = get_bits1(gb);
1576
3186
    pps->entropy_coding_sync_enabled_flag = get_bits1(gb);
1577
1578
3186
    if (pps->tiles_enabled_flag) {
1579
899
        int num_tile_columns_minus1 = get_ue_golomb(gb);
1580
899
        int num_tile_rows_minus1    = get_ue_golomb(gb);
1581
1582
899
        if (num_tile_columns_minus1 < 0 ||
1583
899
            num_tile_columns_minus1 >= sps->ctb_width) {
1584
            av_log(avctx, AV_LOG_ERROR, "num_tile_columns_minus1 out of range: %d\n",
1585
                   num_tile_columns_minus1);
1586
            ret = num_tile_columns_minus1 < 0 ? num_tile_columns_minus1 : AVERROR_INVALIDDATA;
1587
            goto err;
1588
        }
1589
899
        if (num_tile_rows_minus1 < 0 ||
1590
899
            num_tile_rows_minus1 >= sps->ctb_height) {
1591
            av_log(avctx, AV_LOG_ERROR, "num_tile_rows_minus1 out of range: %d\n",
1592
                   num_tile_rows_minus1);
1593
            ret = num_tile_rows_minus1 < 0 ? num_tile_rows_minus1 : AVERROR_INVALIDDATA;
1594
            goto err;
1595
        }
1596
899
        pps->num_tile_columns = num_tile_columns_minus1 + 1;
1597
899
        pps->num_tile_rows    = num_tile_rows_minus1    + 1;
1598
1599
899
        pps->column_width = av_malloc_array(pps->num_tile_columns, sizeof(*pps->column_width));
1600
899
        pps->row_height   = av_malloc_array(pps->num_tile_rows,    sizeof(*pps->row_height));
1601

899
        if (!pps->column_width || !pps->row_height) {
1602
            ret = AVERROR(ENOMEM);
1603
            goto err;
1604
        }
1605
1606
899
        pps->uniform_spacing_flag = get_bits1(gb);
1607
899
        if (!pps->uniform_spacing_flag) {
1608
528
            uint64_t sum = 0;
1609
2600
            for (i = 0; i < pps->num_tile_columns - 1; i++) {
1610
2072
                pps->column_width[i] = get_ue_golomb_long(gb) + 1;
1611
2072
                sum                 += pps->column_width[i];
1612
            }
1613
528
            if (sum >= sps->ctb_width) {
1614
                av_log(avctx, AV_LOG_ERROR, "Invalid tile widths.\n");
1615
                ret = AVERROR_INVALIDDATA;
1616
                goto err;
1617
            }
1618
528
            pps->column_width[pps->num_tile_columns - 1] = sps->ctb_width - sum;
1619
1620
528
            sum = 0;
1621
2590
            for (i = 0; i < pps->num_tile_rows - 1; i++) {
1622
2062
                pps->row_height[i] = get_ue_golomb_long(gb) + 1;
1623
2062
                sum               += pps->row_height[i];
1624
            }
1625
528
            if (sum >= sps->ctb_height) {
1626
                av_log(avctx, AV_LOG_ERROR, "Invalid tile heights.\n");
1627
                ret = AVERROR_INVALIDDATA;
1628
                goto err;
1629
            }
1630
528
            pps->row_height[pps->num_tile_rows - 1] = sps->ctb_height - sum;
1631
        }
1632
899
        pps->loop_filter_across_tiles_enabled_flag = get_bits1(gb);
1633
    }
1634
1635
3186
    pps->seq_loop_filter_across_slices_enabled_flag = get_bits1(gb);
1636
1637
3186
    pps->deblocking_filter_control_present_flag = get_bits1(gb);
1638
3186
    if (pps->deblocking_filter_control_present_flag) {
1639
994
        pps->deblocking_filter_override_enabled_flag = get_bits1(gb);
1640
994
        pps->disable_dbf                             = get_bits1(gb);
1641
994
        if (!pps->disable_dbf) {
1642
852
            int beta_offset_div2 = get_se_golomb(gb);
1643
852
            int tc_offset_div2   = get_se_golomb(gb) ;
1644

852
            if (beta_offset_div2 < -6 || beta_offset_div2 > 6) {
1645
                av_log(avctx, AV_LOG_ERROR, "pps_beta_offset_div2 out of range: %d\n",
1646
                       beta_offset_div2);
1647
                ret = AVERROR_INVALIDDATA;
1648
                goto err;
1649
            }
1650

852
            if (tc_offset_div2 < -6 || tc_offset_div2 > 6) {
1651
                av_log(avctx, AV_LOG_ERROR, "pps_tc_offset_div2 out of range: %d\n",
1652
                       tc_offset_div2);
1653
                ret = AVERROR_INVALIDDATA;
1654
                goto err;
1655
            }
1656
852
            pps->beta_offset = 2 * beta_offset_div2;
1657
852
            pps->tc_offset   = 2 *   tc_offset_div2;
1658
        }
1659
    }
1660
1661
3186
    pps->scaling_list_data_present_flag = get_bits1(gb);
1662
3186
    if (pps->scaling_list_data_present_flag) {
1663
463
        set_default_scaling_list_data(&pps->scaling_list);
1664
463
        ret = scaling_list_data(gb, avctx, &pps->scaling_list, sps);
1665
463
        if (ret < 0)
1666
            goto err;
1667
    }
1668
3186
    pps->lists_modification_present_flag = get_bits1(gb);
1669
3186
    log2_parallel_merge_level_minus2     = get_ue_golomb_long(gb);
1670
3186
    if (log2_parallel_merge_level_minus2 > sps->log2_ctb_size) {
1671
        av_log(avctx, AV_LOG_ERROR, "log2_parallel_merge_level_minus2 out of range: %d\n",
1672
               log2_parallel_merge_level_minus2);
1673
        ret = AVERROR_INVALIDDATA;
1674
        goto err;
1675
    }
1676
3186
    pps->log2_parallel_merge_level       = log2_parallel_merge_level_minus2 + 2;
1677
1678
3186
    pps->slice_header_extension_present_flag = get_bits1(gb);
1679
1680
3186
    if (get_bits1(gb)) { // pps_extension_present_flag
1681
87
        pps->pps_range_extensions_flag = get_bits1(gb);
1682
87
        skip_bits(gb, 7); // pps_extension_7bits
1683

87
        if (sps->ptl.general_ptl.profile_idc == FF_PROFILE_HEVC_REXT && pps->pps_range_extensions_flag) {
1684
72
            if ((ret = pps_range_extensions(gb, avctx, pps, sps)) < 0)
1685
                goto err;
1686
        }
1687
    }
1688
1689
3186
    ret = setup_pps(avctx, gb, pps, sps);
1690
3186
    if (ret < 0)
1691
        goto err;
1692
1693
3186
    if (get_bits_left(gb) < 0) {
1694
        av_log(avctx, AV_LOG_ERROR,
1695
               "Overread PPS by %d bits\n", -get_bits_left(gb));
1696
        goto err;
1697
    }
1698
1699
3186
    remove_pps(ps, pps_id);
1700
3186
    ps->pps_list[pps_id] = pps_buf;
1701
1702
3186
    return 0;
1703
1704
4
err:
1705
4
    av_buffer_unref(&pps_buf);
1706
4
    return ret;
1707
}
1708
1709
558
void ff_hevc_ps_uninit(HEVCParamSets *ps)
1710
{
1711
    int i;
1712
1713
9486
    for (i = 0; i < FF_ARRAY_ELEMS(ps->vps_list); i++)
1714
8928
        av_buffer_unref(&ps->vps_list[i]);
1715
9486
    for (i = 0; i < FF_ARRAY_ELEMS(ps->sps_list); i++)
1716
8928
        av_buffer_unref(&ps->sps_list[i]);
1717
36270
    for (i = 0; i < FF_ARRAY_ELEMS(ps->pps_list); i++)
1718
35712
        av_buffer_unref(&ps->pps_list[i]);
1719
1720
558
    ps->sps = NULL;
1721
558
    ps->pps = NULL;
1722
558
    ps->vps = NULL;
1723
558
}
1724
1725
30192
int ff_hevc_compute_poc(const HEVCSPS *sps, int pocTid0, int poc_lsb, int nal_unit_type)
1726
{
1727
30192
    int max_poc_lsb  = 1 << sps->log2_max_poc_lsb;
1728
30192
    int prev_poc_lsb = pocTid0 % max_poc_lsb;
1729
30192
    int prev_poc_msb = pocTid0 - prev_poc_lsb;
1730
    int poc_msb;
1731
1732

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

30152
    else if (poc_lsb > prev_poc_lsb && poc_lsb - prev_poc_lsb > max_poc_lsb / 2)
1735
252
        poc_msb = prev_poc_msb - max_poc_lsb;
1736
    else
1737
29900
        poc_msb = prev_poc_msb;
1738
1739
    // For BLA picture types, POCmsb is set to 0.
1740

30192
    if (nal_unit_type == HEVC_NAL_BLA_W_LP   ||
1741
30171
        nal_unit_type == HEVC_NAL_BLA_W_RADL ||
1742
        nal_unit_type == HEVC_NAL_BLA_N_LP)
1743
24
        poc_msb = 0;
1744
1745
30192
    return poc_msb + poc_lsb;
1746
}