LCOV - code coverage report
Current view: top level - libavcodec - dca_lbr.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 20 1009 2.0 %
Date: 2017-12-16 13:57:32 Functions: 3 40 7.5 %

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

Generated by: LCOV version 1.13