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