xref: /btstack/3rd-party/lc3-google/src/sns.c (revision 4a9eead824c50b40e12b6f72611a74a3f57a47f6)
1 /******************************************************************************
2  *
3  *  Copyright 2021 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #include "sns.h"
20 #include "tables.h"
21 
22 
23 /* ----------------------------------------------------------------------------
24  *  DCT-16
25  * -------------------------------------------------------------------------- */
26 
27 /**
28  * Matrix of DCT-16 coefficients
29  *
30  * M[n][k] = 2f cos( Pi k (2n + 1) / 2N )
31  *
32  *   k = [0..N-1], n = [0..N-1], N = 16
33  *   f = sqrt(1/4N) for k=0, sqrt(1/2N) otherwise
34  */
35 static const float dct16_m[16][16] = {
36 
37     {  2.50000000e-01,  3.51850934e-01,  3.46759961e-01,  3.38329500e-01,
38        3.26640741e-01,  3.11806253e-01,  2.93968901e-01,  2.73300467e-01,
39        2.50000000e-01,  2.24291897e-01,  1.96423740e-01,  1.66663915e-01,
40        1.35299025e-01,  1.02631132e-01,  6.89748448e-02,  3.46542923e-02 },
41 
42     {  2.50000000e-01,  3.38329500e-01,  2.93968901e-01,  2.24291897e-01,
43        1.35299025e-01,  3.46542923e-02, -6.89748448e-02, -1.66663915e-01,
44       -2.50000000e-01, -3.11806253e-01, -3.46759961e-01, -3.51850934e-01,
45       -3.26640741e-01, -2.73300467e-01, -1.96423740e-01, -1.02631132e-01 },
46 
47      { 2.50000000e-01,  3.11806253e-01,  1.96423740e-01,  3.46542923e-02,
48       -1.35299025e-01, -2.73300467e-01, -3.46759961e-01, -3.38329500e-01,
49       -2.50000000e-01, -1.02631132e-01,  6.89748448e-02,  2.24291897e-01,
50        3.26640741e-01,  3.51850934e-01,  2.93968901e-01,  1.66663915e-01 },
51 
52      { 2.50000000e-01,  2.73300467e-01,  6.89748448e-02, -1.66663915e-01,
53       -3.26640741e-01, -3.38329500e-01, -1.96423740e-01,  3.46542923e-02,
54        2.50000000e-01,  3.51850934e-01,  2.93968901e-01,  1.02631132e-01,
55       -1.35299025e-01, -3.11806253e-01, -3.46759961e-01, -2.24291897e-01 },
56 
57     {  2.50000000e-01,  2.24291897e-01, -6.89748448e-02, -3.11806253e-01,
58       -3.26640741e-01, -1.02631132e-01,  1.96423740e-01,  3.51850934e-01,
59        2.50000000e-01, -3.46542923e-02, -2.93968901e-01, -3.38329500e-01,
60       -1.35299025e-01,  1.66663915e-01,  3.46759961e-01,  2.73300467e-01 },
61 
62     {  2.50000000e-01,  1.66663915e-01, -1.96423740e-01, -3.51850934e-01,
63       -1.35299025e-01,  2.24291897e-01,  3.46759961e-01,  1.02631132e-01,
64       -2.50000000e-01, -3.38329500e-01, -6.89748448e-02,  2.73300467e-01,
65        3.26640741e-01,  3.46542923e-02, -2.93968901e-01, -3.11806253e-01 },
66 
67     {  2.50000000e-01,  1.02631132e-01, -2.93968901e-01, -2.73300467e-01,
68        1.35299025e-01,  3.51850934e-01,  6.89748448e-02, -3.11806253e-01,
69       -2.50000000e-01,  1.66663915e-01,  3.46759961e-01,  3.46542923e-02,
70       -3.26640741e-01, -2.24291897e-01,  1.96423740e-01,  3.38329500e-01 },
71 
72     {  2.50000000e-01,  3.46542923e-02, -3.46759961e-01, -1.02631132e-01,
73        3.26640741e-01,  1.66663915e-01, -2.93968901e-01, -2.24291897e-01,
74        2.50000000e-01,  2.73300467e-01, -1.96423740e-01, -3.11806253e-01,
75        1.35299025e-01,  3.38329500e-01, -6.89748448e-02, -3.51850934e-01 },
76 
77     {  2.50000000e-01, -3.46542923e-02, -3.46759961e-01,  1.02631132e-01,
78        3.26640741e-01, -1.66663915e-01, -2.93968901e-01,  2.24291897e-01,
79        2.50000000e-01, -2.73300467e-01, -1.96423740e-01,  3.11806253e-01,
80        1.35299025e-01, -3.38329500e-01, -6.89748448e-02,  3.51850934e-01 },
81 
82     {  2.50000000e-01, -1.02631132e-01, -2.93968901e-01,  2.73300467e-01,
83        1.35299025e-01, -3.51850934e-01,  6.89748448e-02,  3.11806253e-01,
84       -2.50000000e-01, -1.66663915e-01,  3.46759961e-01, -3.46542923e-02,
85       -3.26640741e-01,  2.24291897e-01,  1.96423740e-01, -3.38329500e-01 },
86 
87     {  2.50000000e-01, -1.66663915e-01, -1.96423740e-01,  3.51850934e-01,
88       -1.35299025e-01, -2.24291897e-01,  3.46759961e-01, -1.02631132e-01,
89       -2.50000000e-01,  3.38329500e-01, -6.89748448e-02, -2.73300467e-01,
90        3.26640741e-01, -3.46542923e-02, -2.93968901e-01,  3.11806253e-01 },
91 
92     {  2.50000000e-01, -2.24291897e-01, -6.89748448e-02,  3.11806253e-01,
93       -3.26640741e-01,  1.02631132e-01,  1.96423740e-01, -3.51850934e-01,
94        2.50000000e-01,  3.46542923e-02, -2.93968901e-01,  3.38329500e-01,
95       -1.35299025e-01, -1.66663915e-01,  3.46759961e-01, -2.73300467e-01 },
96 
97     {  2.50000000e-01, -2.73300467e-01,  6.89748448e-02,  1.66663915e-01,
98       -3.26640741e-01,  3.38329500e-01, -1.96423740e-01, -3.46542923e-02,
99        2.50000000e-01, -3.51850934e-01,  2.93968901e-01, -1.02631132e-01,
100       -1.35299025e-01,  3.11806253e-01, -3.46759961e-01,  2.24291897e-01 },
101 
102     {  2.50000000e-01, -3.11806253e-01,  1.96423740e-01, -3.46542923e-02,
103       -1.35299025e-01,  2.73300467e-01, -3.46759961e-01,  3.38329500e-01,
104       -2.50000000e-01,  1.02631132e-01,  6.89748448e-02, -2.24291897e-01,
105        3.26640741e-01, -3.51850934e-01,  2.93968901e-01, -1.66663915e-01 },
106 
107     {  2.50000000e-01, -3.38329500e-01,  2.93968901e-01, -2.24291897e-01,
108        1.35299025e-01, -3.46542923e-02, -6.89748448e-02,  1.66663915e-01,
109       -2.50000000e-01,  3.11806253e-01, -3.46759961e-01,  3.51850934e-01,
110       -3.26640741e-01,  2.73300467e-01, -1.96423740e-01,  1.02631132e-01 },
111 
112     {  2.50000000e-01, -3.51850934e-01,  3.46759961e-01, -3.38329500e-01,
113        3.26640741e-01, -3.11806253e-01,  2.93968901e-01, -2.73300467e-01,
114        2.50000000e-01, -2.24291897e-01,  1.96423740e-01, -1.66663915e-01,
115        1.35299025e-01, -1.02631132e-01,  6.89748448e-02, -3.46542923e-02 },
116 
117 };
118 
119 /**
120  * Forward DCT-16 transformation
121  * x, y            Input and output 16 values
122  */
123 static void dct16_forward(const float *x, float *y)
124 {
125     for (int i = 0, j; i < 16; i++)
126         for (y[i] = 0, j = 0; j < 16; j++)
127             y[i] += x[j] * dct16_m[j][i];
128 }
129 
130 /**
131  * Inverse DCT-16 transformation
132  * x, y            Input and output 16 values
133  */
134 static void dct16_inverse(const float *x, float *y)
135 {
136     for (int i = 0, j; i < 16; i++)
137         for (y[i] = 0, j = 0; j < 16; j++)
138             y[i] += x[j] * dct16_m[i][j];
139 }
140 
141 
142 /* ----------------------------------------------------------------------------
143  *  Scale factors
144  * -------------------------------------------------------------------------- */
145 
146 /**
147  * Scale factors
148  * dt, sr          Duration and samplerate of the frame
149  * eb              Energy estimation per bands
150  * att             1: Attack detected  0: Otherwise
151  * scf             Output 16 scale factors
152  */
153 static void compute_scale_factors(enum lc3_dt dt, enum lc3_srate sr,
154     const float *eb, bool att, float *scf)
155 {
156     /* Pre-emphasis gain table :
157      * Ge[b] = 10 ^ (b * g_tilt) / 630 , b = [0..63] */
158 
159     static const float ge_table[LC3_NUM_SRATE][LC3_NUM_BANDS] = {
160 
161         [LC3_SRATE_8K] = { /* g_tilt = 14 */
162             1.00000000e+00, 1.05250029e+00, 1.10775685e+00, 1.16591440e+00,
163             1.22712524e+00, 1.29154967e+00, 1.35935639e+00, 1.43072299e+00,
164             1.50583635e+00, 1.58489319e+00, 1.66810054e+00, 1.75567629e+00,
165             1.84784980e+00, 1.94486244e+00, 2.04696827e+00, 2.15443469e+00,
166             2.26754313e+00, 2.38658979e+00, 2.51188643e+00, 2.64376119e+00,
167             2.78255940e+00, 2.92864456e+00, 3.08239924e+00, 3.24422608e+00,
168             3.41454887e+00, 3.59381366e+00, 3.78248991e+00, 3.98107171e+00,
169             4.19007911e+00, 4.41005945e+00, 4.64158883e+00, 4.88527357e+00,
170             5.14175183e+00, 5.41169527e+00, 5.69581081e+00, 5.99484250e+00,
171             6.30957344e+00, 6.64082785e+00, 6.98947321e+00, 7.35642254e+00,
172             7.74263683e+00, 8.14912747e+00, 8.57695899e+00, 9.02725178e+00,
173             9.50118507e+00, 1.00000000e+01, 1.05250029e+01, 1.10775685e+01,
174             1.16591440e+01, 1.22712524e+01, 1.29154967e+01, 1.35935639e+01,
175             1.43072299e+01, 1.50583635e+01, 1.58489319e+01, 1.66810054e+01,
176             1.75567629e+01, 1.84784980e+01, 1.94486244e+01, 2.04696827e+01,
177             2.15443469e+01, 2.26754313e+01, 2.38658979e+01, 2.51188643e+01 },
178 
179         [LC3_SRATE_16K] = { /* g_tilt = 18 */
180             1.00000000e+00, 1.06800043e+00, 1.14062492e+00, 1.21818791e+00,
181             1.30102522e+00, 1.38949549e+00, 1.48398179e+00, 1.58489319e+00,
182             1.69266662e+00, 1.80776868e+00, 1.93069773e+00, 2.06198601e+00,
183             2.20220195e+00, 2.35195264e+00, 2.51188643e+00, 2.68269580e+00,
184             2.86512027e+00, 3.05994969e+00, 3.26802759e+00, 3.49025488e+00,
185             3.72759372e+00, 3.98107171e+00, 4.25178630e+00, 4.54090961e+00,
186             4.84969343e+00, 5.17947468e+00, 5.53168120e+00, 5.90783791e+00,
187             6.30957344e+00, 6.73862717e+00, 7.19685673e+00, 7.68624610e+00,
188             8.20891416e+00, 8.76712387e+00, 9.36329209e+00, 1.00000000e+01,
189             1.06800043e+01, 1.14062492e+01, 1.21818791e+01, 1.30102522e+01,
190             1.38949549e+01, 1.48398179e+01, 1.58489319e+01, 1.69266662e+01,
191             1.80776868e+01, 1.93069773e+01, 2.06198601e+01, 2.20220195e+01,
192             2.35195264e+01, 2.51188643e+01, 2.68269580e+01, 2.86512027e+01,
193             3.05994969e+01, 3.26802759e+01, 3.49025488e+01, 3.72759372e+01,
194             3.98107171e+01, 4.25178630e+01, 4.54090961e+01, 4.84969343e+01,
195             5.17947468e+01, 5.53168120e+01, 5.90783791e+01, 6.30957344e+01 },
196 
197         [LC3_SRATE_24K] = { /* g_tilt = 22 */
198             1.00000000e+00, 1.08372885e+00, 1.17446822e+00, 1.27280509e+00,
199             1.37937560e+00, 1.49486913e+00, 1.62003281e+00, 1.75567629e+00,
200             1.90267705e+00, 2.06198601e+00, 2.23463373e+00, 2.42173704e+00,
201             2.62450630e+00, 2.84425319e+00, 3.08239924e+00, 3.34048498e+00,
202             3.62017995e+00, 3.92329345e+00, 4.25178630e+00, 4.60778348e+00,
203             4.99358789e+00, 5.41169527e+00, 5.86481029e+00, 6.35586411e+00,
204             6.88803330e+00, 7.46476041e+00, 8.08977621e+00, 8.76712387e+00,
205             9.50118507e+00, 1.02967084e+01, 1.11588399e+01, 1.20931568e+01,
206             1.31057029e+01, 1.42030283e+01, 1.53922315e+01, 1.66810054e+01,
207             1.80776868e+01, 1.95913107e+01, 2.12316686e+01, 2.30093718e+01,
208             2.49359200e+01, 2.70237760e+01, 2.92864456e+01, 3.17385661e+01,
209             3.43959997e+01, 3.72759372e+01, 4.03970086e+01, 4.37794036e+01,
210             4.74450028e+01, 5.14175183e+01, 5.57226480e+01, 6.03882412e+01,
211             6.54444792e+01, 7.09240702e+01, 7.68624610e+01, 8.32980665e+01,
212             9.02725178e+01, 9.78309319e+01, 1.06022203e+02, 1.14899320e+02,
213             1.24519708e+02, 1.34945600e+02, 1.46244440e+02, 1.58489319e+02 },
214 
215         [LC3_SRATE_32K] = { /* g_tilt = 26 */
216             1.00000000e+00, 1.09968890e+00, 1.20931568e+00, 1.32987103e+00,
217             1.46244440e+00, 1.60823388e+00, 1.76855694e+00, 1.94486244e+00,
218             2.13874364e+00, 2.35195264e+00, 2.58641621e+00, 2.84425319e+00,
219             3.12779366e+00, 3.43959997e+00, 3.78248991e+00, 4.15956216e+00,
220             4.57422434e+00, 5.03022373e+00, 5.53168120e+00, 6.08312841e+00,
221             6.68954879e+00, 7.35642254e+00, 8.08977621e+00, 8.89623710e+00,
222             9.78309319e+00, 1.07583590e+01, 1.18308480e+01, 1.30102522e+01,
223             1.43072299e+01, 1.57335019e+01, 1.73019574e+01, 1.90267705e+01,
224             2.09235283e+01, 2.30093718e+01, 2.53031508e+01, 2.78255940e+01,
225             3.05994969e+01, 3.36499270e+01, 3.70044512e+01, 4.06933843e+01,
226             4.47500630e+01, 4.92111475e+01, 5.41169527e+01, 5.95118121e+01,
227             6.54444792e+01, 7.19685673e+01, 7.91430346e+01, 8.70327166e+01,
228             9.57089124e+01, 1.05250029e+02, 1.15742288e+02, 1.27280509e+02,
229             1.39968963e+02, 1.53922315e+02, 1.69266662e+02, 1.86140669e+02,
230             2.04696827e+02, 2.25102829e+02, 2.47543082e+02, 2.72220379e+02,
231             2.99357729e+02, 3.29200372e+02, 3.62017995e+02, 3.98107171e+02 },
232 
233         [LC3_SRATE_48K] = { /* g_tilt = 30 */
234             1.00000000e+00, 1.11588399e+00, 1.24519708e+00, 1.38949549e+00,
235             1.55051578e+00, 1.73019574e+00, 1.93069773e+00, 2.15443469e+00,
236             2.40409918e+00, 2.68269580e+00, 2.99357729e+00, 3.34048498e+00,
237             3.72759372e+00, 4.15956216e+00, 4.64158883e+00, 5.17947468e+00,
238             5.77969288e+00, 6.44946677e+00, 7.19685673e+00, 8.03085722e+00,
239             8.96150502e+00, 1.00000000e+01, 1.11588399e+01, 1.24519708e+01,
240             1.38949549e+01, 1.55051578e+01, 1.73019574e+01, 1.93069773e+01,
241             2.15443469e+01, 2.40409918e+01, 2.68269580e+01, 2.99357729e+01,
242             3.34048498e+01, 3.72759372e+01, 4.15956216e+01, 4.64158883e+01,
243             5.17947468e+01, 5.77969288e+01, 6.44946677e+01, 7.19685673e+01,
244             8.03085722e+01, 8.96150502e+01, 1.00000000e+02, 1.11588399e+02,
245             1.24519708e+02, 1.38949549e+02, 1.55051578e+02, 1.73019574e+02,
246             1.93069773e+02, 2.15443469e+02, 2.40409918e+02, 2.68269580e+02,
247             2.99357729e+02, 3.34048498e+02, 3.72759372e+02, 4.15956216e+02,
248             4.64158883e+02, 5.17947468e+02, 5.77969288e+02, 6.44946677e+02,
249             7.19685673e+02, 8.03085722e+02, 8.96150502e+02, 1.00000000e+03 },
250     };
251 
252     float e[LC3_NUM_BANDS];
253 
254     /* --- Copy and padding --- */
255 
256     int nb = LC3_MIN(lc3_band_lim[dt][sr][LC3_NUM_BANDS], LC3_NUM_BANDS);
257     int n2 = LC3_NUM_BANDS - nb;
258 
259     for (int i2 = 0; i2 < n2; i2++)
260         e[2*i2 + 0] = e[2*i2 + 1] = eb[i2];
261 
262     memcpy(e + 2*n2, eb + n2, (nb - n2) * sizeof(float));
263 
264     /* --- Smoothing, pre-emphasis and logarithm --- */
265 
266     const float *ge = ge_table[sr];
267 
268     float e0 = e[0], e1 = e[0], e2;
269     float e_sum = 0;
270 
271     for (int i = 0; i < LC3_NUM_BANDS-1; ) {
272         e[i] = (e0 * 0.25 + e1 * 0.5 + (e2 = e[i+1]) * 0.25) * ge[i];
273         e_sum += e[i++];
274 
275         e[i] = (e1 * 0.25 + e2 * 0.5 + (e0 = e[i+1]) * 0.25) * ge[i];
276         e_sum += e[i++];
277 
278         e[i] = (e2 * 0.25 + e0 * 0.5 + (e1 = e[i+1]) * 0.25) * ge[i];
279         e_sum += e[i++];
280     }
281 
282     e[LC3_NUM_BANDS-1] = (e0 * 0.25 + e1 * 0.75) * ge[LC3_NUM_BANDS-1];
283     e_sum += e[LC3_NUM_BANDS-1];
284 
285     float noise_floor = fmaxf(e_sum * (1e-4 / 64), 0x1p-32);
286 
287     for (int i = 0; i < LC3_NUM_BANDS; i++)
288         e[i] = log2f(fmaxf(e[i], noise_floor)) * 0.5;
289 
290     /* --- Grouping & scaling --- */
291 
292     float scf_sum;
293 
294     scf[0] = (e[0] + e[4]) * 1./12 +
295              (e[0] + e[3]) * 2./12 +
296              (e[1] + e[2]) * 3./12  ;
297     scf_sum = scf[0];
298 
299     for (int i = 1; i < 15; i++) {
300         scf[i] = (e[4*i-1] + e[4*i+4]) * 1./12 +
301                  (e[4*i  ] + e[4*i+3]) * 2./12 +
302                  (e[4*i+1] + e[4*i+2]) * 3./12  ;
303         scf_sum += scf[i];
304     }
305 
306     scf[15] = (e[59] + e[63]) * 1./12 +
307               (e[60] + e[63]) * 2./12 +
308               (e[61] + e[62]) * 3./12  ;
309     scf_sum += scf[15];
310 
311     for (int i = 0; i < 16; i++)
312         scf[i] = 0.85 * (scf[i] - scf_sum * 1./16);
313 
314     /* --- Attack handling --- */
315 
316     if (!att)
317         return;
318 
319     float s0, s1 = scf[0], s2 = scf[1], s3 = scf[2], s4 = scf[3];
320     float sn = s1 + s2;
321 
322     scf[0] = (sn += s3) * 1./3;
323     scf[1] = (sn += s4) * 1./4;
324     scf_sum = scf[0] + scf[1];
325 
326     for (int i = 2; i < 14; i++, sn -= s0) {
327         s0 = s1, s1 = s2, s2 = s3, s3 = s4, s4 = scf[i+2];
328         scf[i] = (sn += s4) * 1./5;
329         scf_sum += scf[i];
330     }
331 
332     scf[14] = (sn      ) * 1./4;
333     scf[15] = (sn -= s1) * 1./3;
334     scf_sum += scf[14] + scf[15];
335 
336     for (int i = 0; i < 16; i++)
337         scf[i] = (dt == LC3_DT_7M5 ? 0.3 : 0.5) *
338                  (scf[i] - scf_sum * 1./16);
339 }
340 
341 /**
342  * Codebooks
343  * scf             Input 16 scale factors
344  * lf/hfcb_idx     Output the low and high frequency codebooks index
345  */
346 static void resolve_codebooks(const float *scf, int *lfcb_idx, int *hfcb_idx)
347 {
348     float dlfcb_max = 0, dhfcb_max = 0;
349     *lfcb_idx = *hfcb_idx = 0;
350 
351     for (int icb = 0; icb < 32; icb++) {
352         const float *lfcb = lc3_sns_lfcb[icb];
353         const float *hfcb = lc3_sns_hfcb[icb];
354         float dlfcb = 0, dhfcb = 0;
355 
356         for (int i = 0; i < 8; i++) {
357             dlfcb += (scf[  i] - lfcb[i]) * (scf[  i] - lfcb[i]);
358             dhfcb += (scf[8+i] - hfcb[i]) * (scf[8+i] - hfcb[i]);
359         }
360 
361         if (icb == 0 || dlfcb < dlfcb_max)
362             *lfcb_idx = icb, dlfcb_max = dlfcb;
363 
364         if (icb == 0 || dhfcb < dhfcb_max)
365             *hfcb_idx = icb, dhfcb_max = dhfcb;
366     }
367 }
368 
369 /**
370  * Unit energy normalize pulse configuration
371  * c               Pulse configuration
372  * cn              Normalized pulse configuration
373  */
374 static void normalize(const int *c, float *cn)
375 {
376     int c2_sum = 0;
377     for (int i = 0; i < 16; i++)
378         c2_sum += c[i] * c[i];
379 
380     float c_norm = 1.f / sqrtf(c2_sum);
381 
382     for (int i = 0; i < 16; i++)
383         cn[i] = c[i] * c_norm;
384 }
385 
386 /**
387  * Sub-procedure of `quantize()`, add unit pulse
388  * x, y, n         Transformed residual, and vector of pulses with length
389  * start, end      Current number of pulses, limit to reach
390  * corr, energy    Correlation (x,y) and y energy, updated at output
391  */
392 static void add_pulse(const float *x, int *y, int n,
393     int start, int end, float *corr, float *energy)
394 {
395     for (int k = start; k < end; k++) {
396         float best_c2 = (*corr + x[0]) * (*corr + x[0]);
397         float best_e = *energy + 2*y[0] + 1;
398         int nbest = 0;
399 
400         for (int i = 1; i < n; i++) {
401             float c2 = (*corr + x[i]) * (*corr + x[i]);
402             float e  = *energy + 2*y[i] + 1;
403 
404             if (c2 * best_e > e * best_c2)
405                 best_c2 = c2, best_e = e, nbest = i;
406         }
407 
408         *corr += x[nbest];
409         *energy += 2*y[nbest] + 1;
410         y[nbest]++;
411     }
412 }
413 
414 /**
415  * Quantization of codebooks residual
416  * scf             Input 16 scale factors, output quantized version
417  * lf/hfcb_idx     Codebooks index
418  * c, cn           Output 4 pulse configurations candidates, normalized
419  * shape/gain_idx  Output selected shape/gain indexes
420  */
421 static void quantize(const float *scf, int lfcb_idx, int hfcb_idx,
422     int (*c)[16], float (*cn)[16], int *shape_idx, int *gain_idx)
423 {
424     /* --- Residual --- */
425 
426     const float *lfcb = lc3_sns_lfcb[lfcb_idx];
427     const float *hfcb = lc3_sns_hfcb[hfcb_idx];
428     float r[16], x[16];
429 
430     for (int i = 0; i < 8; i++) {
431         r[  i] = scf[  i] - lfcb[i];
432         r[8+i] = scf[8+i] - hfcb[i];
433     }
434 
435     dct16_forward(r, x);
436 
437     /* --- Shape 3 candidate ---
438      * Project to or below pyramid N = 16, K = 6,
439      * then add unit pulses until you reach K = 6, over N = 16 */
440 
441     float xm[16];
442     float xm_sum = 0;
443 
444     for (int i = 0; i < 16; i++) {
445         xm[i] = fabsf(x[i]);
446         xm_sum += xm[i];
447     }
448 
449     float proj_factor = (6 - 1) / fmaxf(xm_sum, 1e-31);
450     float corr = 0, energy = 0;
451     int npulses = 0;
452 
453     for (int i = 0; i < 16; i++) {
454         c[3][i] = floorf(xm[i] * proj_factor);
455         npulses += c[3][i];
456         corr    += c[3][i] * xm[i];
457         energy  += c[3][i] * c[3][i];
458     }
459 
460     add_pulse(xm, c[3], 16, npulses, 6, &corr, &energy);
461     npulses = 6;
462 
463     /* --- Shape 2 candidate ---
464      * Add unit pulses until you reach K = 8 on shape 3 */
465 
466     memcpy(c[2], c[3], sizeof(c[2]));
467 
468     add_pulse(xm, c[2], 16, npulses, 8, &corr, &energy);
469     npulses = 8;
470 
471     /* --- Shape 1 candidate ---
472      * Remove any unit pulses from shape 2 that are not part of 0 to 9
473      * Update energy and correlation terms accordingly
474      * Add unit pulses until you reach K = 10, over N = 10 */
475 
476     memcpy(c[1], c[2], sizeof(c[1]));
477 
478     for (int i = 10; i < 16; i++) {
479         c[1][i] = 0;
480         npulses -= c[2][i];
481         corr    -= c[2][i] * xm[i];
482         energy  -= c[2][i] * c[2][i];
483     }
484 
485     add_pulse(xm, c[1], 10, npulses, 10, &corr, &energy);
486     npulses = 10;
487 
488     /* --- Shape 0 candidate ---
489      * Add unit pulses until you reach K = 1, on shape 1 */
490 
491     memcpy(c[0], c[1], sizeof(c[0]));
492 
493     add_pulse(xm + 10, c[0] + 10, 6, 0, 1, &corr, &energy);
494 
495     /* --- Add sign and unit energy normalize --- */
496 
497     for (int j = 0; j < 16; j++)
498         for (int i = 0; i < 4; i++)
499             c[i][j] = x[j] < 0 ? -c[i][j] : c[i][j];
500 
501     for (int i = 0; i < 4; i++)
502         normalize(c[i], cn[i]);
503 
504     /* --- Determe shape & gain index ---
505      * Search the Mean Square Error, within (shape, gain) combinations */
506 
507     float mse_min = INFINITY;
508     *shape_idx = *gain_idx = 0;
509 
510     for (int ic = 0; ic < 4; ic++) {
511         const struct lc3_sns_vq_gains *cgains = lc3_sns_vq_gains + ic;
512         float cmse_min = INFINITY;
513         int cgain_idx = 0;
514 
515         for (int ig = 0; ig < cgains->count; ig++) {
516             float g = cgains->v[ig];
517 
518             float mse = 0;
519             for (int i = 0; i < 16; i++)
520                 mse += (x[i] - g * cn[ic][i]) * (x[i] - g * cn[ic][i]);
521 
522             if (mse < cmse_min) {
523                 cgain_idx = ig,
524                 cmse_min = mse;
525             }
526         }
527 
528         if (cmse_min < mse_min) {
529             *shape_idx = ic, *gain_idx = cgain_idx;
530             mse_min = cmse_min;
531         }
532     }
533 }
534 
535 /**
536  * Unquantization of codebooks residual
537  * lf/hfcb_idx     Low and high frequency codebooks index
538  * c               Table of normalized pulse configuration
539  * shape/gain      Selected shape/gain indexes
540  * scf             Return unquantized scale factors
541  */
542 static void unquantize(int lfcb_idx, int hfcb_idx,
543     const float *c, int shape, int gain, float *scf)
544 {
545     const float *lfcb = lc3_sns_lfcb[lfcb_idx];
546     const float *hfcb = lc3_sns_hfcb[hfcb_idx];
547     float g = lc3_sns_vq_gains[shape].v[gain];
548 
549     dct16_inverse(c, scf);
550 
551     for (int i = 0; i < 8; i++)
552         scf[i] = lfcb[i] + g * scf[i];
553 
554     for (int i = 8; i < 16; i++)
555         scf[i] = hfcb[i-8] + g * scf[i];
556 }
557 
558 /**
559  * Sub-procedure of `sns_enumerate()`, enumeration of a vector
560  * c, n            Table of pulse configuration, and length
561  * idx, ls         Return enumeration set
562  */
563 static void enum_mvpq(const int *c, int n, int *idx, bool *ls)
564 {
565     int ci, i, j;
566 
567     /* --- Scan for 1st significant coeff --- */
568 
569     for (i = 0, c += n; (ci = *(--c)) == 0 ; i++);
570 
571     *idx = 0;
572     *ls = ci < 0;
573 
574     /* --- Scan remaining coefficients --- */
575 
576     for (i++, j = LC3_ABS(ci); i < n; i++, j += LC3_ABS(ci)) {
577 
578         if ((ci = *(--c)) != 0) {
579             *idx = (*idx << 1) | *ls;
580             *ls = ci < 0;
581         }
582 
583         *idx += lc3_sns_mpvq_offsets[i][j];
584     }
585 }
586 
587 /**
588  * Sub-procedure of `sns_deenumerate()`, deenumeration of a vector
589  * idx, ls         Enumeration set
590  * npulses         Number of pulses in the set
591  * c, n            Table of pulses configuration, and length
592  */
593 static void deenum_mvpq(int idx, bool ls, int npulses, int *c, int n)
594 {
595     int i;
596 
597     /* --- Scan for coefficients --- */
598 
599     for (i = n-1; i >= 0 && idx; i--) {
600 
601         int ci = 0;
602 
603         for (ci = 0; idx < lc3_sns_mpvq_offsets[i][npulses - ci]; ci++);
604         idx -= lc3_sns_mpvq_offsets[i][npulses - ci];
605 
606         *(c++) = ls ? -ci : ci;
607         npulses -= ci;
608         if (ci > 0) {
609             ls = idx & 1;
610             idx >>= 1;
611         }
612     }
613 
614     /* --- Set last significant --- */
615 
616     int ci = npulses;
617 
618     if (i-- >= 0)
619         *(c++) = ls ? -ci : ci;
620 
621     while (i-- >= 0)
622         *(c++) = 0;
623 }
624 
625 /**
626  * SNS Enumeration of PVQ configuration
627  * shape           Selected shape index
628  * c               Selected pulse configuration
629  * idx_a, ls_a     Return enumeration set A
630  * idx_b, ls_b     Return enumeration set B (shape = 0)
631  */
632 static void enumerate(int shape, const int *c,
633     int *idx_a, bool *ls_a, int *idx_b, bool *ls_b)
634 {
635     enum_mvpq(c, shape < 2 ? 10 : 16, idx_a, ls_a);
636 
637     if (shape == 0)
638         enum_mvpq(c + 10, 6, idx_b, ls_b);
639 }
640 
641 /**
642  * SNS Deenumeration of PVQ configuration
643  * shape           Selected shape index
644  * idx_a, ls_a     enumeration set A
645  * idx_b, ls_b     enumeration set B (shape = 0)
646  * c               Return pulse configuration
647  */
648 static void deenumerate(int shape,
649     int idx_a, bool ls_a, int idx_b, bool ls_b, int *c)
650 {
651     int npulses_a = (const int []){ 10, 10, 8, 6 }[shape];
652 
653     deenum_mvpq(idx_a, ls_a, npulses_a, c, shape < 2 ? 10 : 16);
654 
655     if (shape == 0)
656         deenum_mvpq(idx_b, ls_b, 1, c + 10, 6);
657     else if (shape == 1)
658         memset(c + 10, 0, 6 * sizeof(*c));
659 }
660 
661 
662 /* ----------------------------------------------------------------------------
663  *  Filtering
664  * -------------------------------------------------------------------------- */
665 
666 /**
667  * Spectral shaping
668  * dt, sr          Duration and samplerate of the frame
669  * scf_q           Quantized scale factors
670  * inv             True on inverse shaping, False otherwise
671  * x               Spectral coefficients
672  * y               Return shapped coefficients
673  *
674  * `x` and `y` can be the same buffer
675  */
676 static void spectral_shaping(enum lc3_dt dt, enum lc3_srate sr,
677     const float *scf_q, bool inv, const float *x, float *y)
678 {
679     /* --- Interpolate scale factors --- */
680 
681     float scf[LC3_NUM_BANDS];
682     float s0, s1 = inv ? -scf_q[0] : scf_q[0];
683 
684     scf[0] = scf[1] = s1;
685     for (int i = 0; i < 15; i++) {
686         s0 = s1, s1 = inv ? -scf_q[i+1] : scf_q[i+1];
687         scf[4*i+2] = s0 + 0.125 * (s1 - s0);
688         scf[4*i+3] = s0 + 0.375 * (s1 - s0);
689         scf[4*i+4] = s0 + 0.625 * (s1 - s0);
690         scf[4*i+5] = s0 + 0.875 * (s1 - s0);
691     }
692     scf[62] = s1 + 0.125 * (s1 - s0);
693     scf[63] = s1 + 0.375 * (s1 - s0);
694 
695     int nb = LC3_MIN(lc3_band_lim[dt][sr][LC3_NUM_BANDS], LC3_NUM_BANDS);
696     int n2 = LC3_NUM_BANDS - nb;
697 
698     for (int i2 = 0; i2 < n2; i2++)
699         scf[i2] = 0.5 * (scf[2*i2] + scf[2*i2+1]);
700 
701     if (n2 > 0)
702         memmove(scf + n2, scf + 2*n2, (nb - n2) * sizeof(float));
703 
704     /* --- Spectral shaping --- */
705 
706     const int *lim = lc3_band_lim[dt][sr];
707 
708     for (int i = 0, ib = 0; ib < nb; ib++) {
709         float g_sns = powf(2, -scf[ib]);
710 
711         for ( ; i < lim[ib+1]; i++)
712             y[i] = x[i] * g_sns;
713     }
714 }
715 
716 
717 /* ----------------------------------------------------------------------------
718  *  Interface
719  * -------------------------------------------------------------------------- */
720 
721 /**
722  * SNS analysis
723  */
724 void lc3_sns_analyze(enum lc3_dt dt, enum lc3_srate sr,
725     const float *eb, bool att, struct lc3_sns_data *data,
726     const float *x, float *y)
727 {
728     /* Processing steps :
729      * - Determine 16 scale factors from bands energy estimation
730      * - Get codebooks indexes that match thoses scale factors
731      * - Quantize the residual with the selected codebook
732      * - The pulse configuration `c[]` is enumerated
733      * - Finally shape the spectrum coefficients accordingly */
734 
735     float scf[16], cn[4][16];
736     int c[4][16];
737 
738     compute_scale_factors(dt, sr, eb, att, scf);
739 
740     resolve_codebooks(scf, &data->lfcb, &data->hfcb);
741 
742     quantize(scf, data->lfcb, data->hfcb,
743         c, cn, &data->shape, &data->gain);
744 
745     unquantize(data->lfcb, data->hfcb,
746         cn[data->shape], data->shape, data->gain, scf);
747 
748     enumerate(data->shape, c[data->shape],
749         &data->idx_a, &data->ls_a, &data->idx_b, &data->ls_b);
750 
751     spectral_shaping(dt, sr, scf, false, x, y);
752 }
753 
754 /**
755  * SNS synthesis
756  */
757 void lc3_sns_synthesize(enum lc3_dt dt, enum lc3_srate sr,
758     const lc3_sns_data_t *data, const float *x, float *y)
759 {
760     float scf[16], cn[16];
761     int c[16];
762 
763     deenumerate(data->shape,
764         data->idx_a, data->ls_a, data->idx_b, data->ls_b, c);
765 
766     normalize(c, cn);
767 
768     unquantize(data->lfcb, data->hfcb, cn, data->shape, data->gain, scf);
769 
770     spectral_shaping(dt, sr, scf, true, x, y);
771 }
772 
773 /**
774  * Return number of bits coding the bitstream data
775  */
776 int lc3_sns_get_nbits(void)
777 {
778     return 38;
779 }
780 
781 /**
782  * Put bitstream data
783  */
784 void lc3_sns_put_data(lc3_bits_t *bits, const struct lc3_sns_data *data)
785 {
786     /* --- Codebooks --- */
787 
788     lc3_put_bits(bits, data->lfcb, 5);
789     lc3_put_bits(bits, data->hfcb, 5);
790 
791     /* --- Shape, gain and vectors --- *
792      * Write MSB bit of shape index, next LSB bits of shape and gain,
793      * and MVPQ vectors indexes are muxed */
794 
795     int shape_msb = data->shape >> 1;
796     lc3_put_bit(bits, shape_msb);
797 
798     if (shape_msb == 0) {
799         const int size_a = 2390004;
800         int submode = data->shape & 1;
801 
802         int mux_high = submode == 0 ?
803             2 * (data->idx_b + 1) + data->ls_b : data->gain & 1;
804         int mux_code = mux_high * size_a + data->idx_a;
805 
806         lc3_put_bits(bits, data->gain >> submode, 1);
807         lc3_put_bits(bits, data->ls_a, 1);
808         lc3_put_bits(bits, mux_code, 25);
809 
810     } else {
811         const int size_a = 15158272;
812         int submode = data->shape & 1;
813 
814         int mux_code = submode == 0 ?
815             data->idx_a : size_a + 2 * data->idx_a + (data->gain & 1);
816 
817         lc3_put_bits(bits, data->gain >> submode, 2);
818         lc3_put_bits(bits, data->ls_a, 1);
819         lc3_put_bits(bits, mux_code, 24);
820     }
821 }
822 
823 /**
824  * Get bitstream data
825  */
826 int lc3_sns_get_data(lc3_bits_t *bits, struct lc3_sns_data *data)
827 {
828     /* --- Codebooks --- */
829 
830     *data = (struct lc3_sns_data){
831         .lfcb = lc3_get_bits(bits, 5),
832         .hfcb = lc3_get_bits(bits, 5)
833     };
834 
835     /* --- Shape, gain and vectors --- */
836 
837     int shape_msb = lc3_get_bit(bits);
838     data->gain = lc3_get_bits(bits, 1 + shape_msb);
839     data->ls_a = lc3_get_bit(bits);
840 
841     int mux_code = lc3_get_bits(bits, 25 - shape_msb);
842 
843     if (shape_msb == 0) {
844         const int size_a = 2390004;
845 
846         if (mux_code >= size_a * 14)
847             return -1;
848 
849         data->idx_a = mux_code % size_a;
850         mux_code = mux_code / size_a;
851 
852         data->shape = (mux_code < 2);
853 
854         if (data->shape == 0) {
855             data->idx_b = (mux_code - 2) / 2;
856             data->ls_b  = (mux_code - 2) % 2;
857         } else {
858             data->gain = (data->gain << 1) + (mux_code % 2);
859         }
860 
861     } else {
862         const int size_a = 15158272;
863 
864         if (mux_code >= size_a + 1549824)
865             return -1;
866 
867         data->shape = 2 + (mux_code >= size_a);
868         if (data->shape == 2) {
869             data->idx_a = mux_code;
870         } else {
871             mux_code -= size_a;
872             data->idx_a = mux_code / 2;
873             data->gain = (data->gain << 1) + (mux_code % 2);
874         }
875     }
876 
877     return 0;
878 }
879