GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/dca_lbr.c Lines: 20 1000 2.0 %
Date: 2019-11-22 03:34:36 Branches: 9 692 1.3 %

Line Branch Exec Source
1
/*
2
 * Copyright (C) 2016 foo86
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
 */
20
21
#define BITSTREAM_READER_LE
22
23
#include "libavutil/channel_layout.h"
24
25
#include "dcadec.h"
26
#include "dcadata.h"
27
#include "dcahuff.h"
28
#include "dca_syncwords.h"
29
#include "bytestream.h"
30
31
#define AMP_MAX     56
32
33
enum LBRFlags {
34
    LBR_FLAG_24_BIT             = 0x01,
35
    LBR_FLAG_LFE_PRESENT        = 0x02,
36
    LBR_FLAG_BAND_LIMIT_2_3     = 0x04,
37
    LBR_FLAG_BAND_LIMIT_1_2     = 0x08,
38
    LBR_FLAG_BAND_LIMIT_1_3     = 0x0c,
39
    LBR_FLAG_BAND_LIMIT_1_4     = 0x10,
40
    LBR_FLAG_BAND_LIMIT_1_8     = 0x18,
41
    LBR_FLAG_BAND_LIMIT_NONE    = 0x14,
42
    LBR_FLAG_BAND_LIMIT_MASK    = 0x1c,
43
    LBR_FLAG_DMIX_STEREO        = 0x20,
44
    LBR_FLAG_DMIX_MULTI_CH      = 0x40
45
};
46
47
enum LBRChunkTypes {
48
    LBR_CHUNK_NULL              = 0x00,
49
    LBR_CHUNK_PAD               = 0x01,
50
    LBR_CHUNK_FRAME             = 0x04,
51
    LBR_CHUNK_FRAME_NO_CSUM     = 0x06,
52
    LBR_CHUNK_LFE               = 0x0a,
53
    LBR_CHUNK_ECS               = 0x0b,
54
    LBR_CHUNK_RESERVED_1        = 0x0c,
55
    LBR_CHUNK_RESERVED_2        = 0x0d,
56
    LBR_CHUNK_SCF               = 0x0e,
57
    LBR_CHUNK_TONAL             = 0x10,
58
    LBR_CHUNK_TONAL_GRP_1       = 0x11,
59
    LBR_CHUNK_TONAL_GRP_2       = 0x12,
60
    LBR_CHUNK_TONAL_GRP_3       = 0x13,
61
    LBR_CHUNK_TONAL_GRP_4       = 0x14,
62
    LBR_CHUNK_TONAL_GRP_5       = 0x15,
63
    LBR_CHUNK_TONAL_SCF         = 0x16,
64
    LBR_CHUNK_TONAL_SCF_GRP_1   = 0x17,
65
    LBR_CHUNK_TONAL_SCF_GRP_2   = 0x18,
66
    LBR_CHUNK_TONAL_SCF_GRP_3   = 0x19,
67
    LBR_CHUNK_TONAL_SCF_GRP_4   = 0x1a,
68
    LBR_CHUNK_TONAL_SCF_GRP_5   = 0x1b,
69
    LBR_CHUNK_RES_GRID_LR       = 0x30,
70
    LBR_CHUNK_RES_GRID_LR_LAST  = 0x3f,
71
    LBR_CHUNK_RES_GRID_HR       = 0x40,
72
    LBR_CHUNK_RES_GRID_HR_LAST  = 0x4f,
73
    LBR_CHUNK_RES_TS_1          = 0x50,
74
    LBR_CHUNK_RES_TS_1_LAST     = 0x5f,
75
    LBR_CHUNK_RES_TS_2          = 0x60,
76
    LBR_CHUNK_RES_TS_2_LAST     = 0x6f,
77
    LBR_CHUNK_EXTENSION         = 0x7f
78
};
79
80
typedef struct LBRChunk {
81
    int id, len;
82
    const uint8_t *data;
83
} LBRChunk;
84
85
static const int8_t channel_reorder_nolfe[7][5] = {
86
    { 0, -1, -1, -1, -1 },  // C
87
    { 0,  1, -1, -1, -1 },  // LR
88
    { 0,  1,  2, -1, -1 },  // LR C
89
    { 0,  1, -1, -1, -1 },  // LsRs
90
    { 1,  2,  0, -1, -1 },  // LsRs C
91
    { 0,  1,  2,  3, -1 },  // LR LsRs
92
    { 0,  1,  3,  4,  2 },  // LR LsRs C
93
};
94
95
static const int8_t channel_reorder_lfe[7][5] = {
96
    { 0, -1, -1, -1, -1 },  // C
97
    { 0,  1, -1, -1, -1 },  // LR
98
    { 0,  1,  2, -1, -1 },  // LR C
99
    { 1,  2, -1, -1, -1 },  // LsRs
100
    { 2,  3,  0, -1, -1 },  // LsRs C
101
    { 0,  1,  3,  4, -1 },  // LR LsRs
102
    { 0,  1,  4,  5,  2 },  // LR LsRs C
103
};
104
105
static const uint8_t lfe_index[7] = {
106
    1, 2, 3, 0, 1, 2, 3
107
};
108
109
static const uint8_t channel_counts[7] = {
110
    1, 2, 3, 2, 3, 4, 5
111
};
112
113
static const uint16_t channel_layouts[7] = {
114
    AV_CH_LAYOUT_MONO,
115
    AV_CH_LAYOUT_STEREO,
116
    AV_CH_LAYOUT_SURROUND,
117
    AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,
118
    AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,
119
    AV_CH_LAYOUT_2_2,
120
    AV_CH_LAYOUT_5POINT0
121
};
122
123
static float    cos_tab[256];
124
static float    lpc_tab[16];
125
126
92
static av_cold void init_tables(void)
127
{
128
    static int initialized;
129
    int i;
130
131
92
    if (initialized)
132
45
        return;
133
134
12079
    for (i = 0; i < 256; i++)
135
12032
        cos_tab[i] = cos(M_PI * i / 128);
136
137
799
    for (i = 0; i < 16; i++)
138
752
        lpc_tab[i] = sin((i - 8) * (M_PI / ((i < 8) ? 17 : 15)));
139
140
47
    initialized = 1;
141
}
142
143
static int parse_lfe_24(DCALbrDecoder *s)
144
{
145
    int step_max = FF_ARRAY_ELEMS(ff_dca_lfe_step_size_24) - 1;
146
    int i, ps, si, code, step_i;
147
    float step, value, delta;
148
149
    ps = get_bits(&s->gb, 24);
150
    si = ps >> 23;
151
152
    value = (((ps & 0x7fffff) ^ -si) + si) * (1.0f / 0x7fffff);
153
154
    step_i = get_bits(&s->gb, 8);
155
    if (step_i > step_max) {
156
        av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE step size index\n");
157
        return -1;
158
    }
159
160
    step = ff_dca_lfe_step_size_24[step_i];
161
162
    for (i = 0; i < 64; i++) {
163
        code = get_bits(&s->gb, 6);
164
165
        delta = step * 0.03125f;
166
        if (code & 16)
167
            delta += step;
168
        if (code & 8)
169
            delta += step * 0.5f;
170
        if (code & 4)
171
            delta += step * 0.25f;
172
        if (code & 2)
173
            delta += step * 0.125f;
174
        if (code & 1)
175
            delta += step * 0.0625f;
176
177
        if (code & 32) {
178
            value -= delta;
179
            if (value < -3.0f)
180
                value = -3.0f;
181
        } else {
182
            value += delta;
183
            if (value > 3.0f)
184
                value = 3.0f;
185
        }
186
187
        step_i += ff_dca_lfe_delta_index_24[code & 31];
188
        step_i = av_clip(step_i, 0, step_max);
189
190
        step = ff_dca_lfe_step_size_24[step_i];
191
        s->lfe_data[i] = value * s->lfe_scale;
192
    }
193
194
    return 0;
195
}
196
197
static int parse_lfe_16(DCALbrDecoder *s)
198
{
199
    int step_max = FF_ARRAY_ELEMS(ff_dca_lfe_step_size_16) - 1;
200
    int i, ps, si, code, step_i;
201
    float step, value, delta;
202
203
    ps = get_bits(&s->gb, 16);
204
    si = ps >> 15;
205
206
    value = (((ps & 0x7fff) ^ -si) + si) * (1.0f / 0x7fff);
207
208
    step_i = get_bits(&s->gb, 8);
209
    if (step_i > step_max) {
210
        av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE step size index\n");
211
        return -1;
212
    }
213
214
    step = ff_dca_lfe_step_size_16[step_i];
215
216
    for (i = 0; i < 64; i++) {
217
        code = get_bits(&s->gb, 4);
218
219
        delta = step * 0.125f;
220
        if (code & 4)
221
            delta += step;
222
        if (code & 2)
223
            delta += step * 0.5f;
224
        if (code & 1)
225
            delta += step * 0.25f;
226
227
        if (code & 8) {
228
            value -= delta;
229
            if (value < -3.0f)
230
                value = -3.0f;
231
        } else {
232
            value += delta;
233
            if (value > 3.0f)
234
                value = 3.0f;
235
        }
236
237
        step_i += ff_dca_lfe_delta_index_16[code & 7];
238
        step_i = av_clip(step_i, 0, step_max);
239
240
        step = ff_dca_lfe_step_size_16[step_i];
241
        s->lfe_data[i] = value * s->lfe_scale;
242
    }
243
244
    return 0;
245
}
246
247
static int parse_lfe_chunk(DCALbrDecoder *s, LBRChunk *chunk)
248
{
249
    if (!(s->flags & LBR_FLAG_LFE_PRESENT))
250
        return 0;
251
252
    if (!chunk->len)
253
        return 0;
254
255
    if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
256
        return -1;
257
258
    // Determine bit depth from chunk size
259
    if (chunk->len >= 52)
260
        return parse_lfe_24(s);
261
    if (chunk->len >= 35)
262
        return parse_lfe_16(s);
263
264
    av_log(s->avctx, AV_LOG_ERROR, "LFE chunk too short\n");
265
    return -1;
266
}
267
268
static inline int parse_vlc(GetBitContext *s, VLC *vlc, int max_depth)
269
{
270
    int v = get_vlc2(s, vlc->table, vlc->bits, max_depth);
271
    if (v > 0)
272
        return v - 1;
273
    // Rare value
274
    return get_bits(s, get_bits(s, 3) + 1);
275
}
276
277
static int parse_tonal(DCALbrDecoder *s, int group)
278
{
279
    unsigned int amp[DCA_LBR_CHANNELS_TOTAL];
280
    unsigned int phs[DCA_LBR_CHANNELS_TOTAL];
281
    unsigned int diff, main_amp, shift;
282
    int sf, sf_idx, ch, main_ch, freq;
283
    int ch_nbits = av_ceil_log2(s->nchannels_total);
284
285
    // Parse subframes for this group
286
    for (sf = 0; sf < 1 << group; sf += diff ? 8 : 1) {
287
        sf_idx = ((s->framenum << group) + sf) & 31;
288
        s->tonal_bounds[group][sf_idx][0] = s->ntones;
289
290
        // Parse tones for this subframe
291
        for (freq = 1;; freq++) {
292
            if (get_bits_left(&s->gb) < 1) {
293
                av_log(s->avctx, AV_LOG_ERROR, "Tonal group chunk too short\n");
294
                return -1;
295
            }
296
297
            diff = parse_vlc(&s->gb, &ff_dca_vlc_tnl_grp[group], 2);
298
            if (diff >= FF_ARRAY_ELEMS(ff_dca_fst_amp)) {
299
                av_log(s->avctx, AV_LOG_ERROR, "Invalid tonal frequency diff\n");
300
                return -1;
301
            }
302
303
            diff = get_bitsz(&s->gb, diff >> 2) + ff_dca_fst_amp[diff];
304
            if (diff <= 1)
305
                break;  // End of subframe
306
307
            freq += diff - 2;
308
            if (freq >> (5 - group) > s->nsubbands * 4 - 6) {
309
                av_log(s->avctx, AV_LOG_ERROR, "Invalid spectral line offset\n");
310
                return -1;
311
            }
312
313
            // Main channel
314
            main_ch = get_bitsz(&s->gb, ch_nbits);
315
            main_amp = parse_vlc(&s->gb, &ff_dca_vlc_tnl_scf, 2)
316
                + s->tonal_scf[ff_dca_freq_to_sb[freq >> (7 - group)]]
317
                + s->limited_range - 2;
318
            amp[main_ch] = main_amp < AMP_MAX ? main_amp : 0;
319
            phs[main_ch] = get_bits(&s->gb, 3);
320
321
            // Secondary channels
322
            for (ch = 0; ch < s->nchannels_total; ch++) {
323
                if (ch == main_ch)
324
                    continue;
325
                if (get_bits1(&s->gb)) {
326
                    amp[ch] = amp[main_ch] - parse_vlc(&s->gb, &ff_dca_vlc_damp, 1);
327
                    phs[ch] = phs[main_ch] - parse_vlc(&s->gb, &ff_dca_vlc_dph,  1);
328
                } else {
329
                    amp[ch] = 0;
330
                    phs[ch] = 0;
331
                }
332
            }
333
334
            if (amp[main_ch]) {
335
                // Allocate new tone
336
                DCALbrTone *t = &s->tones[s->ntones];
337
                s->ntones = (s->ntones + 1) & (DCA_LBR_TONES - 1);
338
339
                t->x_freq = freq >> (5 - group);
340
                t->f_delt = (freq & ((1 << (5 - group)) - 1)) << group;
341
                t->ph_rot = 256 - (t->x_freq & 1) * 128 - t->f_delt * 4;
342
343
                shift = ff_dca_ph0_shift[(t->x_freq & 3) * 2 + (freq & 1)]
344
                    - ((t->ph_rot << (5 - group)) - t->ph_rot);
345
346
                for (ch = 0; ch < s->nchannels; ch++) {
347
                    t->amp[ch] = amp[ch] < AMP_MAX ? amp[ch] : 0;
348
                    t->phs[ch] = 128 - phs[ch] * 32 + shift;
349
                }
350
            }
351
        }
352
353
        s->tonal_bounds[group][sf_idx][1] = s->ntones;
354
    }
355
356
    return 0;
357
}
358
359
static int parse_tonal_chunk(DCALbrDecoder *s, LBRChunk *chunk)
360
{
361
    int sb, group;
362
363
    if (!chunk->len)
364
        return 0;
365
366
    if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
367
        return -1;
368
369
    // Scale factors
370
    if (chunk->id == LBR_CHUNK_SCF || chunk->id == LBR_CHUNK_TONAL_SCF) {
371
        if (get_bits_left(&s->gb) < 36) {
372
            av_log(s->avctx, AV_LOG_ERROR, "Tonal scale factor chunk too short\n");
373
            return -1;
374
        }
375
        for (sb = 0; sb < 6; sb++)
376
            s->tonal_scf[sb] = get_bits(&s->gb, 6);
377
    }
378
379
    // Tonal groups
380
    if (chunk->id == LBR_CHUNK_TONAL || chunk->id == LBR_CHUNK_TONAL_SCF)
381
        for (group = 0; group < 5; group++)
382
            if (parse_tonal(s, group) < 0)
383
                return -1;
384
385
    return 0;
386
}
387
388
static int parse_tonal_group(DCALbrDecoder *s, LBRChunk *chunk)
389
{
390
    if (!chunk->len)
391
        return 0;
392
393
    if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
394
        return -1;
395
396
    return parse_tonal(s, chunk->id);
397
}
398
399
/**
400
 * Check point to ensure that enough bits are left. Aborts decoding
401
 * by skipping to the end of chunk otherwise.
402
 */
403
static int ensure_bits(GetBitContext *s, int n)
404
{
405
    int left = get_bits_left(s);
406
    if (left < 0)
407
        return -1;
408
    if (left < n) {
409
        skip_bits_long(s, left);
410
        return 1;
411
    }
412
    return 0;
413
}
414
415
static int parse_scale_factors(DCALbrDecoder *s, uint8_t *scf)
416
{
417
    int i, sf, prev, next, dist;
418
419
    // Truncated scale factors remain zero
420
    if (ensure_bits(&s->gb, 20))
421
        return 0;
422
423
    // Initial scale factor
424
    prev = parse_vlc(&s->gb, &ff_dca_vlc_fst_rsd_amp, 2);
425
426
    for (sf = 0; sf < 7; sf += dist) {
427
        scf[sf] = prev; // Store previous value
428
429
        if (ensure_bits(&s->gb, 20))
430
            return 0;
431
432
        // Interpolation distance
433
        dist = parse_vlc(&s->gb, &ff_dca_vlc_rsd_apprx, 1) + 1;
434
        if (dist > 7 - sf) {
435
            av_log(s->avctx, AV_LOG_ERROR, "Invalid scale factor distance\n");
436
            return -1;
437
        }
438
439
        if (ensure_bits(&s->gb, 20))
440
            return 0;
441
442
        // Final interpolation point
443
        next = parse_vlc(&s->gb, &ff_dca_vlc_rsd_amp, 2);
444
445
        if (next & 1)
446
            next = prev + ((next + 1) >> 1);
447
        else
448
            next = prev - ( next      >> 1);
449
450
        // Interpolate
451
        switch (dist) {
452
        case 2:
453
            if (next > prev)
454
                scf[sf + 1] = prev + ((next - prev) >> 1);
455
            else
456
                scf[sf + 1] = prev - ((prev - next) >> 1);
457
            break;
458
459
        case 4:
460
            if (next > prev) {
461
                scf[sf + 1] = prev + ( (next - prev)      >> 2);
462
                scf[sf + 2] = prev + ( (next - prev)      >> 1);
463
                scf[sf + 3] = prev + (((next - prev) * 3) >> 2);
464
            } else {
465
                scf[sf + 1] = prev - ( (prev - next)      >> 2);
466
                scf[sf + 2] = prev - ( (prev - next)      >> 1);
467
                scf[sf + 3] = prev - (((prev - next) * 3) >> 2);
468
            }
469
            break;
470
471
        default:
472
            for (i = 1; i < dist; i++)
473
                scf[sf + i] = prev + (next - prev) * i / dist;
474
            break;
475
        }
476
477
        prev = next;
478
    }
479
480
    scf[sf] = next; // Store final value
481
482
    return 0;
483
}
484
485
static int parse_st_code(GetBitContext *s, int min_v)
486
{
487
    unsigned int v = parse_vlc(s, &ff_dca_vlc_st_grid, 2) + min_v;
488
489
    if (v & 1)
490
        v = 16 + (v >> 1);
491
    else
492
        v = 16 - (v >> 1);
493
494
    if (v >= FF_ARRAY_ELEMS(ff_dca_st_coeff))
495
        v = 16;
496
    return v;
497
}
498
499
static int parse_grid_1_chunk(DCALbrDecoder *s, LBRChunk *chunk, int ch1, int ch2)
500
{
501
    int ch, sb, sf, nsubbands;
502
503
    if (!chunk->len)
504
        return 0;
505
506
    if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
507
        return -1;
508
509
    // Scale factors
510
    nsubbands = ff_dca_scf_to_grid_1[s->nsubbands - 1] + 1;
511
    for (sb = 2; sb < nsubbands; sb++) {
512
        if (parse_scale_factors(s, s->grid_1_scf[ch1][sb]) < 0)
513
            return -1;
514
        if (ch1 != ch2 && ff_dca_grid_1_to_scf[sb] < s->min_mono_subband
515
            && parse_scale_factors(s, s->grid_1_scf[ch2][sb]) < 0)
516
            return -1;
517
    }
518
519
    if (get_bits_left(&s->gb) < 1)
520
        return 0;   // Should not happen, but a sample exists that proves otherwise
521
522
    // Average values for third grid
523
    for (sb = 0; sb < s->nsubbands - 4; sb++) {
524
        s->grid_3_avg[ch1][sb] = parse_vlc(&s->gb, &ff_dca_vlc_avg_g3, 2) - 16;
525
        if (ch1 != ch2) {
526
            if (sb + 4 < s->min_mono_subband)
527
                s->grid_3_avg[ch2][sb] = parse_vlc(&s->gb, &ff_dca_vlc_avg_g3, 2) - 16;
528
            else
529
                s->grid_3_avg[ch2][sb] = s->grid_3_avg[ch1][sb];
530
        }
531
    }
532
533
    if (get_bits_left(&s->gb) < 0) {
534
        av_log(s->avctx, AV_LOG_ERROR, "First grid chunk too short\n");
535
        return -1;
536
    }
537
538
    // Stereo image for partial mono mode
539
    if (ch1 != ch2) {
540
        int min_v[2];
541
542
        if (ensure_bits(&s->gb, 8))
543
            return 0;
544
545
        min_v[0] = get_bits(&s->gb, 4);
546
        min_v[1] = get_bits(&s->gb, 4);
547
548
        nsubbands = (s->nsubbands - s->min_mono_subband + 3) / 4;
549
        for (sb = 0; sb < nsubbands; sb++)
550
            for (ch = ch1; ch <= ch2; ch++)
551
                for (sf = 1; sf <= 4; sf++)
552
                    s->part_stereo[ch][sb][sf] = parse_st_code(&s->gb, min_v[ch - ch1]);
553
554
        if (get_bits_left(&s->gb) >= 0)
555
            s->part_stereo_pres |= 1 << ch1;
556
    }
557
558
    // Low resolution spatial information is not decoded
559
560
    return 0;
561
}
562
563
static int parse_grid_1_sec_ch(DCALbrDecoder *s, int ch2)
564
{
565
    int sb, nsubbands;
566
567
    // Scale factors
568
    nsubbands = ff_dca_scf_to_grid_1[s->nsubbands - 1] + 1;
569
    for (sb = 2; sb < nsubbands; sb++) {
570
        if (ff_dca_grid_1_to_scf[sb] >= s->min_mono_subband
571
            && parse_scale_factors(s, s->grid_1_scf[ch2][sb]) < 0)
572
            return -1;
573
    }
574
575
    // Average values for third grid
576
    for (sb = 0; sb < s->nsubbands - 4; sb++) {
577
        if (sb + 4 >= s->min_mono_subband) {
578
            if (ensure_bits(&s->gb, 20))
579
                return 0;
580
            s->grid_3_avg[ch2][sb] = parse_vlc(&s->gb, &ff_dca_vlc_avg_g3, 2) - 16;
581
        }
582
    }
583
584
    return 0;
585
}
586
587
static void parse_grid_3(DCALbrDecoder *s, int ch1, int ch2, int sb, int flag)
588
{
589
    int i, ch;
590
591
    for (ch = ch1; ch <= ch2; ch++) {
592
        if ((ch != ch1 && sb + 4 >= s->min_mono_subband) != flag)
593
            continue;
594
595
        if (s->grid_3_pres[ch] & (1U << sb))
596
            continue;   // Already parsed
597
598
        for (i = 0; i < 8; i++) {
599
            if (ensure_bits(&s->gb, 20))
600
                return;
601
            s->grid_3_scf[ch][sb][i] = parse_vlc(&s->gb, &ff_dca_vlc_grid_3, 2) - 16;
602
        }
603
604
        // Flag scale factors for this subband parsed
605
        s->grid_3_pres[ch] |= 1U << sb;
606
    }
607
}
608
609
static float lbr_rand(DCALbrDecoder *s, int sb)
610
{
611
    s->lbr_rand = 1103515245U * s->lbr_rand + 12345U;
612
    return s->lbr_rand * s->sb_scf[sb];
613
}
614
615
/**
616
 * Parse time samples for one subband, filling truncated samples with randomness
617
 */
618
static void parse_ch(DCALbrDecoder *s, int ch, int sb, int quant_level, int flag)
619
{
620
    float *samples = s->time_samples[ch][sb];
621
    int i, j, code, nblocks, coding_method;
622
623
    if (ensure_bits(&s->gb, 20))
624
        return; // Too few bits left
625
626
    coding_method = get_bits1(&s->gb);
627
628
    switch (quant_level) {
629
    case 1:
630
        nblocks = FFMIN(get_bits_left(&s->gb) / 8, DCA_LBR_TIME_SAMPLES / 8);
631
        for (i = 0; i < nblocks; i++, samples += 8) {
632
            code = get_bits(&s->gb, 8);
633
            for (j = 0; j < 8; j++)
634
                samples[j] = ff_dca_rsd_level_2a[(code >> j) & 1];
635
        }
636
        i = nblocks * 8;
637
        break;
638
639
    case 2:
640
        if (coding_method) {
641
            for (i = 0; i < DCA_LBR_TIME_SAMPLES && get_bits_left(&s->gb) >= 2; i++) {
642
                if (get_bits1(&s->gb))
643
                    samples[i] = ff_dca_rsd_level_2b[get_bits1(&s->gb)];
644
                else
645
                    samples[i] = 0;
646
            }
647
        } else {
648
            nblocks = FFMIN(get_bits_left(&s->gb) / 8, (DCA_LBR_TIME_SAMPLES + 4) / 5);
649
            for (i = 0; i < nblocks; i++, samples += 5) {
650
                code = ff_dca_rsd_pack_5_in_8[get_bits(&s->gb, 8)];
651
                for (j = 0; j < 5; j++)
652
                    samples[j] = ff_dca_rsd_level_3[(code >> j * 2) & 3];
653
            }
654
            i = nblocks * 5;
655
        }
656
        break;
657
658
    case 3:
659
        nblocks = FFMIN(get_bits_left(&s->gb) / 7, (DCA_LBR_TIME_SAMPLES + 2) / 3);
660
        for (i = 0; i < nblocks; i++, samples += 3) {
661
            code = get_bits(&s->gb, 7);
662
            for (j = 0; j < 3; j++)
663
                samples[j] = ff_dca_rsd_level_5[ff_dca_rsd_pack_3_in_7[code][j]];
664
        }
665
        i = nblocks * 3;
666
        break;
667
668
    case 4:
669
        for (i = 0; i < DCA_LBR_TIME_SAMPLES && get_bits_left(&s->gb) >= 6; i++)
670
            samples[i] = ff_dca_rsd_level_8[get_vlc2(&s->gb, ff_dca_vlc_rsd.table, 6, 1)];
671
        break;
672
673
    case 5:
674
        nblocks = FFMIN(get_bits_left(&s->gb) / 4, DCA_LBR_TIME_SAMPLES);
675
        for (i = 0; i < nblocks; i++)
676
            samples[i] = ff_dca_rsd_level_16[get_bits(&s->gb, 4)];
677
        break;
678
679
    default:
680
        av_assert0(0);
681
    }
682
683
    if (flag && get_bits_left(&s->gb) < 20)
684
        return; // Skip incomplete mono subband
685
686
    for (; i < DCA_LBR_TIME_SAMPLES; i++)
687
        s->time_samples[ch][sb][i] = lbr_rand(s, sb);
688
689
    s->ch_pres[ch] |= 1U << sb;
690
}
691
692
static int parse_ts(DCALbrDecoder *s, int ch1, int ch2,
693
                    int start_sb, int end_sb, int flag)
694
{
695
    int sb, sb_g3, sb_reorder, quant_level;
696
697
    for (sb = start_sb; sb < end_sb; sb++) {
698
        // Subband number before reordering
699
        if (sb < 6) {
700
            sb_reorder = sb;
701
        } else if (flag && sb < s->max_mono_subband) {
702
            sb_reorder = s->sb_indices[sb];
703
        } else {
704
            if (ensure_bits(&s->gb, 28))
705
                break;
706
            sb_reorder = get_bits(&s->gb, s->limited_range + 3);
707
            if (sb_reorder < 6)
708
                sb_reorder = 6;
709
            s->sb_indices[sb] = sb_reorder;
710
        }
711
        if (sb_reorder >= s->nsubbands)
712
            return -1;
713
714
        // Third grid scale factors
715
        if (sb == 12) {
716
            for (sb_g3 = 0; sb_g3 < s->g3_avg_only_start_sb - 4; sb_g3++)
717
                parse_grid_3(s, ch1, ch2, sb_g3, flag);
718
        } else if (sb < 12 && sb_reorder >= 4) {
719
            parse_grid_3(s, ch1, ch2, sb_reorder - 4, flag);
720
        }
721
722
        // Secondary channel flags
723
        if (ch1 != ch2) {
724
            if (ensure_bits(&s->gb, 20))
725
                break;
726
            if (!flag || sb_reorder >= s->max_mono_subband)
727
                s->sec_ch_sbms[ch1 / 2][sb_reorder] = get_bits(&s->gb, 8);
728
            if (flag && sb_reorder >= s->min_mono_subband)
729
                s->sec_ch_lrms[ch1 / 2][sb_reorder] = get_bits(&s->gb, 8);
730
        }
731
732
        quant_level = s->quant_levels[ch1 / 2][sb];
733
        if (!quant_level)
734
            return -1;
735
736
        // Time samples for one or both channels
737
        if (sb < s->max_mono_subband && sb_reorder >= s->min_mono_subband) {
738
            if (!flag)
739
                parse_ch(s, ch1, sb_reorder, quant_level, 0);
740
            else if (ch1 != ch2)
741
                parse_ch(s, ch2, sb_reorder, quant_level, 1);
742
        } else {
743
            parse_ch(s, ch1, sb_reorder, quant_level, 0);
744
            if (ch1 != ch2)
745
                parse_ch(s, ch2, sb_reorder, quant_level, 0);
746
        }
747
    }
748
749
    return 0;
750
}
751
752
/**
753
 * Convert from reflection coefficients to direct form coefficients
754
 */
755
static void convert_lpc(float *coeff, const int *codes)
756
{
757
    int i, j;
758
759
    for (i = 0; i < 8; i++) {
760
        float rc = lpc_tab[codes[i]];
761
        for (j = 0; j < (i + 1) / 2; j++) {
762
            float tmp1 = coeff[    j    ];
763
            float tmp2 = coeff[i - j - 1];
764
            coeff[    j    ] = tmp1 + rc * tmp2;
765
            coeff[i - j - 1] = tmp2 + rc * tmp1;
766
        }
767
        coeff[i] = rc;
768
    }
769
}
770
771
static int parse_lpc(DCALbrDecoder *s, int ch1, int ch2, int start_sb, int end_sb)
772
{
773
    int f = s->framenum & 1;
774
    int i, sb, ch, codes[16];
775
776
    // First two subbands have two sets of coefficients, third subband has one
777
    for (sb = start_sb; sb < end_sb; sb++) {
778
        int ncodes = 8 * (1 + (sb < 2));
779
        for (ch = ch1; ch <= ch2; ch++) {
780
            if (ensure_bits(&s->gb, 4 * ncodes))
781
                return 0;
782
            for (i = 0; i < ncodes; i++)
783
                codes[i] = get_bits(&s->gb, 4);
784
            for (i = 0; i < ncodes / 8; i++)
785
                convert_lpc(s->lpc_coeff[f][ch][sb][i], &codes[i * 8]);
786
        }
787
    }
788
789
    return 0;
790
}
791
792
static int parse_high_res_grid(DCALbrDecoder *s, LBRChunk *chunk, int ch1, int ch2)
793
{
794
    int quant_levels[DCA_LBR_SUBBANDS];
795
    int sb, ch, ol, st, max_sb, profile;
796
797
    if (!chunk->len)
798
        return 0;
799
800
    if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
801
        return -1;
802
803
    // Quantizer profile
804
    profile = get_bits(&s->gb, 8);
805
    // Overall level
806
    ol = (profile >> 3) & 7;
807
    // Steepness
808
    st = profile >> 6;
809
    // Max energy subband
810
    max_sb = profile & 7;
811
812
    // Calculate quantization levels
813
    for (sb = 0; sb < s->nsubbands; sb++) {
814
        int f = sb * s->limited_rate / s->nsubbands;
815
        int a = 18000 / (12 * f / 1000 + 100 + 40 * st) + 20 * ol;
816
        if (a <= 95)
817
            quant_levels[sb] = 1;
818
        else if (a <= 140)
819
            quant_levels[sb] = 2;
820
        else if (a <= 180)
821
            quant_levels[sb] = 3;
822
        else if (a <= 230)
823
            quant_levels[sb] = 4;
824
        else
825
            quant_levels[sb] = 5;
826
    }
827
828
    // Reorder quantization levels for lower subbands
829
    for (sb = 0; sb < 8; sb++)
830
        s->quant_levels[ch1 / 2][sb] = quant_levels[ff_dca_sb_reorder[max_sb][sb]];
831
    for (; sb < s->nsubbands; sb++)
832
        s->quant_levels[ch1 / 2][sb] = quant_levels[sb];
833
834
    // LPC for the first two subbands
835
    if (parse_lpc(s, ch1, ch2, 0, 2) < 0)
836
        return -1;
837
838
    // Time-samples for the first two subbands of main channel
839
    if (parse_ts(s, ch1, ch2, 0, 2, 0) < 0)
840
        return -1;
841
842
    // First two bands of the first grid
843
    for (sb = 0; sb < 2; sb++)
844
        for (ch = ch1; ch <= ch2; ch++)
845
            if (parse_scale_factors(s, s->grid_1_scf[ch][sb]) < 0)
846
                return -1;
847
848
    return 0;
849
}
850
851
static int parse_grid_2(DCALbrDecoder *s, int ch1, int ch2,
852
                        int start_sb, int end_sb, int flag)
853
{
854
    int i, j, sb, ch, nsubbands;
855
856
    nsubbands = ff_dca_scf_to_grid_2[s->nsubbands - 1] + 1;
857
    if (end_sb > nsubbands)
858
        end_sb = nsubbands;
859
860
    for (sb = start_sb; sb < end_sb; sb++) {
861
        for (ch = ch1; ch <= ch2; ch++) {
862
            uint8_t *g2_scf = s->grid_2_scf[ch][sb];
863
864
            if ((ch != ch1 && ff_dca_grid_2_to_scf[sb] >= s->min_mono_subband) != flag) {
865
                if (!flag)
866
                    memcpy(g2_scf, s->grid_2_scf[ch1][sb], 64);
867
                continue;
868
            }
869
870
            // Scale factors in groups of 8
871
            for (i = 0; i < 8; i++, g2_scf += 8) {
872
                if (get_bits_left(&s->gb) < 1) {
873
                    memset(g2_scf, 0, 64 - i * 8);
874
                    break;
875
                }
876
                // Bit indicating if whole group has zero values
877
                if (get_bits1(&s->gb)) {
878
                    for (j = 0; j < 8; j++) {
879
                        if (ensure_bits(&s->gb, 20))
880
                            break;
881
                        g2_scf[j] = parse_vlc(&s->gb, &ff_dca_vlc_grid_2, 2);
882
                    }
883
                } else {
884
                    memset(g2_scf, 0, 8);
885
                }
886
            }
887
        }
888
    }
889
890
    return 0;
891
}
892
893
static int parse_ts1_chunk(DCALbrDecoder *s, LBRChunk *chunk, int ch1, int ch2)
894
{
895
    if (!chunk->len)
896
        return 0;
897
    if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
898
        return -1;
899
    if (parse_lpc(s, ch1, ch2, 2, 3) < 0)
900
        return -1;
901
    if (parse_ts(s, ch1, ch2, 2, 4, 0) < 0)
902
        return -1;
903
    if (parse_grid_2(s, ch1, ch2, 0, 1, 0) < 0)
904
        return -1;
905
    if (parse_ts(s, ch1, ch2, 4, 6, 0) < 0)
906
        return -1;
907
    return 0;
908
}
909
910
static int parse_ts2_chunk(DCALbrDecoder *s, LBRChunk *chunk, int ch1, int ch2)
911
{
912
    if (!chunk->len)
913
        return 0;
914
    if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
915
        return -1;
916
    if (parse_grid_2(s, ch1, ch2, 1, 3, 0) < 0)
917
        return -1;
918
    if (parse_ts(s, ch1, ch2, 6, s->max_mono_subband, 0) < 0)
919
        return -1;
920
    if (ch1 != ch2) {
921
        if (parse_grid_1_sec_ch(s, ch2) < 0)
922
            return -1;
923
        if (parse_grid_2(s, ch1, ch2, 0, 3, 1) < 0)
924
            return -1;
925
    }
926
    if (parse_ts(s, ch1, ch2, s->min_mono_subband, s->nsubbands, 1) < 0)
927
        return -1;
928
    return 0;
929
}
930
931
static int init_sample_rate(DCALbrDecoder *s)
932
{
933
    double scale = (-1.0 / (1 << 17)) * sqrt(1 << (2 - s->limited_range));
934
    int i, br_per_ch = s->bit_rate_scaled / s->nchannels_total;
935
936
    ff_mdct_end(&s->imdct);
937
938
    if (ff_mdct_init(&s->imdct, s->freq_range + 6, 1, scale) < 0)
939
        return -1;
940
941
    for (i = 0; i < 32 << s->freq_range; i++)
942
        s->window[i] = ff_dca_long_window[i << (2 - s->freq_range)];
943
944
    if (br_per_ch < 14000)
945
        scale = 0.85;
946
    else if (br_per_ch < 32000)
947
        scale = (br_per_ch - 14000) * (1.0 / 120000) + 0.85;
948
    else
949
        scale = 1.0;
950
951
    scale *= 1.0 / INT_MAX;
952
953
    for (i = 0; i < s->nsubbands; i++) {
954
        if (i < 2)
955
            s->sb_scf[i] = 0;   // The first two subbands are always zero
956
        else if (i < 5)
957
            s->sb_scf[i] = (i - 1) * 0.25 * 0.785 * scale;
958
        else
959
            s->sb_scf[i] = 0.785 * scale;
960
    }
961
962
    s->lfe_scale = (16 << s->freq_range) * 0.0000078265894;
963
964
    return 0;
965
}
966
967
static int alloc_sample_buffer(DCALbrDecoder *s)
968
{
969
    // Reserve space for history and padding
970
    int nchsamples = DCA_LBR_TIME_SAMPLES + DCA_LBR_TIME_HISTORY * 2;
971
    int nsamples = nchsamples * s->nchannels * s->nsubbands;
972
    int ch, sb;
973
    float *ptr;
974
975
    // Reallocate time sample buffer
976
    av_fast_mallocz(&s->ts_buffer, &s->ts_size, nsamples * sizeof(float));
977
    if (!s->ts_buffer)
978
        return -1;
979
980
    ptr = s->ts_buffer + DCA_LBR_TIME_HISTORY;
981
    for (ch = 0; ch < s->nchannels; ch++) {
982
        for (sb = 0; sb < s->nsubbands; sb++) {
983
            s->time_samples[ch][sb] = ptr;
984
            ptr += nchsamples;
985
        }
986
    }
987
988
    return 0;
989
}
990
991
static int parse_decoder_init(DCALbrDecoder *s, GetByteContext *gb)
992
{
993
    int old_rate = s->sample_rate;
994
    int old_band_limit = s->band_limit;
995
    int old_nchannels = s->nchannels;
996
    int version, bit_rate_hi;
997
    unsigned int sr_code;
998
999
    // Sample rate of LBR audio
1000
    sr_code = bytestream2_get_byte(gb);
1001
    if (sr_code >= FF_ARRAY_ELEMS(ff_dca_sampling_freqs)) {
1002
        av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR sample rate\n");
1003
        return AVERROR_INVALIDDATA;
1004
    }
1005
    s->sample_rate = ff_dca_sampling_freqs[sr_code];
1006
    if (s->sample_rate > 48000) {
1007
        avpriv_report_missing_feature(s->avctx, "%d Hz LBR sample rate", s->sample_rate);
1008
        return AVERROR_PATCHWELCOME;
1009
    }
1010
1011
    // LBR speaker mask
1012
    s->ch_mask = bytestream2_get_le16(gb);
1013
    if (!(s->ch_mask & 0x7)) {
1014
        avpriv_report_missing_feature(s->avctx, "LBR channel mask %#x", s->ch_mask);
1015
        return AVERROR_PATCHWELCOME;
1016
    }
1017
    if ((s->ch_mask & 0xfff0) && !(s->warned & 1)) {
1018
        avpriv_report_missing_feature(s->avctx, "LBR channel mask %#x", s->ch_mask);
1019
        s->warned |= 1;
1020
    }
1021
1022
    // LBR bitstream version
1023
    version = bytestream2_get_le16(gb);
1024
    if ((version & 0xff00) != 0x0800) {
1025
        avpriv_report_missing_feature(s->avctx, "LBR stream version %#x", version);
1026
        return AVERROR_PATCHWELCOME;
1027
    }
1028
1029
    // Flags for LBR decoder initialization
1030
    s->flags = bytestream2_get_byte(gb);
1031
    if (s->flags & LBR_FLAG_DMIX_MULTI_CH) {
1032
        avpriv_report_missing_feature(s->avctx, "LBR multi-channel downmix");
1033
        return AVERROR_PATCHWELCOME;
1034
    }
1035
    if ((s->flags & LBR_FLAG_LFE_PRESENT) && s->sample_rate != 48000) {
1036
        if (!(s->warned & 2)) {
1037
            avpriv_report_missing_feature(s->avctx, "%d Hz LFE interpolation", s->sample_rate);
1038
            s->warned |= 2;
1039
        }
1040
        s->flags &= ~LBR_FLAG_LFE_PRESENT;
1041
    }
1042
1043
    // Most significant bit rate nibbles
1044
    bit_rate_hi = bytestream2_get_byte(gb);
1045
1046
    // Least significant original bit rate word
1047
    s->bit_rate_orig = bytestream2_get_le16(gb) | ((bit_rate_hi & 0x0F) << 16);
1048
1049
    // Least significant scaled bit rate word
1050
    s->bit_rate_scaled = bytestream2_get_le16(gb) | ((bit_rate_hi & 0xF0) << 12);
1051
1052
    // Setup number of fullband channels
1053
    s->nchannels_total = ff_dca_count_chs_for_mask(s->ch_mask & ~DCA_SPEAKER_PAIR_LFE1);
1054
    s->nchannels = FFMIN(s->nchannels_total, DCA_LBR_CHANNELS);
1055
1056
    // Setup band limit
1057
    switch (s->flags & LBR_FLAG_BAND_LIMIT_MASK) {
1058
    case LBR_FLAG_BAND_LIMIT_NONE:
1059
        s->band_limit = 0;
1060
        break;
1061
    case LBR_FLAG_BAND_LIMIT_1_2:
1062
        s->band_limit = 1;
1063
        break;
1064
    case LBR_FLAG_BAND_LIMIT_1_4:
1065
        s->band_limit = 2;
1066
        break;
1067
    default:
1068
        avpriv_report_missing_feature(s->avctx, "LBR band limit %#x", s->flags & LBR_FLAG_BAND_LIMIT_MASK);
1069
        return AVERROR_PATCHWELCOME;
1070
    }
1071
1072
    // Setup frequency range
1073
    s->freq_range = ff_dca_freq_ranges[sr_code];
1074
1075
    // Setup resolution profile
1076
    if (s->bit_rate_orig >= 44000 * (s->nchannels_total + 2))
1077
        s->res_profile = 2;
1078
    else if (s->bit_rate_orig >= 25000 * (s->nchannels_total + 2))
1079
        s->res_profile = 1;
1080
    else
1081
        s->res_profile = 0;
1082
1083
    // Setup limited sample rate, number of subbands, etc
1084
    s->limited_rate = s->sample_rate >> s->band_limit;
1085
    s->limited_range = s->freq_range - s->band_limit;
1086
    if (s->limited_range < 0) {
1087
        av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR band limit for frequency range\n");
1088
        return AVERROR_INVALIDDATA;
1089
    }
1090
1091
    s->nsubbands = 8 << s->limited_range;
1092
1093
    s->g3_avg_only_start_sb = s->nsubbands * ff_dca_avg_g3_freqs[s->res_profile] / (s->limited_rate / 2);
1094
    if (s->g3_avg_only_start_sb > s->nsubbands)
1095
        s->g3_avg_only_start_sb = s->nsubbands;
1096
1097
    s->min_mono_subband = s->nsubbands *  2000 / (s->limited_rate / 2);
1098
    if (s->min_mono_subband > s->nsubbands)
1099
        s->min_mono_subband = s->nsubbands;
1100
1101
    s->max_mono_subband = s->nsubbands * 14000 / (s->limited_rate / 2);
1102
    if (s->max_mono_subband > s->nsubbands)
1103
        s->max_mono_subband = s->nsubbands;
1104
1105
    // Handle change of sample rate
1106
    if ((old_rate != s->sample_rate || old_band_limit != s->band_limit) && init_sample_rate(s) < 0)
1107
        return AVERROR(ENOMEM);
1108
1109
    // Setup stereo downmix
1110
    if (s->flags & LBR_FLAG_DMIX_STEREO) {
1111
        DCAContext *dca = s->avctx->priv_data;
1112
1113
        if (s->nchannels_total < 3 || s->nchannels_total > DCA_LBR_CHANNELS_TOTAL - 2) {
1114
            av_log(s->avctx, AV_LOG_ERROR, "Invalid number of channels for LBR stereo downmix\n");
1115
            return AVERROR_INVALIDDATA;
1116
        }
1117
1118
        // This decoder doesn't support ECS chunk
1119
        if (dca->request_channel_layout != DCA_SPEAKER_LAYOUT_STEREO && !(s->warned & 4)) {
1120
            avpriv_report_missing_feature(s->avctx, "Embedded LBR stereo downmix");
1121
            s->warned |= 4;
1122
        }
1123
1124
        // Account for extra downmixed channel pair
1125
        s->nchannels_total += 2;
1126
        s->nchannels = 2;
1127
        s->ch_mask = DCA_SPEAKER_PAIR_LR;
1128
        s->flags &= ~LBR_FLAG_LFE_PRESENT;
1129
    }
1130
1131
    // Handle change of sample rate or number of channels
1132
    if (old_rate != s->sample_rate
1133
        || old_band_limit != s->band_limit
1134
        || old_nchannels != s->nchannels) {
1135
        if (alloc_sample_buffer(s) < 0)
1136
            return AVERROR(ENOMEM);
1137
        ff_dca_lbr_flush(s);
1138
    }
1139
1140
    return 0;
1141
}
1142
1143
int ff_dca_lbr_parse(DCALbrDecoder *s, uint8_t *data, DCAExssAsset *asset)
1144
{
1145
    struct {
1146
        LBRChunk    lfe;
1147
        LBRChunk    tonal;
1148
        LBRChunk    tonal_grp[5];
1149
        LBRChunk    grid1[DCA_LBR_CHANNELS / 2];
1150
        LBRChunk    hr_grid[DCA_LBR_CHANNELS / 2];
1151
        LBRChunk    ts1[DCA_LBR_CHANNELS / 2];
1152
        LBRChunk    ts2[DCA_LBR_CHANNELS / 2];
1153
    } chunk = { {0} };
1154
1155
    GetByteContext gb;
1156
1157
    int i, ch, sb, sf, ret, group, chunk_id, chunk_len;
1158
1159
    bytestream2_init(&gb, data + asset->lbr_offset, asset->lbr_size);
1160
1161
    // LBR sync word
1162
    if (bytestream2_get_be32(&gb) != DCA_SYNCWORD_LBR) {
1163
        av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR sync word\n");
1164
        return AVERROR_INVALIDDATA;
1165
    }
1166
1167
    // LBR header type
1168
    switch (bytestream2_get_byte(&gb)) {
1169
    case DCA_LBR_HEADER_SYNC_ONLY:
1170
        if (!s->sample_rate) {
1171
            av_log(s->avctx, AV_LOG_ERROR, "LBR decoder not initialized\n");
1172
            return AVERROR_INVALIDDATA;
1173
        }
1174
        break;
1175
    case DCA_LBR_HEADER_DECODER_INIT:
1176
        if ((ret = parse_decoder_init(s, &gb)) < 0) {
1177
            s->sample_rate = 0;
1178
            return ret;
1179
        }
1180
        break;
1181
    default:
1182
        av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR header type\n");
1183
        return AVERROR_INVALIDDATA;
1184
    }
1185
1186
    // LBR frame chunk header
1187
    chunk_id = bytestream2_get_byte(&gb);
1188
    chunk_len = (chunk_id & 0x80) ? bytestream2_get_be16(&gb) : bytestream2_get_byte(&gb);
1189
1190
    if (chunk_len > bytestream2_get_bytes_left(&gb)) {
1191
        chunk_len = bytestream2_get_bytes_left(&gb);
1192
        av_log(s->avctx, AV_LOG_WARNING, "LBR frame chunk was truncated\n");
1193
        if (s->avctx->err_recognition & AV_EF_EXPLODE)
1194
            return AVERROR_INVALIDDATA;
1195
    }
1196
1197
    bytestream2_init(&gb, gb.buffer, chunk_len);
1198
1199
    switch (chunk_id & 0x7f) {
1200
    case LBR_CHUNK_FRAME:
1201
        if (s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL)) {
1202
            int checksum = bytestream2_get_be16(&gb);
1203
            uint16_t res = chunk_id;
1204
            res += (chunk_len >> 8) & 0xff;
1205
            res += chunk_len & 0xff;
1206
            for (i = 0; i < chunk_len - 2; i++)
1207
                res += gb.buffer[i];
1208
            if (checksum != res) {
1209
                av_log(s->avctx, AV_LOG_WARNING, "Invalid LBR checksum\n");
1210
                if (s->avctx->err_recognition & AV_EF_EXPLODE)
1211
                    return AVERROR_INVALIDDATA;
1212
            }
1213
        } else {
1214
            bytestream2_skip(&gb, 2);
1215
        }
1216
        break;
1217
    case LBR_CHUNK_FRAME_NO_CSUM:
1218
        break;
1219
    default:
1220
        av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR frame chunk ID\n");
1221
        return AVERROR_INVALIDDATA;
1222
    }
1223
1224
    // Clear current frame
1225
    memset(s->quant_levels, 0, sizeof(s->quant_levels));
1226
    memset(s->sb_indices, 0xff, sizeof(s->sb_indices));
1227
    memset(s->sec_ch_sbms, 0, sizeof(s->sec_ch_sbms));
1228
    memset(s->sec_ch_lrms, 0, sizeof(s->sec_ch_lrms));
1229
    memset(s->ch_pres, 0, sizeof(s->ch_pres));
1230
    memset(s->grid_1_scf, 0, sizeof(s->grid_1_scf));
1231
    memset(s->grid_2_scf, 0, sizeof(s->grid_2_scf));
1232
    memset(s->grid_3_avg, 0, sizeof(s->grid_3_avg));
1233
    memset(s->grid_3_scf, 0, sizeof(s->grid_3_scf));
1234
    memset(s->grid_3_pres, 0, sizeof(s->grid_3_pres));
1235
    memset(s->tonal_scf, 0, sizeof(s->tonal_scf));
1236
    memset(s->lfe_data, 0, sizeof(s->lfe_data));
1237
    s->part_stereo_pres = 0;
1238
    s->framenum = (s->framenum + 1) & 31;
1239
1240
    for (ch = 0; ch < s->nchannels; ch++) {
1241
        for (sb = 0; sb < s->nsubbands / 4; sb++) {
1242
            s->part_stereo[ch][sb][0] = s->part_stereo[ch][sb][4];
1243
            s->part_stereo[ch][sb][4] = 16;
1244
        }
1245
    }
1246
1247
    memset(s->lpc_coeff[s->framenum & 1], 0, sizeof(s->lpc_coeff[0]));
1248
1249
    for (group = 0; group < 5; group++) {
1250
        for (sf = 0; sf < 1 << group; sf++) {
1251
            int sf_idx = ((s->framenum << group) + sf) & 31;
1252
            s->tonal_bounds[group][sf_idx][0] =
1253
            s->tonal_bounds[group][sf_idx][1] = s->ntones;
1254
        }
1255
    }
1256
1257
    // Parse chunk headers
1258
    while (bytestream2_get_bytes_left(&gb) > 0) {
1259
        chunk_id = bytestream2_get_byte(&gb);
1260
        chunk_len = (chunk_id & 0x80) ? bytestream2_get_be16(&gb) : bytestream2_get_byte(&gb);
1261
        chunk_id &= 0x7f;
1262
1263
        if (chunk_len > bytestream2_get_bytes_left(&gb)) {
1264
            chunk_len = bytestream2_get_bytes_left(&gb);
1265
            av_log(s->avctx, AV_LOG_WARNING, "LBR chunk %#x was truncated\n", chunk_id);
1266
            if (s->avctx->err_recognition & AV_EF_EXPLODE)
1267
                return AVERROR_INVALIDDATA;
1268
        }
1269
1270
        switch (chunk_id) {
1271
        case LBR_CHUNK_LFE:
1272
            chunk.lfe.len  = chunk_len;
1273
            chunk.lfe.data = gb.buffer;
1274
            break;
1275
1276
        case LBR_CHUNK_SCF:
1277
        case LBR_CHUNK_TONAL:
1278
        case LBR_CHUNK_TONAL_SCF:
1279
            chunk.tonal.id   = chunk_id;
1280
            chunk.tonal.len  = chunk_len;
1281
            chunk.tonal.data = gb.buffer;
1282
            break;
1283
1284
        case LBR_CHUNK_TONAL_GRP_1:
1285
        case LBR_CHUNK_TONAL_GRP_2:
1286
        case LBR_CHUNK_TONAL_GRP_3:
1287
        case LBR_CHUNK_TONAL_GRP_4:
1288
        case LBR_CHUNK_TONAL_GRP_5:
1289
            i = LBR_CHUNK_TONAL_GRP_5 - chunk_id;
1290
            chunk.tonal_grp[i].id   = i;
1291
            chunk.tonal_grp[i].len  = chunk_len;
1292
            chunk.tonal_grp[i].data = gb.buffer;
1293
            break;
1294
1295
        case LBR_CHUNK_TONAL_SCF_GRP_1:
1296
        case LBR_CHUNK_TONAL_SCF_GRP_2:
1297
        case LBR_CHUNK_TONAL_SCF_GRP_3:
1298
        case LBR_CHUNK_TONAL_SCF_GRP_4:
1299
        case LBR_CHUNK_TONAL_SCF_GRP_5:
1300
            i = LBR_CHUNK_TONAL_SCF_GRP_5 - chunk_id;
1301
            chunk.tonal_grp[i].id   = i;
1302
            chunk.tonal_grp[i].len  = chunk_len;
1303
            chunk.tonal_grp[i].data = gb.buffer;
1304
            break;
1305
1306
        case LBR_CHUNK_RES_GRID_LR:
1307
        case LBR_CHUNK_RES_GRID_LR + 1:
1308
        case LBR_CHUNK_RES_GRID_LR + 2:
1309
            i = chunk_id - LBR_CHUNK_RES_GRID_LR;
1310
            chunk.grid1[i].len  = chunk_len;
1311
            chunk.grid1[i].data = gb.buffer;
1312
            break;
1313
1314
        case LBR_CHUNK_RES_GRID_HR:
1315
        case LBR_CHUNK_RES_GRID_HR + 1:
1316
        case LBR_CHUNK_RES_GRID_HR + 2:
1317
            i = chunk_id - LBR_CHUNK_RES_GRID_HR;
1318
            chunk.hr_grid[i].len  = chunk_len;
1319
            chunk.hr_grid[i].data = gb.buffer;
1320
            break;
1321
1322
        case LBR_CHUNK_RES_TS_1:
1323
        case LBR_CHUNK_RES_TS_1 + 1:
1324
        case LBR_CHUNK_RES_TS_1 + 2:
1325
            i = chunk_id - LBR_CHUNK_RES_TS_1;
1326
            chunk.ts1[i].len  = chunk_len;
1327
            chunk.ts1[i].data = gb.buffer;
1328
            break;
1329
1330
        case LBR_CHUNK_RES_TS_2:
1331
        case LBR_CHUNK_RES_TS_2 + 1:
1332
        case LBR_CHUNK_RES_TS_2 + 2:
1333
            i = chunk_id - LBR_CHUNK_RES_TS_2;
1334
            chunk.ts2[i].len  = chunk_len;
1335
            chunk.ts2[i].data = gb.buffer;
1336
            break;
1337
        }
1338
1339
        bytestream2_skip(&gb, chunk_len);
1340
    }
1341
1342
    // Parse the chunks
1343
    ret = parse_lfe_chunk(s, &chunk.lfe);
1344
1345
    ret |= parse_tonal_chunk(s, &chunk.tonal);
1346
1347
    for (i = 0; i < 5; i++)
1348
        ret |= parse_tonal_group(s, &chunk.tonal_grp[i]);
1349
1350
    for (i = 0; i < (s->nchannels + 1) / 2; i++) {
1351
        int ch1 = i * 2;
1352
        int ch2 = FFMIN(ch1 + 1, s->nchannels - 1);
1353
1354
        if (parse_grid_1_chunk (s, &chunk.grid1  [i], ch1, ch2) < 0 ||
1355
            parse_high_res_grid(s, &chunk.hr_grid[i], ch1, ch2) < 0) {
1356
            ret = -1;
1357
            continue;
1358
        }
1359
1360
        // TS chunks depend on both grids. TS_2 depends on TS_1.
1361
        if (!chunk.grid1[i].len || !chunk.hr_grid[i].len || !chunk.ts1[i].len)
1362
            continue;
1363
1364
        if (parse_ts1_chunk(s, &chunk.ts1[i], ch1, ch2) < 0 ||
1365
            parse_ts2_chunk(s, &chunk.ts2[i], ch1, ch2) < 0) {
1366
            ret = -1;
1367
            continue;
1368
        }
1369
    }
1370
1371
    if (ret < 0 && (s->avctx->err_recognition & AV_EF_EXPLODE))
1372
        return AVERROR_INVALIDDATA;
1373
1374
    return 0;
1375
}
1376
1377
/**
1378
 * Reconstruct high-frequency resolution grid from first and third grids
1379
 */
1380
static void decode_grid(DCALbrDecoder *s, int ch1, int ch2)
1381
{
1382
    int i, ch, sb;
1383
1384
    for (ch = ch1; ch <= ch2; ch++) {
1385
        for (sb = 0; sb < s->nsubbands; sb++) {
1386
            int g1_sb = ff_dca_scf_to_grid_1[sb];
1387
1388
            uint8_t *g1_scf_a = s->grid_1_scf[ch][g1_sb    ];
1389
            uint8_t *g1_scf_b = s->grid_1_scf[ch][g1_sb + 1];
1390
1391
            int w1 = ff_dca_grid_1_weights[g1_sb    ][sb];
1392
            int w2 = ff_dca_grid_1_weights[g1_sb + 1][sb];
1393
1394
            uint8_t *hr_scf = s->high_res_scf[ch][sb];
1395
1396
            if (sb < 4) {
1397
                for (i = 0; i < 8; i++) {
1398
                    int scf = w1 * g1_scf_a[i] + w2 * g1_scf_b[i];
1399
                    hr_scf[i] = scf >> 7;
1400
                }
1401
            } else {
1402
                int8_t *g3_scf = s->grid_3_scf[ch][sb - 4];
1403
                int g3_avg = s->grid_3_avg[ch][sb - 4];
1404
1405
                for (i = 0; i < 8; i++) {
1406
                    int scf = w1 * g1_scf_a[i] + w2 * g1_scf_b[i];
1407
                    hr_scf[i] = (scf >> 7) - g3_avg - g3_scf[i];
1408
                }
1409
            }
1410
        }
1411
    }
1412
}
1413
1414
/**
1415
 * Fill unallocated subbands with randomness
1416
 */
1417
static void random_ts(DCALbrDecoder *s, int ch1, int ch2)
1418
{
1419
    int i, j, k, ch, sb;
1420
1421
    for (ch = ch1; ch <= ch2; ch++) {
1422
        for (sb = 0; sb < s->nsubbands; sb++) {
1423
            float *samples = s->time_samples[ch][sb];
1424
1425
            if (s->ch_pres[ch] & (1U << sb))
1426
                continue;   // Skip allocated subband
1427
1428
            if (sb < 2) {
1429
                // The first two subbands are always zero
1430
                memset(samples, 0, DCA_LBR_TIME_SAMPLES * sizeof(float));
1431
            } else if (sb < 10) {
1432
                for (i = 0; i < DCA_LBR_TIME_SAMPLES; i++)
1433
                    samples[i] = lbr_rand(s, sb);
1434
            } else {
1435
                for (i = 0; i < DCA_LBR_TIME_SAMPLES / 8; i++, samples += 8) {
1436
                    float accum[8] = { 0 };
1437
1438
                    // Modulate by subbands 2-5 in blocks of 8
1439
                    for (k = 2; k < 6; k++) {
1440
                        float *other = &s->time_samples[ch][k][i * 8];
1441
                        for (j = 0; j < 8; j++)
1442
                            accum[j] += fabs(other[j]);
1443
                    }
1444
1445
                    for (j = 0; j < 8; j++)
1446
                        samples[j] = (accum[j] * 0.25f + 0.5f) * lbr_rand(s, sb);
1447
                }
1448
            }
1449
        }
1450
    }
1451
}
1452
1453
static void predict(float *samples, const float *coeff, int nsamples)
1454
{
1455
    int i, j;
1456
1457
    for (i = 0; i < nsamples; i++) {
1458
        float res = 0;
1459
        for (j = 0; j < 8; j++)
1460
            res += coeff[j] * samples[i - j - 1];
1461
        samples[i] -= res;
1462
    }
1463
}
1464
1465
static void synth_lpc(DCALbrDecoder *s, int ch1, int ch2, int sb)
1466
{
1467
    int f = s->framenum & 1;
1468
    int ch;
1469
1470
    for (ch = ch1; ch <= ch2; ch++) {
1471
        float *samples = s->time_samples[ch][sb];
1472
1473
        if (!(s->ch_pres[ch] & (1U << sb)))
1474
            continue;
1475
1476
        if (sb < 2) {
1477
            predict(samples,      s->lpc_coeff[f^1][ch][sb][1],  16);
1478
            predict(samples + 16, s->lpc_coeff[f  ][ch][sb][0],  64);
1479
            predict(samples + 80, s->lpc_coeff[f  ][ch][sb][1],  48);
1480
        } else {
1481
            predict(samples,      s->lpc_coeff[f^1][ch][sb][0],  16);
1482
            predict(samples + 16, s->lpc_coeff[f  ][ch][sb][0], 112);
1483
        }
1484
    }
1485
}
1486
1487
static void filter_ts(DCALbrDecoder *s, int ch1, int ch2)
1488
{
1489
    int i, j, sb, ch;
1490
1491
    for (sb = 0; sb < s->nsubbands; sb++) {
1492
        // Scale factors
1493
        for (ch = ch1; ch <= ch2; ch++) {
1494
            float *samples = s->time_samples[ch][sb];
1495
            uint8_t *hr_scf = s->high_res_scf[ch][sb];
1496
            if (sb < 4) {
1497
                for (i = 0; i < DCA_LBR_TIME_SAMPLES / 16; i++, samples += 16) {
1498
                    unsigned int scf = hr_scf[i];
1499
                    if (scf > AMP_MAX)
1500
                        scf = AMP_MAX;
1501
                    for (j = 0; j < 16; j++)
1502
                        samples[j] *= ff_dca_quant_amp[scf];
1503
                }
1504
            } else {
1505
                uint8_t *g2_scf = s->grid_2_scf[ch][ff_dca_scf_to_grid_2[sb]];
1506
                for (i = 0; i < DCA_LBR_TIME_SAMPLES / 2; i++, samples += 2) {
1507
                    unsigned int scf = hr_scf[i / 8] - g2_scf[i];
1508
                    if (scf > AMP_MAX)
1509
                        scf = AMP_MAX;
1510
                    samples[0] *= ff_dca_quant_amp[scf];
1511
                    samples[1] *= ff_dca_quant_amp[scf];
1512
                }
1513
            }
1514
        }
1515
1516
        // Mid-side stereo
1517
        if (ch1 != ch2) {
1518
            float *samples_l = s->time_samples[ch1][sb];
1519
            float *samples_r = s->time_samples[ch2][sb];
1520
            int ch2_pres = s->ch_pres[ch2] & (1U << sb);
1521
1522
            for (i = 0; i < DCA_LBR_TIME_SAMPLES / 16; i++) {
1523
                int sbms = (s->sec_ch_sbms[ch1 / 2][sb] >> i) & 1;
1524
                int lrms = (s->sec_ch_lrms[ch1 / 2][sb] >> i) & 1;
1525
1526
                if (sb >= s->min_mono_subband) {
1527
                    if (lrms && ch2_pres) {
1528
                        if (sbms) {
1529
                            for (j = 0; j < 16; j++) {
1530
                                float tmp = samples_l[j];
1531
                                samples_l[j] =  samples_r[j];
1532
                                samples_r[j] = -tmp;
1533
                            }
1534
                        } else {
1535
                            for (j = 0; j < 16; j++) {
1536
                                float tmp = samples_l[j];
1537
                                samples_l[j] =  samples_r[j];
1538
                                samples_r[j] =  tmp;
1539
                            }
1540
                        }
1541
                    } else if (!ch2_pres) {
1542
                        if (sbms && (s->part_stereo_pres & (1 << ch1))) {
1543
                            for (j = 0; j < 16; j++)
1544
                                samples_r[j] = -samples_l[j];
1545
                        } else {
1546
                            for (j = 0; j < 16; j++)
1547
                                samples_r[j] =  samples_l[j];
1548
                        }
1549
                    }
1550
                } else if (sbms && ch2_pres) {
1551
                    for (j = 0; j < 16; j++) {
1552
                        float tmp = samples_l[j];
1553
                        samples_l[j] = (tmp + samples_r[j]) * 0.5f;
1554
                        samples_r[j] = (tmp - samples_r[j]) * 0.5f;
1555
                    }
1556
                }
1557
1558
                samples_l += 16;
1559
                samples_r += 16;
1560
            }
1561
        }
1562
1563
        // Inverse prediction
1564
        if (sb < 3)
1565
            synth_lpc(s, ch1, ch2, sb);
1566
    }
1567
}
1568
1569
/**
1570
 * Modulate by interpolated partial stereo coefficients
1571
 */
1572
static void decode_part_stereo(DCALbrDecoder *s, int ch1, int ch2)
1573
{
1574
    int i, ch, sb, sf;
1575
1576
    for (ch = ch1; ch <= ch2; ch++) {
1577
        for (sb = s->min_mono_subband; sb < s->nsubbands; sb++) {
1578
            uint8_t *pt_st = s->part_stereo[ch][(sb - s->min_mono_subband) / 4];
1579
            float *samples = s->time_samples[ch][sb];
1580
1581
            if (s->ch_pres[ch2] & (1U << sb))
1582
                continue;
1583
1584
            for (sf = 1; sf <= 4; sf++, samples += 32) {
1585
                float prev = ff_dca_st_coeff[pt_st[sf - 1]];
1586
                float next = ff_dca_st_coeff[pt_st[sf    ]];
1587
1588
                for (i = 0; i < 32; i++)
1589
                    samples[i] *= (32 - i) * prev + i * next;
1590
            }
1591
        }
1592
    }
1593
}
1594
1595
/**
1596
 * Synthesise tones in the given group for the given tonal subframe
1597
 */
1598
static void synth_tones(DCALbrDecoder *s, int ch, float *values,
1599
                        int group, int group_sf, int synth_idx)
1600
{
1601
    int i, start, count;
1602
1603
    if (synth_idx < 0)
1604
        return;
1605
1606
    start =  s->tonal_bounds[group][group_sf][0];
1607
    count = (s->tonal_bounds[group][group_sf][1] - start) & (DCA_LBR_TONES - 1);
1608
1609
    for (i = 0; i < count; i++) {
1610
        DCALbrTone *t = &s->tones[(start + i) & (DCA_LBR_TONES - 1)];
1611
1612
        if (t->amp[ch]) {
1613
            float amp = ff_dca_synth_env[synth_idx] * ff_dca_quant_amp[t->amp[ch]];
1614
            float c = amp * cos_tab[(t->phs[ch]     ) & 255];
1615
            float s = amp * cos_tab[(t->phs[ch] + 64) & 255];
1616
            const float *cf = ff_dca_corr_cf[t->f_delt];
1617
            int x_freq = t->x_freq;
1618
1619
            switch (x_freq) {
1620
            case 0:
1621
                goto p0;
1622
            case 1:
1623
                values[3] += cf[0] * -s;
1624
                values[2] += cf[1] *  c;
1625
                values[1] += cf[2] *  s;
1626
                values[0] += cf[3] * -c;
1627
                goto p1;
1628
            case 2:
1629
                values[2] += cf[0] * -s;
1630
                values[1] += cf[1] *  c;
1631
                values[0] += cf[2] *  s;
1632
                goto p2;
1633
            case 3:
1634
                values[1] += cf[0] * -s;
1635
                values[0] += cf[1] *  c;
1636
                goto p3;
1637
            case 4:
1638
                values[0] += cf[0] * -s;
1639
                goto p4;
1640
            }
1641
1642
            values[x_freq - 5] += cf[ 0] * -s;
1643
        p4: values[x_freq - 4] += cf[ 1] *  c;
1644
        p3: values[x_freq - 3] += cf[ 2] *  s;
1645
        p2: values[x_freq - 2] += cf[ 3] * -c;
1646
        p1: values[x_freq - 1] += cf[ 4] * -s;
1647
        p0: values[x_freq    ] += cf[ 5] *  c;
1648
            values[x_freq + 1] += cf[ 6] *  s;
1649
            values[x_freq + 2] += cf[ 7] * -c;
1650
            values[x_freq + 3] += cf[ 8] * -s;
1651
            values[x_freq + 4] += cf[ 9] *  c;
1652
            values[x_freq + 5] += cf[10] *  s;
1653
        }
1654
1655
        t->phs[ch] += t->ph_rot;
1656
    }
1657
}
1658
1659
/**
1660
 * Synthesise all tones in all groups for the given residual subframe
1661
 */
1662
static void base_func_synth(DCALbrDecoder *s, int ch, float *values, int sf)
1663
{
1664
    int group;
1665
1666
    // Tonal vs residual shift is 22 subframes
1667
    for (group = 0; group < 5; group++) {
1668
        int group_sf = (s->framenum << group) + ((sf - 22) >> (5 - group));
1669
        int synth_idx = ((((sf - 22) & 31) << group) & 31) + (1 << group) - 1;
1670
1671
        synth_tones(s, ch, values, group, (group_sf - 1) & 31, 30 - synth_idx);
1672
        synth_tones(s, ch, values, group, (group_sf    ) & 31,      synth_idx);
1673
    }
1674
}
1675
1676
static void transform_channel(DCALbrDecoder *s, int ch, float *output)
1677
{
1678
    LOCAL_ALIGNED_32(float, values, [DCA_LBR_SUBBANDS    ], [4]);
1679
    LOCAL_ALIGNED_32(float, result, [DCA_LBR_SUBBANDS * 2], [4]);
1680
    int sf, sb, nsubbands = s->nsubbands, noutsubbands = 8 << s->freq_range;
1681
1682
    // Clear inactive subbands
1683
    if (nsubbands < noutsubbands)
1684
        memset(values[nsubbands], 0, (noutsubbands - nsubbands) * sizeof(values[0]));
1685
1686
    for (sf = 0; sf < DCA_LBR_TIME_SAMPLES / 4; sf++) {
1687
        // Hybrid filterbank
1688
        s->dcadsp->lbr_bank(values, s->time_samples[ch],
1689
                            ff_dca_bank_coeff, sf * 4, nsubbands);
1690
1691
        base_func_synth(s, ch, values[0], sf);
1692
1693
        s->imdct.imdct_calc(&s->imdct, result[0], values[0]);
1694
1695
        // Long window and overlap-add
1696
        s->fdsp->vector_fmul_add(output, result[0], s->window,
1697
                                 s->history[ch], noutsubbands * 4);
1698
        s->fdsp->vector_fmul_reverse(s->history[ch], result[noutsubbands],
1699
                                     s->window, noutsubbands * 4);
1700
        output += noutsubbands * 4;
1701
    }
1702
1703
    // Update history for LPC and forward MDCT
1704
    for (sb = 0; sb < nsubbands; sb++) {
1705
        float *samples = s->time_samples[ch][sb] - DCA_LBR_TIME_HISTORY;
1706
        memcpy(samples, samples + DCA_LBR_TIME_SAMPLES, DCA_LBR_TIME_HISTORY * sizeof(float));
1707
    }
1708
}
1709
1710
int ff_dca_lbr_filter_frame(DCALbrDecoder *s, AVFrame *frame)
1711
{
1712
    AVCodecContext *avctx = s->avctx;
1713
    int i, ret, nchannels, ch_conf = (s->ch_mask & 0x7) - 1;
1714
    const int8_t *reorder;
1715
1716
    avctx->channel_layout = channel_layouts[ch_conf];
1717
    avctx->channels = nchannels = channel_counts[ch_conf];
1718
    avctx->sample_rate = s->sample_rate;
1719
    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1720
    avctx->bits_per_raw_sample = 0;
1721
    avctx->profile = FF_PROFILE_DTS_EXPRESS;
1722
    avctx->bit_rate = s->bit_rate_scaled;
1723
1724
    if (s->flags & LBR_FLAG_LFE_PRESENT) {
1725
        avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1726
        avctx->channels++;
1727
        reorder = channel_reorder_lfe[ch_conf];
1728
    } else {
1729
        reorder = channel_reorder_nolfe[ch_conf];
1730
    }
1731
1732
    frame->nb_samples = 1024 << s->freq_range;
1733
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1734
        return ret;
1735
1736
    // Filter fullband channels
1737
    for (i = 0; i < (s->nchannels + 1) / 2; i++) {
1738
        int ch1 = i * 2;
1739
        int ch2 = FFMIN(ch1 + 1, s->nchannels - 1);
1740
1741
        decode_grid(s, ch1, ch2);
1742
1743
        random_ts(s, ch1, ch2);
1744
1745
        filter_ts(s, ch1, ch2);
1746
1747
        if (ch1 != ch2 && (s->part_stereo_pres & (1 << ch1)))
1748
            decode_part_stereo(s, ch1, ch2);
1749
1750
        if (ch1 < nchannels)
1751
            transform_channel(s, ch1, (float *)frame->extended_data[reorder[ch1]]);
1752
1753
        if (ch1 != ch2 && ch2 < nchannels)
1754
            transform_channel(s, ch2, (float *)frame->extended_data[reorder[ch2]]);
1755
    }
1756
1757
    // Interpolate LFE channel
1758
    if (s->flags & LBR_FLAG_LFE_PRESENT) {
1759
        s->dcadsp->lfe_iir((float *)frame->extended_data[lfe_index[ch_conf]],
1760
                           s->lfe_data, ff_dca_lfe_iir,
1761
                           s->lfe_history, 16 << s->freq_range);
1762
    }
1763
1764
    if ((ret = ff_side_data_update_matrix_encoding(frame, AV_MATRIX_ENCODING_NONE)) < 0)
1765
        return ret;
1766
1767
    return 0;
1768
}
1769
1770
av_cold void ff_dca_lbr_flush(DCALbrDecoder *s)
1771
{
1772
    int ch, sb;
1773
1774
    if (!s->sample_rate)
1775
        return;
1776
1777
    // Clear history
1778
    memset(s->part_stereo, 16, sizeof(s->part_stereo));
1779
    memset(s->lpc_coeff, 0, sizeof(s->lpc_coeff));
1780
    memset(s->history, 0, sizeof(s->history));
1781
    memset(s->tonal_bounds, 0, sizeof(s->tonal_bounds));
1782
    memset(s->lfe_history, 0, sizeof(s->lfe_history));
1783
    s->framenum = 0;
1784
    s->ntones = 0;
1785
1786
    for (ch = 0; ch < s->nchannels; ch++) {
1787
        for (sb = 0; sb < s->nsubbands; sb++) {
1788
            float *samples = s->time_samples[ch][sb] - DCA_LBR_TIME_HISTORY;
1789
            memset(samples, 0, DCA_LBR_TIME_HISTORY * sizeof(float));
1790
        }
1791
    }
1792
}
1793
1794
92
av_cold int ff_dca_lbr_init(DCALbrDecoder *s)
1795
{
1796
92
    init_tables();
1797
1798
92
    if (!(s->fdsp = avpriv_float_dsp_alloc(0)))
1799
        return -1;
1800
1801
92
    s->lbr_rand = 1;
1802
92
    return 0;
1803
}
1804
1805
92
av_cold void ff_dca_lbr_close(DCALbrDecoder *s)
1806
{
1807
92
    s->sample_rate = 0;
1808
1809
92
    av_freep(&s->ts_buffer);
1810
92
    s->ts_size = 0;
1811
1812
92
    av_freep(&s->fdsp);
1813
92
    ff_mdct_end(&s->imdct);
1814
92
}