2 * Copyright (C) 2016 foo86
4 * This file is part of FFmpeg.
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.
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.
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
21 #define BITSTREAM_READER_LE
23 #include "libavutil/channel_layout.h"
28 #include "dca_syncwords.h"
29 #include "bytestream.h"
34 LBR_HEADER_SYNC_ONLY = 1,
35 LBR_HEADER_DECODER_INIT = 2
39 LBR_FLAG_24_BIT = 0x01,
40 LBR_FLAG_LFE_PRESENT = 0x02,
41 LBR_FLAG_BAND_LIMIT_2_3 = 0x04,
42 LBR_FLAG_BAND_LIMIT_1_2 = 0x08,
43 LBR_FLAG_BAND_LIMIT_1_3 = 0x0c,
44 LBR_FLAG_BAND_LIMIT_1_4 = 0x10,
45 LBR_FLAG_BAND_LIMIT_1_8 = 0x18,
46 LBR_FLAG_BAND_LIMIT_NONE = 0x14,
47 LBR_FLAG_BAND_LIMIT_MASK = 0x1c,
48 LBR_FLAG_DMIX_STEREO = 0x20,
49 LBR_FLAG_DMIX_MULTI_CH = 0x40
53 LBR_CHUNK_NULL = 0x00,
55 LBR_CHUNK_FRAME = 0x04,
56 LBR_CHUNK_FRAME_NO_CSUM = 0x06,
59 LBR_CHUNK_RESERVED_1 = 0x0c,
60 LBR_CHUNK_RESERVED_2 = 0x0d,
62 LBR_CHUNK_TONAL = 0x10,
63 LBR_CHUNK_TONAL_GRP_1 = 0x11,
64 LBR_CHUNK_TONAL_GRP_2 = 0x12,
65 LBR_CHUNK_TONAL_GRP_3 = 0x13,
66 LBR_CHUNK_TONAL_GRP_4 = 0x14,
67 LBR_CHUNK_TONAL_GRP_5 = 0x15,
68 LBR_CHUNK_TONAL_SCF = 0x16,
69 LBR_CHUNK_TONAL_SCF_GRP_1 = 0x17,
70 LBR_CHUNK_TONAL_SCF_GRP_2 = 0x18,
71 LBR_CHUNK_TONAL_SCF_GRP_3 = 0x19,
72 LBR_CHUNK_TONAL_SCF_GRP_4 = 0x1a,
73 LBR_CHUNK_TONAL_SCF_GRP_5 = 0x1b,
74 LBR_CHUNK_RES_GRID_LR = 0x30,
75 LBR_CHUNK_RES_GRID_LR_LAST = 0x3f,
76 LBR_CHUNK_RES_GRID_HR = 0x40,
77 LBR_CHUNK_RES_GRID_HR_LAST = 0x4f,
78 LBR_CHUNK_RES_TS_1 = 0x50,
79 LBR_CHUNK_RES_TS_1_LAST = 0x5f,
80 LBR_CHUNK_RES_TS_2 = 0x60,
81 LBR_CHUNK_RES_TS_2_LAST = 0x6f,
82 LBR_CHUNK_EXTENSION = 0x7f
85 typedef struct LBRChunk {
90 static const int8_t channel_reorder_nolfe[7][5] = {
91 { 0, -1, -1, -1, -1 }, // C
92 { 0, 1, -1, -1, -1 }, // LR
93 { 0, 1, 2, -1, -1 }, // LR C
94 { 0, 1, -1, -1, -1 }, // LsRs
95 { 1, 2, 0, -1, -1 }, // LsRs C
96 { 0, 1, 2, 3, -1 }, // LR LsRs
97 { 0, 1, 3, 4, 2 }, // LR LsRs C
100 static const int8_t channel_reorder_lfe[7][5] = {
101 { 0, -1, -1, -1, -1 }, // C
102 { 0, 1, -1, -1, -1 }, // LR
103 { 0, 1, 2, -1, -1 }, // LR C
104 { 1, 2, -1, -1, -1 }, // LsRs
105 { 2, 3, 0, -1, -1 }, // LsRs C
106 { 0, 1, 3, 4, -1 }, // LR LsRs
107 { 0, 1, 4, 5, 2 }, // LR LsRs C
110 static const uint8_t lfe_index[7] = {
114 static const uint8_t channel_counts[7] = {
118 static const uint16_t channel_layouts[7] = {
121 AV_CH_LAYOUT_SURROUND,
122 AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,
123 AV_CH_FRONT_CENTER | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT,
128 static float cos_tab[256];
129 static float lpc_tab[16];
131 static av_cold void init_tables(void)
133 static int initialized;
139 for (i = 0; i < 256; i++)
140 cos_tab[i] = cos(M_PI * i / 128);
142 for (i = 0; i < 16; i++)
143 lpc_tab[i] = sin((i - 8) * (M_PI / ((i < 8) ? 17 : 15)));
148 static int parse_lfe_24(DCALbrDecoder *s)
150 int step_max = FF_ARRAY_ELEMS(ff_dca_lfe_step_size_24) - 1;
151 int i, ps, si, code, step_i;
152 float step, value, delta;
154 ps = get_bits(&s->gb, 24);
157 value = (((ps & 0x7fffff) ^ -si) + si) * (1.0f / 0x7fffff);
159 step_i = get_bits(&s->gb, 8);
160 if (step_i > step_max) {
161 av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE step size index\n");
165 step = ff_dca_lfe_step_size_24[step_i];
167 for (i = 0; i < 64; i++) {
168 code = get_bits(&s->gb, 6);
170 delta = step * 0.03125f;
174 delta += step * 0.5f;
176 delta += step * 0.25f;
178 delta += step * 0.125f;
180 delta += step * 0.0625f;
192 step_i += ff_dca_lfe_delta_index_24[code & 31];
193 step_i = av_clip(step_i, 0, step_max);
195 step = ff_dca_lfe_step_size_24[step_i];
196 s->lfe_data[i] = value * s->lfe_scale;
202 static int parse_lfe_16(DCALbrDecoder *s)
204 int step_max = FF_ARRAY_ELEMS(ff_dca_lfe_step_size_16) - 1;
205 int i, ps, si, code, step_i;
206 float step, value, delta;
208 ps = get_bits(&s->gb, 16);
211 value = (((ps & 0x7fff) ^ -si) + si) * (1.0f / 0x7fff);
213 step_i = get_bits(&s->gb, 8);
214 if (step_i > step_max) {
215 av_log(s->avctx, AV_LOG_ERROR, "Invalid LFE step size index\n");
219 step = ff_dca_lfe_step_size_16[step_i];
221 for (i = 0; i < 64; i++) {
222 code = get_bits(&s->gb, 4);
224 delta = step * 0.125f;
228 delta += step * 0.5f;
230 delta += step * 0.25f;
242 step_i += ff_dca_lfe_delta_index_16[code & 7];
243 step_i = av_clip(step_i, 0, step_max);
245 step = ff_dca_lfe_step_size_16[step_i];
246 s->lfe_data[i] = value * s->lfe_scale;
252 static int parse_lfe_chunk(DCALbrDecoder *s, LBRChunk *chunk)
254 if (!(s->flags & LBR_FLAG_LFE_PRESENT))
260 if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
263 // Determine bit depth from chunk size
264 if (chunk->len >= 52)
265 return parse_lfe_24(s);
266 if (chunk->len >= 35)
267 return parse_lfe_16(s);
269 av_log(s->avctx, AV_LOG_ERROR, "LFE chunk too short\n");
273 static inline int parse_vlc(GetBitContext *s, VLC *vlc, int max_depth)
275 int v = get_vlc2(s, vlc->table, vlc->bits, max_depth);
279 return get_bits(s, get_bits(s, 3) + 1);
282 static int parse_tonal(DCALbrDecoder *s, int group)
284 unsigned int amp[DCA_LBR_CHANNELS_TOTAL];
285 unsigned int phs[DCA_LBR_CHANNELS_TOTAL];
286 unsigned int diff, main_amp, shift;
287 int sf, sf_idx, ch, main_ch, freq;
288 int ch_nbits = av_ceil_log2(s->nchannels_total);
290 // Parse subframes for this group
291 for (sf = 0; sf < 1 << group; sf += diff ? 8 : 1) {
292 sf_idx = ((s->framenum << group) + sf) & 31;
293 s->tonal_bounds[group][sf_idx][0] = s->ntones;
295 // Parse tones for this subframe
296 for (freq = 1;; freq++) {
297 if (get_bits_left(&s->gb) < 1) {
298 av_log(s->avctx, AV_LOG_ERROR, "Tonal group chunk too short\n");
302 diff = parse_vlc(&s->gb, &ff_dca_vlc_tnl_grp[group], 2);
303 if (diff >= FF_ARRAY_ELEMS(ff_dca_fst_amp)) {
304 av_log(s->avctx, AV_LOG_ERROR, "Invalid tonal frequency diff\n");
308 diff = get_bitsz(&s->gb, diff >> 2) + ff_dca_fst_amp[diff];
310 break; // End of subframe
313 if (freq >> (5 - group) > s->nsubbands * 4 - 6) {
314 av_log(s->avctx, AV_LOG_ERROR, "Invalid spectral line offset\n");
319 main_ch = get_bitsz(&s->gb, ch_nbits);
320 main_amp = parse_vlc(&s->gb, &ff_dca_vlc_tnl_scf, 2)
321 + s->tonal_scf[ff_dca_freq_to_sb[freq >> (7 - group)]]
322 + s->limited_range - 2;
323 amp[main_ch] = main_amp < AMP_MAX ? main_amp : 0;
324 phs[main_ch] = get_bits(&s->gb, 3);
326 // Secondary channels
327 for (ch = 0; ch < s->nchannels_total; ch++) {
330 if (get_bits1(&s->gb)) {
331 amp[ch] = amp[main_ch] - parse_vlc(&s->gb, &ff_dca_vlc_damp, 1);
332 phs[ch] = phs[main_ch] - parse_vlc(&s->gb, &ff_dca_vlc_dph, 1);
341 DCALbrTone *t = &s->tones[s->ntones];
342 s->ntones = (s->ntones + 1) & (DCA_LBR_TONES - 1);
344 t->x_freq = freq >> (5 - group);
345 t->f_delt = (freq & ((1 << (5 - group)) - 1)) << group;
346 t->ph_rot = 256 - (t->x_freq & 1) * 128 - t->f_delt * 4;
348 shift = ff_dca_ph0_shift[(t->x_freq & 3) * 2 + (freq & 1)]
349 - ((t->ph_rot << (5 - group)) - t->ph_rot);
351 for (ch = 0; ch < s->nchannels; ch++) {
352 t->amp[ch] = amp[ch] < AMP_MAX ? amp[ch] : 0;
353 t->phs[ch] = 128 - phs[ch] * 32 + shift;
358 s->tonal_bounds[group][sf_idx][1] = s->ntones;
364 static int parse_tonal_chunk(DCALbrDecoder *s, LBRChunk *chunk)
371 if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
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");
380 for (sb = 0; sb < 6; sb++)
381 s->tonal_scf[sb] = get_bits(&s->gb, 6);
385 if (chunk->id == LBR_CHUNK_TONAL || chunk->id == LBR_CHUNK_TONAL_SCF)
386 for (group = 0; group < 5; group++)
387 if (parse_tonal(s, group) < 0)
393 static int parse_tonal_group(DCALbrDecoder *s, LBRChunk *chunk)
398 if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
401 return parse_tonal(s, chunk->id);
405 * Check point to ensure that enough bits are left. Aborts decoding
406 * by skipping to the end of chunk otherwise.
408 static int ensure_bits(GetBitContext *s, int n)
410 int left = get_bits_left(s);
414 skip_bits_long(s, left);
420 static int parse_scale_factors(DCALbrDecoder *s, uint8_t *scf)
422 int i, sf, prev, next, dist;
424 // Truncated scale factors remain zero
425 if (ensure_bits(&s->gb, 20))
428 // Initial scale factor
429 prev = parse_vlc(&s->gb, &ff_dca_vlc_fst_rsd_amp, 2);
431 for (sf = 0; sf < 7; sf += dist) {
432 scf[sf] = prev; // Store previous value
434 if (ensure_bits(&s->gb, 20))
437 // Interpolation distance
438 dist = parse_vlc(&s->gb, &ff_dca_vlc_rsd_apprx, 1) + 1;
440 av_log(s->avctx, AV_LOG_ERROR, "Invalid scale factor distance\n");
444 if (ensure_bits(&s->gb, 20))
447 // Final interpolation point
448 next = parse_vlc(&s->gb, &ff_dca_vlc_rsd_amp, 2);
451 next = prev + ((next + 1) >> 1);
453 next = prev - ( next >> 1);
459 scf[sf + 1] = prev + ((next - prev) >> 1);
461 scf[sf + 1] = prev - ((prev - next) >> 1);
466 scf[sf + 1] = prev + ( (next - prev) >> 2);
467 scf[sf + 2] = prev + ( (next - prev) >> 1);
468 scf[sf + 3] = prev + (((next - prev) * 3) >> 2);
470 scf[sf + 1] = prev - ( (prev - next) >> 2);
471 scf[sf + 2] = prev - ( (prev - next) >> 1);
472 scf[sf + 3] = prev - (((prev - next) * 3) >> 2);
477 for (i = 1; i < dist; i++)
478 scf[sf + i] = prev + (next - prev) * i / dist;
485 scf[sf] = next; // Store final value
490 static int parse_st_code(GetBitContext *s, int min_v)
492 unsigned int v = parse_vlc(s, &ff_dca_vlc_st_grid, 2) + min_v;
499 if (v >= FF_ARRAY_ELEMS(ff_dca_st_coeff))
504 static int parse_grid_1_chunk(DCALbrDecoder *s, LBRChunk *chunk, int ch1, int ch2)
506 int ch, sb, sf, nsubbands;
511 if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
515 nsubbands = ff_dca_scf_to_grid_1[s->nsubbands - 1] + 1;
516 for (sb = 2; sb < nsubbands; sb++) {
517 if (parse_scale_factors(s, s->grid_1_scf[ch1][sb]) < 0)
519 if (ch1 != ch2 && ff_dca_grid_1_to_scf[sb] < s->min_mono_subband
520 && parse_scale_factors(s, s->grid_1_scf[ch2][sb]) < 0)
524 if (get_bits_left(&s->gb) < 1)
525 return 0; // Should not happen, but a sample exists that proves otherwise
527 // Average values for third grid
528 for (sb = 0; sb < s->nsubbands - 4; sb++) {
529 s->grid_3_avg[ch1][sb] = parse_vlc(&s->gb, &ff_dca_vlc_avg_g3, 2) - 16;
531 if (sb + 4 < s->min_mono_subband)
532 s->grid_3_avg[ch2][sb] = parse_vlc(&s->gb, &ff_dca_vlc_avg_g3, 2) - 16;
534 s->grid_3_avg[ch2][sb] = s->grid_3_avg[ch1][sb];
538 if (get_bits_left(&s->gb) < 0) {
539 av_log(s->avctx, AV_LOG_ERROR, "First grid chunk too short\n");
543 // Stereo image for partial mono mode
547 if (ensure_bits(&s->gb, 8))
550 min_v[0] = get_bits(&s->gb, 4);
551 min_v[1] = get_bits(&s->gb, 4);
553 nsubbands = (s->nsubbands - s->min_mono_subband + 3) / 4;
554 for (sb = 0; sb < nsubbands; sb++)
555 for (ch = ch1; ch <= ch2; ch++)
556 for (sf = 1; sf <= 4; sf++)
557 s->part_stereo[ch][sb][sf] = parse_st_code(&s->gb, min_v[ch - ch1]);
559 if (get_bits_left(&s->gb) >= 0)
560 s->part_stereo_pres |= 1 << ch1;
563 // Low resolution spatial information is not decoded
568 static int parse_grid_1_sec_ch(DCALbrDecoder *s, int ch2)
573 nsubbands = ff_dca_scf_to_grid_1[s->nsubbands - 1] + 1;
574 for (sb = 2; sb < nsubbands; sb++) {
575 if (ff_dca_grid_1_to_scf[sb] >= s->min_mono_subband
576 && parse_scale_factors(s, s->grid_1_scf[ch2][sb]) < 0)
580 // Average values for third grid
581 for (sb = 0; sb < s->nsubbands - 4; sb++) {
582 if (sb + 4 >= s->min_mono_subband) {
583 if (ensure_bits(&s->gb, 20))
585 s->grid_3_avg[ch2][sb] = parse_vlc(&s->gb, &ff_dca_vlc_avg_g3, 2) - 16;
592 static void parse_grid_3(DCALbrDecoder *s, int ch1, int ch2, int sb, int flag)
596 for (ch = ch1; ch <= ch2; ch++) {
597 if ((ch != ch1 && sb + 4 >= s->min_mono_subband) != flag)
600 if (s->grid_3_pres[ch] & (1U << sb))
601 continue; // Already parsed
603 for (i = 0; i < 8; i++) {
604 if (ensure_bits(&s->gb, 20))
606 s->grid_3_scf[ch][sb][i] = parse_vlc(&s->gb, &ff_dca_vlc_grid_3, 2) - 16;
609 // Flag scale factors for this subband parsed
610 s->grid_3_pres[ch] |= 1U << sb;
614 static float lbr_rand(DCALbrDecoder *s, int sb)
616 s->lbr_rand = 1103515245U * s->lbr_rand + 12345U;
617 return s->lbr_rand * s->sb_scf[sb];
621 * Parse time samples for one subband, filling truncated samples with randomness
623 static void parse_ch(DCALbrDecoder *s, int ch, int sb, int quant_level, int flag)
625 float *samples = s->time_samples[ch][sb];
626 int i, j, code, nblocks, coding_method;
628 if (ensure_bits(&s->gb, 20))
629 return; // Too few bits left
631 coding_method = get_bits1(&s->gb);
633 switch (quant_level) {
635 nblocks = FFMIN(get_bits_left(&s->gb) / 8, DCA_LBR_TIME_SAMPLES / 8);
636 for (i = 0; i < nblocks; i++, samples += 8) {
637 code = get_bits(&s->gb, 8);
638 for (j = 0; j < 8; j++)
639 samples[j] = ff_dca_rsd_level_2a[(code >> j) & 1];
646 for (i = 0; i < DCA_LBR_TIME_SAMPLES && get_bits_left(&s->gb) >= 2; i++) {
647 if (get_bits1(&s->gb))
648 samples[i] = ff_dca_rsd_level_2b[get_bits1(&s->gb)];
653 nblocks = FFMIN(get_bits_left(&s->gb) / 8, (DCA_LBR_TIME_SAMPLES + 4) / 5);
654 for (i = 0; i < nblocks; i++, samples += 5) {
655 code = ff_dca_rsd_pack_5_in_8[get_bits(&s->gb, 8)];
656 for (j = 0; j < 5; j++)
657 samples[j] = ff_dca_rsd_level_3[(code >> j * 2) & 3];
664 nblocks = FFMIN(get_bits_left(&s->gb) / 7, (DCA_LBR_TIME_SAMPLES + 2) / 3);
665 for (i = 0; i < nblocks; i++, samples += 3) {
666 code = get_bits(&s->gb, 7);
667 for (j = 0; j < 3; j++)
668 samples[j] = ff_dca_rsd_level_5[ff_dca_rsd_pack_3_in_7[code][j]];
674 for (i = 0; i < DCA_LBR_TIME_SAMPLES && get_bits_left(&s->gb) >= 6; i++)
675 samples[i] = ff_dca_rsd_level_8[get_vlc2(&s->gb, ff_dca_vlc_rsd.table, 6, 1)];
679 nblocks = FFMIN(get_bits_left(&s->gb) / 4, DCA_LBR_TIME_SAMPLES);
680 for (i = 0; i < nblocks; i++)
681 samples[i] = ff_dca_rsd_level_16[get_bits(&s->gb, 4)];
688 if (flag && get_bits_left(&s->gb) < 20)
689 return; // Skip incomplete mono subband
691 for (; i < DCA_LBR_TIME_SAMPLES; i++)
692 s->time_samples[ch][sb][i] = lbr_rand(s, sb);
694 s->ch_pres[ch] |= 1U << sb;
697 static int parse_ts(DCALbrDecoder *s, int ch1, int ch2,
698 int start_sb, int end_sb, int flag)
700 int sb, sb_g3, sb_reorder, quant_level;
702 for (sb = start_sb; sb < end_sb; sb++) {
703 // Subband number before reordering
706 } else if (flag && sb < s->max_mono_subband) {
707 sb_reorder = s->sb_indices[sb];
709 if (ensure_bits(&s->gb, 28))
711 sb_reorder = get_bits(&s->gb, s->limited_range + 3);
714 s->sb_indices[sb] = sb_reorder;
716 if (sb_reorder >= s->nsubbands)
719 // Third grid scale factors
721 for (sb_g3 = 0; sb_g3 < s->g3_avg_only_start_sb - 4; sb_g3++)
722 parse_grid_3(s, ch1, ch2, sb_g3, flag);
723 } else if (sb < 12 && sb_reorder >= 4) {
724 parse_grid_3(s, ch1, ch2, sb_reorder - 4, flag);
727 // Secondary channel flags
729 if (ensure_bits(&s->gb, 20))
731 if (!flag || sb_reorder >= s->max_mono_subband)
732 s->sec_ch_sbms[ch1 / 2][sb_reorder] = get_bits(&s->gb, 8);
733 if (flag && sb_reorder >= s->min_mono_subband)
734 s->sec_ch_lrms[ch1 / 2][sb_reorder] = get_bits(&s->gb, 8);
737 quant_level = s->quant_levels[ch1 / 2][sb];
741 // Time samples for one or both channels
742 if (sb < s->max_mono_subband && sb_reorder >= s->min_mono_subband) {
744 parse_ch(s, ch1, sb_reorder, quant_level, 0);
746 parse_ch(s, ch2, sb_reorder, quant_level, 1);
748 parse_ch(s, ch1, sb_reorder, quant_level, 0);
750 parse_ch(s, ch2, sb_reorder, quant_level, 0);
758 * Convert from reflection coefficients to direct form coefficients
760 static void convert_lpc(float *coeff, const int *codes)
764 for (i = 0; i < 8; i++) {
765 float rc = lpc_tab[codes[i]];
766 for (j = 0; j < (i + 1) / 2; j++) {
767 float tmp1 = coeff[ j ];
768 float tmp2 = coeff[i - j - 1];
769 coeff[ j ] = tmp1 + rc * tmp2;
770 coeff[i - j - 1] = tmp2 + rc * tmp1;
776 static int parse_lpc(DCALbrDecoder *s, int ch1, int ch2, int start_sb, int end_sb)
778 int f = s->framenum & 1;
779 int i, sb, ch, codes[16];
781 // First two subbands have two sets of coefficients, third subband has one
782 for (sb = start_sb; sb < end_sb; sb++) {
783 int ncodes = 8 * (1 + (sb < 2));
784 for (ch = ch1; ch <= ch2; ch++) {
785 if (ensure_bits(&s->gb, 4 * ncodes))
787 for (i = 0; i < ncodes; i++)
788 codes[i] = get_bits(&s->gb, 4);
789 for (i = 0; i < ncodes / 8; i++)
790 convert_lpc(s->lpc_coeff[f][ch][sb][i], &codes[i * 8]);
797 static int parse_high_res_grid(DCALbrDecoder *s, LBRChunk *chunk, int ch1, int ch2)
799 int quant_levels[DCA_LBR_SUBBANDS];
800 int sb, ch, ol, st, max_sb, profile;
805 if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
809 profile = get_bits(&s->gb, 8);
811 ol = (profile >> 3) & 7;
814 // Max energy subband
815 max_sb = profile & 7;
817 // Calculate quantization levels
818 for (sb = 0; sb < s->nsubbands; sb++) {
819 int f = sb * s->limited_rate / s->nsubbands;
820 int a = 18000 / (12 * f / 1000 + 100 + 40 * st) + 20 * ol;
822 quant_levels[sb] = 1;
824 quant_levels[sb] = 2;
826 quant_levels[sb] = 3;
828 quant_levels[sb] = 4;
830 quant_levels[sb] = 5;
833 // Reorder quantization levels for lower subbands
834 for (sb = 0; sb < 8; sb++)
835 s->quant_levels[ch1 / 2][sb] = quant_levels[ff_dca_sb_reorder[max_sb][sb]];
836 for (; sb < s->nsubbands; sb++)
837 s->quant_levels[ch1 / 2][sb] = quant_levels[sb];
839 // LPC for the first two subbands
840 if (parse_lpc(s, ch1, ch2, 0, 2) < 0)
843 // Time-samples for the first two subbands of main channel
844 if (parse_ts(s, ch1, ch2, 0, 2, 0) < 0)
847 // First two bands of the first grid
848 for (sb = 0; sb < 2; sb++)
849 for (ch = ch1; ch <= ch2; ch++)
850 if (parse_scale_factors(s, s->grid_1_scf[ch][sb]) < 0)
856 static int parse_grid_2(DCALbrDecoder *s, int ch1, int ch2,
857 int start_sb, int end_sb, int flag)
859 int i, j, sb, ch, nsubbands;
861 nsubbands = ff_dca_scf_to_grid_2[s->nsubbands - 1] + 1;
862 if (end_sb > nsubbands)
865 for (sb = start_sb; sb < end_sb; sb++) {
866 for (ch = ch1; ch <= ch2; ch++) {
867 uint8_t *g2_scf = s->grid_2_scf[ch][sb];
869 if ((ch != ch1 && ff_dca_grid_2_to_scf[sb] >= s->min_mono_subband) != flag) {
871 memcpy(g2_scf, s->grid_2_scf[ch1][sb], 64);
875 // Scale factors in groups of 8
876 for (i = 0; i < 8; i++, g2_scf += 8) {
877 if (get_bits_left(&s->gb) < 1) {
878 memset(g2_scf, 0, 64 - i * 8);
881 // Bit indicating if whole group has zero values
882 if (get_bits1(&s->gb)) {
883 for (j = 0; j < 8; j++) {
884 if (ensure_bits(&s->gb, 20))
886 g2_scf[j] = parse_vlc(&s->gb, &ff_dca_vlc_grid_2, 2);
889 memset(g2_scf, 0, 8);
898 static int parse_ts1_chunk(DCALbrDecoder *s, LBRChunk *chunk, int ch1, int ch2)
902 if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
904 if (parse_lpc(s, ch1, ch2, 2, 3) < 0)
906 if (parse_ts(s, ch1, ch2, 2, 4, 0) < 0)
908 if (parse_grid_2(s, ch1, ch2, 0, 1, 0) < 0)
910 if (parse_ts(s, ch1, ch2, 4, 6, 0) < 0)
915 static int parse_ts2_chunk(DCALbrDecoder *s, LBRChunk *chunk, int ch1, int ch2)
919 if (init_get_bits8(&s->gb, chunk->data, chunk->len) < 0)
921 if (parse_grid_2(s, ch1, ch2, 1, 3, 0) < 0)
923 if (parse_ts(s, ch1, ch2, 6, s->max_mono_subband, 0) < 0)
926 if (parse_grid_1_sec_ch(s, ch2) < 0)
928 if (parse_grid_2(s, ch1, ch2, 0, 3, 1) < 0)
931 if (parse_ts(s, ch1, ch2, s->min_mono_subband, s->nsubbands, 1) < 0)
936 static int init_sample_rate(DCALbrDecoder *s)
938 double scale = (-1.0 / (1 << 17)) * sqrt(1 << (2 - s->limited_range));
939 int i, br_per_ch = s->bit_rate_scaled / s->nchannels_total;
941 ff_mdct_end(&s->imdct);
943 if (ff_mdct_init(&s->imdct, s->freq_range + 6, 1, scale) < 0)
946 for (i = 0; i < 32 << s->freq_range; i++)
947 s->window[i] = ff_dca_long_window[i << (2 - s->freq_range)];
949 if (br_per_ch < 14000)
951 else if (br_per_ch < 32000)
952 scale = (br_per_ch - 14000) * (1.0 / 120000) + 0.85;
956 scale *= 1.0 / INT_MAX;
958 for (i = 0; i < s->nsubbands; i++) {
960 s->sb_scf[i] = 0; // The first two subbands are always zero
962 s->sb_scf[i] = (i - 1) * 0.25 * 0.785 * scale;
964 s->sb_scf[i] = 0.785 * scale;
967 s->lfe_scale = (16 << s->freq_range) * 0.0000078265894;
972 static int alloc_sample_buffer(DCALbrDecoder *s)
974 // Reserve space for history and padding
975 int nchsamples = DCA_LBR_TIME_SAMPLES + DCA_LBR_TIME_HISTORY * 2;
976 int nsamples = nchsamples * s->nchannels * s->nsubbands;
980 // Reallocate time sample buffer
981 av_fast_mallocz(&s->ts_buffer, &s->ts_size, nsamples * sizeof(float));
985 ptr = s->ts_buffer + DCA_LBR_TIME_HISTORY;
986 for (ch = 0; ch < s->nchannels; ch++) {
987 for (sb = 0; sb < s->nsubbands; sb++) {
988 s->time_samples[ch][sb] = ptr;
996 static int parse_decoder_init(DCALbrDecoder *s, GetByteContext *gb)
998 int old_rate = s->sample_rate;
999 int old_band_limit = s->band_limit;
1000 int old_nchannels = s->nchannels;
1001 int version, bit_rate_hi;
1002 unsigned int sr_code;
1004 // Sample rate of LBR audio
1005 sr_code = bytestream2_get_byte(gb);
1006 if (sr_code >= FF_ARRAY_ELEMS(ff_dca_sampling_freqs)) {
1007 av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR sample rate\n");
1008 return AVERROR_INVALIDDATA;
1010 s->sample_rate = ff_dca_sampling_freqs[sr_code];
1011 if (s->sample_rate > 48000) {
1012 avpriv_report_missing_feature(s->avctx, "%d Hz LBR sample rate", s->sample_rate);
1013 return AVERROR_PATCHWELCOME;
1017 s->ch_mask = bytestream2_get_le16(gb);
1018 if (!(s->ch_mask & 0x7)) {
1019 avpriv_report_missing_feature(s->avctx, "LBR channel mask %#x", s->ch_mask);
1020 return AVERROR_PATCHWELCOME;
1022 if ((s->ch_mask & 0xfff0) && !(s->warned & 1)) {
1023 avpriv_report_missing_feature(s->avctx, "LBR channel mask %#x", s->ch_mask);
1027 // LBR bitstream version
1028 version = bytestream2_get_le16(gb);
1029 if ((version & 0xff00) != 0x0800) {
1030 avpriv_report_missing_feature(s->avctx, "LBR stream version %#x", version);
1031 return AVERROR_PATCHWELCOME;
1034 // Flags for LBR decoder initialization
1035 s->flags = bytestream2_get_byte(gb);
1036 if (s->flags & LBR_FLAG_DMIX_MULTI_CH) {
1037 avpriv_report_missing_feature(s->avctx, "LBR multi-channel downmix");
1038 return AVERROR_PATCHWELCOME;
1040 if ((s->flags & LBR_FLAG_LFE_PRESENT) && s->sample_rate != 48000) {
1041 if (!(s->warned & 2)) {
1042 avpriv_report_missing_feature(s->avctx, "%d Hz LFE interpolation", s->sample_rate);
1045 s->flags &= ~LBR_FLAG_LFE_PRESENT;
1048 // Most significant bit rate nibbles
1049 bit_rate_hi = bytestream2_get_byte(gb);
1051 // Least significant original bit rate word
1052 s->bit_rate_orig = bytestream2_get_le16(gb) | ((bit_rate_hi & 0x0F) << 16);
1054 // Least significant scaled bit rate word
1055 s->bit_rate_scaled = bytestream2_get_le16(gb) | ((bit_rate_hi & 0xF0) << 12);
1057 // Setup number of fullband channels
1058 s->nchannels_total = ff_dca_count_chs_for_mask(s->ch_mask & ~DCA_SPEAKER_PAIR_LFE1);
1059 s->nchannels = FFMIN(s->nchannels_total, DCA_LBR_CHANNELS);
1062 switch (s->flags & LBR_FLAG_BAND_LIMIT_MASK) {
1063 case LBR_FLAG_BAND_LIMIT_NONE:
1066 case LBR_FLAG_BAND_LIMIT_1_2:
1069 case LBR_FLAG_BAND_LIMIT_1_4:
1073 avpriv_report_missing_feature(s->avctx, "LBR band limit %#x", s->flags & LBR_FLAG_BAND_LIMIT_MASK);
1074 return AVERROR_PATCHWELCOME;
1077 // Setup frequency range
1078 s->freq_range = ff_dca_freq_ranges[sr_code];
1080 // Setup resolution profile
1081 if (s->bit_rate_orig >= 44000 * (s->nchannels_total + 2))
1083 else if (s->bit_rate_orig >= 25000 * (s->nchannels_total + 2))
1088 // Setup limited sample rate, number of subbands, etc
1089 s->limited_rate = s->sample_rate >> s->band_limit;
1090 s->limited_range = s->freq_range - s->band_limit;
1091 if (s->limited_range < 0) {
1092 av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR band limit for frequency range\n");
1093 return AVERROR_INVALIDDATA;
1096 s->nsubbands = 8 << s->limited_range;
1098 s->g3_avg_only_start_sb = s->nsubbands * ff_dca_avg_g3_freqs[s->res_profile] / (s->limited_rate / 2);
1099 if (s->g3_avg_only_start_sb > s->nsubbands)
1100 s->g3_avg_only_start_sb = s->nsubbands;
1102 s->min_mono_subband = s->nsubbands * 2000 / (s->limited_rate / 2);
1103 if (s->min_mono_subband > s->nsubbands)
1104 s->min_mono_subband = s->nsubbands;
1106 s->max_mono_subband = s->nsubbands * 14000 / (s->limited_rate / 2);
1107 if (s->max_mono_subband > s->nsubbands)
1108 s->max_mono_subband = s->nsubbands;
1110 // Handle change of sample rate
1111 if ((old_rate != s->sample_rate || old_band_limit != s->band_limit) && init_sample_rate(s) < 0)
1112 return AVERROR(ENOMEM);
1114 // Setup stereo downmix
1115 if (s->flags & LBR_FLAG_DMIX_STEREO) {
1116 DCAContext *dca = s->avctx->priv_data;
1118 if (s->nchannels_total < 3 || s->nchannels_total > DCA_LBR_CHANNELS_TOTAL - 2) {
1119 av_log(s->avctx, AV_LOG_ERROR, "Invalid number of channels for LBR stereo downmix\n");
1120 return AVERROR_INVALIDDATA;
1123 // This decoder doesn't support ECS chunk
1124 if (dca->request_channel_layout != DCA_SPEAKER_LAYOUT_STEREO && !(s->warned & 4)) {
1125 avpriv_report_missing_feature(s->avctx, "Embedded LBR stereo downmix");
1129 // Account for extra downmixed channel pair
1130 s->nchannels_total += 2;
1132 s->ch_mask = DCA_SPEAKER_PAIR_LR;
1133 s->flags &= ~LBR_FLAG_LFE_PRESENT;
1136 // Handle change of sample rate or number of channels
1137 if (old_rate != s->sample_rate
1138 || old_band_limit != s->band_limit
1139 || old_nchannels != s->nchannels) {
1140 if (alloc_sample_buffer(s) < 0)
1141 return AVERROR(ENOMEM);
1142 ff_dca_lbr_flush(s);
1148 int ff_dca_lbr_parse(DCALbrDecoder *s, uint8_t *data, DCAExssAsset *asset)
1153 LBRChunk tonal_grp[5];
1154 LBRChunk grid1[DCA_LBR_CHANNELS / 2];
1155 LBRChunk hr_grid[DCA_LBR_CHANNELS / 2];
1156 LBRChunk ts1[DCA_LBR_CHANNELS / 2];
1157 LBRChunk ts2[DCA_LBR_CHANNELS / 2];
1162 int i, ch, sb, sf, ret, group, chunk_id, chunk_len;
1164 bytestream2_init(&gb, data + asset->lbr_offset, asset->lbr_size);
1167 if (bytestream2_get_be32(&gb) != DCA_SYNCWORD_LBR) {
1168 av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR sync word\n");
1169 return AVERROR_INVALIDDATA;
1173 switch (bytestream2_get_byte(&gb)) {
1174 case LBR_HEADER_SYNC_ONLY:
1175 if (!s->sample_rate) {
1176 av_log(s->avctx, AV_LOG_ERROR, "LBR decoder not initialized\n");
1177 return AVERROR_INVALIDDATA;
1180 case LBR_HEADER_DECODER_INIT:
1181 if ((ret = parse_decoder_init(s, &gb)) < 0) {
1187 av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR header type\n");
1188 return AVERROR_INVALIDDATA;
1191 // LBR frame chunk header
1192 chunk_id = bytestream2_get_byte(&gb);
1193 chunk_len = (chunk_id & 0x80) ? bytestream2_get_be16(&gb) : bytestream2_get_byte(&gb);
1195 if (chunk_len > bytestream2_get_bytes_left(&gb)) {
1196 chunk_len = bytestream2_get_bytes_left(&gb);
1197 av_log(s->avctx, AV_LOG_WARNING, "LBR frame chunk was truncated\n");
1198 if (s->avctx->err_recognition & AV_EF_EXPLODE)
1199 return AVERROR_INVALIDDATA;
1202 bytestream2_init(&gb, gb.buffer, chunk_len);
1204 switch (chunk_id & 0x7f) {
1205 case LBR_CHUNK_FRAME:
1206 if (s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL)) {
1207 int checksum = bytestream2_get_be16(&gb);
1208 uint16_t res = chunk_id;
1209 res += (chunk_len >> 8) & 0xff;
1210 res += chunk_len & 0xff;
1211 for (i = 0; i < chunk_len - 2; i++)
1212 res += gb.buffer[i];
1213 if (checksum != res) {
1214 av_log(s->avctx, AV_LOG_WARNING, "Invalid LBR checksum\n");
1215 if (s->avctx->err_recognition & AV_EF_EXPLODE)
1216 return AVERROR_INVALIDDATA;
1219 bytestream2_skip(&gb, 2);
1222 case LBR_CHUNK_FRAME_NO_CSUM:
1225 av_log(s->avctx, AV_LOG_ERROR, "Invalid LBR frame chunk ID\n");
1226 return AVERROR_INVALIDDATA;
1229 // Clear current frame
1230 memset(s->quant_levels, 0, sizeof(s->quant_levels));
1231 memset(s->sb_indices, 0xff, sizeof(s->sb_indices));
1232 memset(s->sec_ch_sbms, 0, sizeof(s->sec_ch_sbms));
1233 memset(s->sec_ch_lrms, 0, sizeof(s->sec_ch_lrms));
1234 memset(s->ch_pres, 0, sizeof(s->ch_pres));
1235 memset(s->grid_1_scf, 0, sizeof(s->grid_1_scf));
1236 memset(s->grid_2_scf, 0, sizeof(s->grid_2_scf));
1237 memset(s->grid_3_avg, 0, sizeof(s->grid_3_avg));
1238 memset(s->grid_3_scf, 0, sizeof(s->grid_3_scf));
1239 memset(s->grid_3_pres, 0, sizeof(s->grid_3_pres));
1240 memset(s->tonal_scf, 0, sizeof(s->tonal_scf));
1241 memset(s->lfe_data, 0, sizeof(s->lfe_data));
1242 s->part_stereo_pres = 0;
1243 s->framenum = (s->framenum + 1) & 31;
1245 for (ch = 0; ch < s->nchannels; ch++) {
1246 for (sb = 0; sb < s->nsubbands / 4; sb++) {
1247 s->part_stereo[ch][sb][0] = s->part_stereo[ch][sb][4];
1248 s->part_stereo[ch][sb][4] = 16;
1252 memset(s->lpc_coeff[s->framenum & 1], 0, sizeof(s->lpc_coeff[0]));
1254 for (group = 0; group < 5; group++) {
1255 for (sf = 0; sf < 1 << group; sf++) {
1256 int sf_idx = ((s->framenum << group) + sf) & 31;
1257 s->tonal_bounds[group][sf_idx][0] =
1258 s->tonal_bounds[group][sf_idx][1] = s->ntones;
1262 // Parse chunk headers
1263 while (bytestream2_get_bytes_left(&gb) > 0) {
1264 chunk_id = bytestream2_get_byte(&gb);
1265 chunk_len = (chunk_id & 0x80) ? bytestream2_get_be16(&gb) : bytestream2_get_byte(&gb);
1268 if (chunk_len > bytestream2_get_bytes_left(&gb)) {
1269 chunk_len = bytestream2_get_bytes_left(&gb);
1270 av_log(s->avctx, AV_LOG_WARNING, "LBR chunk %#x was truncated\n", chunk_id);
1271 if (s->avctx->err_recognition & AV_EF_EXPLODE)
1272 return AVERROR_INVALIDDATA;
1277 chunk.lfe.len = chunk_len;
1278 chunk.lfe.data = gb.buffer;
1282 case LBR_CHUNK_TONAL:
1283 case LBR_CHUNK_TONAL_SCF:
1284 chunk.tonal.id = chunk_id;
1285 chunk.tonal.len = chunk_len;
1286 chunk.tonal.data = gb.buffer;
1289 case LBR_CHUNK_TONAL_GRP_1:
1290 case LBR_CHUNK_TONAL_GRP_2:
1291 case LBR_CHUNK_TONAL_GRP_3:
1292 case LBR_CHUNK_TONAL_GRP_4:
1293 case LBR_CHUNK_TONAL_GRP_5:
1294 i = LBR_CHUNK_TONAL_GRP_5 - chunk_id;
1295 chunk.tonal_grp[i].id = i;
1296 chunk.tonal_grp[i].len = chunk_len;
1297 chunk.tonal_grp[i].data = gb.buffer;
1300 case LBR_CHUNK_TONAL_SCF_GRP_1:
1301 case LBR_CHUNK_TONAL_SCF_GRP_2:
1302 case LBR_CHUNK_TONAL_SCF_GRP_3:
1303 case LBR_CHUNK_TONAL_SCF_GRP_4:
1304 case LBR_CHUNK_TONAL_SCF_GRP_5:
1305 i = LBR_CHUNK_TONAL_SCF_GRP_5 - chunk_id;
1306 chunk.tonal_grp[i].id = i;
1307 chunk.tonal_grp[i].len = chunk_len;
1308 chunk.tonal_grp[i].data = gb.buffer;
1311 case LBR_CHUNK_RES_GRID_LR:
1312 case LBR_CHUNK_RES_GRID_LR + 1:
1313 case LBR_CHUNK_RES_GRID_LR + 2:
1314 i = chunk_id - LBR_CHUNK_RES_GRID_LR;
1315 chunk.grid1[i].len = chunk_len;
1316 chunk.grid1[i].data = gb.buffer;
1319 case LBR_CHUNK_RES_GRID_HR:
1320 case LBR_CHUNK_RES_GRID_HR + 1:
1321 case LBR_CHUNK_RES_GRID_HR + 2:
1322 i = chunk_id - LBR_CHUNK_RES_GRID_HR;
1323 chunk.hr_grid[i].len = chunk_len;
1324 chunk.hr_grid[i].data = gb.buffer;
1327 case LBR_CHUNK_RES_TS_1:
1328 case LBR_CHUNK_RES_TS_1 + 1:
1329 case LBR_CHUNK_RES_TS_1 + 2:
1330 i = chunk_id - LBR_CHUNK_RES_TS_1;
1331 chunk.ts1[i].len = chunk_len;
1332 chunk.ts1[i].data = gb.buffer;
1335 case LBR_CHUNK_RES_TS_2:
1336 case LBR_CHUNK_RES_TS_2 + 1:
1337 case LBR_CHUNK_RES_TS_2 + 2:
1338 i = chunk_id - LBR_CHUNK_RES_TS_2;
1339 chunk.ts2[i].len = chunk_len;
1340 chunk.ts2[i].data = gb.buffer;
1344 bytestream2_skip(&gb, chunk_len);
1348 ret = parse_lfe_chunk(s, &chunk.lfe);
1350 ret |= parse_tonal_chunk(s, &chunk.tonal);
1352 for (i = 0; i < 5; i++)
1353 ret |= parse_tonal_group(s, &chunk.tonal_grp[i]);
1355 for (i = 0; i < (s->nchannels + 1) / 2; i++) {
1357 int ch2 = FFMIN(ch1 + 1, s->nchannels - 1);
1359 if (parse_grid_1_chunk (s, &chunk.grid1 [i], ch1, ch2) < 0 ||
1360 parse_high_res_grid(s, &chunk.hr_grid[i], ch1, ch2) < 0) {
1365 // TS chunks depend on both grids. TS_2 depends on TS_1.
1366 if (!chunk.grid1[i].len || !chunk.hr_grid[i].len || !chunk.ts1[i].len)
1369 if (parse_ts1_chunk(s, &chunk.ts1[i], ch1, ch2) < 0 ||
1370 parse_ts2_chunk(s, &chunk.ts2[i], ch1, ch2) < 0) {
1376 if (ret < 0 && (s->avctx->err_recognition & AV_EF_EXPLODE))
1377 return AVERROR_INVALIDDATA;
1383 * Reconstruct high-frequency resolution grid from first and third grids
1385 static void decode_grid(DCALbrDecoder *s, int ch1, int ch2)
1389 for (ch = ch1; ch <= ch2; ch++) {
1390 for (sb = 0; sb < s->nsubbands; sb++) {
1391 int g1_sb = ff_dca_scf_to_grid_1[sb];
1393 uint8_t *g1_scf_a = s->grid_1_scf[ch][g1_sb ];
1394 uint8_t *g1_scf_b = s->grid_1_scf[ch][g1_sb + 1];
1396 int w1 = ff_dca_grid_1_weights[g1_sb ][sb];
1397 int w2 = ff_dca_grid_1_weights[g1_sb + 1][sb];
1399 uint8_t *hr_scf = s->high_res_scf[ch][sb];
1402 for (i = 0; i < 8; i++) {
1403 int scf = w1 * g1_scf_a[i] + w2 * g1_scf_b[i];
1404 hr_scf[i] = scf >> 7;
1407 int8_t *g3_scf = s->grid_3_scf[ch][sb - 4];
1408 int g3_avg = s->grid_3_avg[ch][sb - 4];
1410 for (i = 0; i < 8; i++) {
1411 int scf = w1 * g1_scf_a[i] + w2 * g1_scf_b[i];
1412 hr_scf[i] = (scf >> 7) - g3_avg - g3_scf[i];
1420 * Fill unallocated subbands with randomness
1422 static void random_ts(DCALbrDecoder *s, int ch1, int ch2)
1424 int i, j, k, ch, sb;
1426 for (ch = ch1; ch <= ch2; ch++) {
1427 for (sb = 0; sb < s->nsubbands; sb++) {
1428 float *samples = s->time_samples[ch][sb];
1430 if (s->ch_pres[ch] & (1U << sb))
1431 continue; // Skip allocated subband
1434 // The first two subbands are always zero
1435 memset(samples, 0, DCA_LBR_TIME_SAMPLES * sizeof(float));
1436 } else if (sb < 10) {
1437 for (i = 0; i < DCA_LBR_TIME_SAMPLES; i++)
1438 samples[i] = lbr_rand(s, sb);
1440 for (i = 0; i < DCA_LBR_TIME_SAMPLES / 8; i++, samples += 8) {
1441 float accum[8] = { 0 };
1443 // Modulate by subbands 2-5 in blocks of 8
1444 for (k = 2; k < 6; k++) {
1445 float *other = &s->time_samples[ch][k][i * 8];
1446 for (j = 0; j < 8; j++)
1447 accum[j] += fabs(other[j]);
1450 for (j = 0; j < 8; j++)
1451 samples[j] = (accum[j] * 0.25f + 0.5f) * lbr_rand(s, sb);
1458 static void predict(float *samples, const float *coeff, int nsamples)
1462 for (i = 0; i < nsamples; i++) {
1464 for (j = 0; j < 8; j++)
1465 res += coeff[j] * samples[i - j - 1];
1470 static void synth_lpc(DCALbrDecoder *s, int ch1, int ch2, int sb)
1472 int f = s->framenum & 1;
1475 for (ch = ch1; ch <= ch2; ch++) {
1476 float *samples = s->time_samples[ch][sb];
1478 if (!(s->ch_pres[ch] & (1U << sb)))
1482 predict(samples, s->lpc_coeff[f^1][ch][sb][1], 16);
1483 predict(samples + 16, s->lpc_coeff[f ][ch][sb][0], 64);
1484 predict(samples + 80, s->lpc_coeff[f ][ch][sb][1], 48);
1486 predict(samples, s->lpc_coeff[f^1][ch][sb][0], 16);
1487 predict(samples + 16, s->lpc_coeff[f ][ch][sb][0], 112);
1492 static void filter_ts(DCALbrDecoder *s, int ch1, int ch2)
1496 for (sb = 0; sb < s->nsubbands; sb++) {
1498 for (ch = ch1; ch <= ch2; ch++) {
1499 float *samples = s->time_samples[ch][sb];
1500 uint8_t *hr_scf = s->high_res_scf[ch][sb];
1502 for (i = 0; i < DCA_LBR_TIME_SAMPLES / 16; i++, samples += 16) {
1503 unsigned int scf = hr_scf[i];
1506 for (j = 0; j < 16; j++)
1507 samples[j] *= ff_dca_quant_amp[scf];
1510 uint8_t *g2_scf = s->grid_2_scf[ch][ff_dca_scf_to_grid_2[sb]];
1511 for (i = 0; i < DCA_LBR_TIME_SAMPLES / 2; i++, samples += 2) {
1512 unsigned int scf = hr_scf[i / 8] - g2_scf[i];
1515 samples[0] *= ff_dca_quant_amp[scf];
1516 samples[1] *= ff_dca_quant_amp[scf];
1523 float *samples_l = s->time_samples[ch1][sb];
1524 float *samples_r = s->time_samples[ch2][sb];
1525 int ch2_pres = s->ch_pres[ch2] & (1U << sb);
1527 for (i = 0; i < DCA_LBR_TIME_SAMPLES / 16; i++) {
1528 int sbms = (s->sec_ch_sbms[ch1 / 2][sb] >> i) & 1;
1529 int lrms = (s->sec_ch_lrms[ch1 / 2][sb] >> i) & 1;
1531 if (sb >= s->min_mono_subband) {
1532 if (lrms && ch2_pres) {
1534 for (j = 0; j < 16; j++) {
1535 float tmp = samples_l[j];
1536 samples_l[j] = samples_r[j];
1537 samples_r[j] = -tmp;
1540 for (j = 0; j < 16; j++) {
1541 float tmp = samples_l[j];
1542 samples_l[j] = samples_r[j];
1546 } else if (!ch2_pres) {
1547 if (sbms && (s->part_stereo_pres & (1 << ch1))) {
1548 for (j = 0; j < 16; j++)
1549 samples_r[j] = -samples_l[j];
1551 for (j = 0; j < 16; j++)
1552 samples_r[j] = samples_l[j];
1555 } else if (sbms && ch2_pres) {
1556 for (j = 0; j < 16; j++) {
1557 float tmp = samples_l[j];
1558 samples_l[j] = (tmp + samples_r[j]) * 0.5f;
1559 samples_r[j] = (tmp - samples_r[j]) * 0.5f;
1568 // Inverse prediction
1570 synth_lpc(s, ch1, ch2, sb);
1575 * Modulate by interpolated partial stereo coefficients
1577 static void decode_part_stereo(DCALbrDecoder *s, int ch1, int ch2)
1581 for (ch = ch1; ch <= ch2; ch++) {
1582 for (sb = s->min_mono_subband; sb < s->nsubbands; sb++) {
1583 uint8_t *pt_st = s->part_stereo[ch][(sb - s->min_mono_subband) / 4];
1584 float *samples = s->time_samples[ch][sb];
1586 if (s->ch_pres[ch2] & (1U << sb))
1589 for (sf = 1; sf <= 4; sf++, samples += 32) {
1590 float prev = ff_dca_st_coeff[pt_st[sf - 1]];
1591 float next = ff_dca_st_coeff[pt_st[sf ]];
1593 for (i = 0; i < 32; i++)
1594 samples[i] *= (32 - i) * prev + i * next;
1601 * Synthesise tones in the given group for the given tonal subframe
1603 static void synth_tones(DCALbrDecoder *s, int ch, float *values,
1604 int group, int group_sf, int synth_idx)
1606 int i, start, count;
1611 start = s->tonal_bounds[group][group_sf][0];
1612 count = (s->tonal_bounds[group][group_sf][1] - start) & (DCA_LBR_TONES - 1);
1614 for (i = 0; i < count; i++) {
1615 DCALbrTone *t = &s->tones[(start + i) & (DCA_LBR_TONES - 1)];
1618 float amp = ff_dca_synth_env[synth_idx] * ff_dca_quant_amp[t->amp[ch]];
1619 float c = amp * cos_tab[(t->phs[ch] ) & 255];
1620 float s = amp * cos_tab[(t->phs[ch] + 64) & 255];
1621 const float *cf = ff_dca_corr_cf[t->f_delt];
1622 int x_freq = t->x_freq;
1628 values[3] += cf[0] * -s;
1629 values[2] += cf[1] * c;
1630 values[1] += cf[2] * s;
1631 values[0] += cf[3] * -c;
1634 values[2] += cf[0] * -s;
1635 values[1] += cf[1] * c;
1636 values[0] += cf[2] * s;
1639 values[1] += cf[0] * -s;
1640 values[0] += cf[1] * c;
1643 values[0] += cf[0] * -s;
1647 values[x_freq - 5] += cf[ 0] * -s;
1648 p4: values[x_freq - 4] += cf[ 1] * c;
1649 p3: values[x_freq - 3] += cf[ 2] * s;
1650 p2: values[x_freq - 2] += cf[ 3] * -c;
1651 p1: values[x_freq - 1] += cf[ 4] * -s;
1652 p0: values[x_freq ] += cf[ 5] * c;
1653 values[x_freq + 1] += cf[ 6] * s;
1654 values[x_freq + 2] += cf[ 7] * -c;
1655 values[x_freq + 3] += cf[ 8] * -s;
1656 values[x_freq + 4] += cf[ 9] * c;
1657 values[x_freq + 5] += cf[10] * s;
1660 t->phs[ch] += t->ph_rot;
1665 * Synthesise all tones in all groups for the given residual subframe
1667 static void base_func_synth(DCALbrDecoder *s, int ch, float *values, int sf)
1671 // Tonal vs residual shift is 22 subframes
1672 for (group = 0; group < 5; group++) {
1673 int group_sf = (s->framenum << group) + ((sf - 22) >> (5 - group));
1674 int synth_idx = ((((sf - 22) & 31) << group) & 31) + (1 << group) - 1;
1676 synth_tones(s, ch, values, group, (group_sf - 1) & 31, 30 - synth_idx);
1677 synth_tones(s, ch, values, group, (group_sf ) & 31, synth_idx);
1681 static void transform_channel(DCALbrDecoder *s, int ch, float *output)
1683 LOCAL_ALIGNED_32(float, values, [DCA_LBR_SUBBANDS ], [4]);
1684 LOCAL_ALIGNED_32(float, result, [DCA_LBR_SUBBANDS * 2], [4]);
1685 int sf, sb, nsubbands = s->nsubbands, noutsubbands = 8 << s->freq_range;
1687 // Clear inactive subbands
1688 if (nsubbands < noutsubbands)
1689 memset(values[nsubbands], 0, (noutsubbands - nsubbands) * sizeof(values[0]));
1691 for (sf = 0; sf < DCA_LBR_TIME_SAMPLES / 4; sf++) {
1692 // Hybrid filterbank
1693 s->dcadsp->lbr_bank(values, s->time_samples[ch],
1694 ff_dca_bank_coeff, sf * 4, nsubbands);
1696 base_func_synth(s, ch, values[0], sf);
1698 s->imdct.imdct_calc(&s->imdct, result[0], values[0]);
1700 // Long window and overlap-add
1701 s->fdsp->vector_fmul_add(output, result[0], s->window,
1702 s->history[ch], noutsubbands * 4);
1703 s->fdsp->vector_fmul_reverse(s->history[ch], result[noutsubbands],
1704 s->window, noutsubbands * 4);
1705 output += noutsubbands * 4;
1708 // Update history for LPC and forward MDCT
1709 for (sb = 0; sb < nsubbands; sb++) {
1710 float *samples = s->time_samples[ch][sb] - DCA_LBR_TIME_HISTORY;
1711 memcpy(samples, samples + DCA_LBR_TIME_SAMPLES, DCA_LBR_TIME_HISTORY * sizeof(float));
1715 int ff_dca_lbr_filter_frame(DCALbrDecoder *s, AVFrame *frame)
1717 AVCodecContext *avctx = s->avctx;
1718 int i, ret, nchannels, ch_conf = (s->ch_mask & 0x7) - 1;
1719 const int8_t *reorder;
1721 avctx->channel_layout = channel_layouts[ch_conf];
1722 avctx->channels = nchannels = channel_counts[ch_conf];
1723 avctx->sample_rate = s->sample_rate;
1724 avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
1725 avctx->bits_per_raw_sample = 0;
1726 avctx->profile = FF_PROFILE_DTS_EXPRESS;
1727 avctx->bit_rate = s->bit_rate_scaled;
1729 if (s->flags & LBR_FLAG_LFE_PRESENT) {
1730 avctx->channel_layout |= AV_CH_LOW_FREQUENCY;
1732 reorder = channel_reorder_lfe[ch_conf];
1734 reorder = channel_reorder_nolfe[ch_conf];
1737 frame->nb_samples = 1024 << s->freq_range;
1738 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1741 // Filter fullband channels
1742 for (i = 0; i < (s->nchannels + 1) / 2; i++) {
1744 int ch2 = FFMIN(ch1 + 1, s->nchannels - 1);
1746 decode_grid(s, ch1, ch2);
1748 random_ts(s, ch1, ch2);
1750 filter_ts(s, ch1, ch2);
1752 if (ch1 != ch2 && (s->part_stereo_pres & (1 << ch1)))
1753 decode_part_stereo(s, ch1, ch2);
1755 if (ch1 < nchannels)
1756 transform_channel(s, ch1, (float *)frame->extended_data[reorder[ch1]]);
1758 if (ch1 != ch2 && ch2 < nchannels)
1759 transform_channel(s, ch2, (float *)frame->extended_data[reorder[ch2]]);
1762 // Interpolate LFE channel
1763 if (s->flags & LBR_FLAG_LFE_PRESENT) {
1764 s->dcadsp->lfe_iir((float *)frame->extended_data[lfe_index[ch_conf]],
1765 s->lfe_data, ff_dca_lfe_iir,
1766 s->lfe_history, 16 << s->freq_range);
1769 if ((ret = ff_side_data_update_matrix_encoding(frame, AV_MATRIX_ENCODING_NONE)) < 0)
1775 av_cold void ff_dca_lbr_flush(DCALbrDecoder *s)
1779 if (!s->sample_rate)
1783 memset(s->part_stereo, 16, sizeof(s->part_stereo));
1784 memset(s->lpc_coeff, 0, sizeof(s->lpc_coeff));
1785 memset(s->history, 0, sizeof(s->history));
1786 memset(s->tonal_bounds, 0, sizeof(s->tonal_bounds));
1787 memset(s->lfe_history, 0, sizeof(s->lfe_history));
1791 for (ch = 0; ch < s->nchannels; ch++) {
1792 for (sb = 0; sb < s->nsubbands; sb++) {
1793 float *samples = s->time_samples[ch][sb] - DCA_LBR_TIME_HISTORY;
1794 memset(samples, 0, DCA_LBR_TIME_HISTORY * sizeof(float));
1799 av_cold int ff_dca_lbr_init(DCALbrDecoder *s)
1803 if (!(s->fdsp = avpriv_float_dsp_alloc(0)))
1810 av_cold void ff_dca_lbr_close(DCALbrDecoder *s)
1814 av_freep(&s->ts_buffer);
1818 ff_mdct_end(&s->imdct);