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