xref: /btstack/3rd-party/lc3-google/src/spec.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 "spec.h"
20 #include "bits.h"
21 #include "tables.h"
22 
23 
24 /* ----------------------------------------------------------------------------
25  *  Global Gain / Quantization
26  * -------------------------------------------------------------------------- */
27 
28 /**
29  * Resolve quantized gain index offset
30  * sr, nbytes      Samplerate and size of the frame
31  * return          Gain index offset
32  */
33 static int resolve_gain_offset(enum lc3_srate sr, int nbytes)
34 {
35     int g_off = (nbytes * 8) / (10 * (1 + sr));
36     return 105 + 5*(1 + sr) + LC3_MIN(g_off, 115);
37 }
38 
39 /**
40  * Global Gain Estimation
41  * dt, sr          Duration and samplerate of the frame
42  * x               Spectral coefficients
43  * nbits_budget    Number of bits available coding the spectrum
44  * nbits_off       Offset on the available bits, temporarily smoothed
45  * g_off           Gain index offset
46  * reset_off       Return True when the nbits_off must be reset
47  * return          The quantized gain value
48  */
49 static int estimate_gain(
50     enum lc3_dt dt, enum lc3_srate sr, const float *x,
51     int nbits_budget, float nbits_off, int g_off, bool *reset_off)
52 {
53     int ne = LC3_NE(dt, sr) >> 2;
54     float e[ne];
55 
56     /* --- Energy (dB) by 4 NDCT blocks ---
57      * For the next steps, add energy offset 28/20 dB,
58      * and compute the maximum magnitude */
59 
60     float x_max = 0;
61 
62     for (int i = 0; i < ne; i++, x += 4) {
63         float x0 = fabsf(x[0]), x1 = fabsf(x[1]);
64         float x2 = fabsf(x[2]), x3 = fabsf(x[3]);
65 
66         x_max = fmaxf(x_max, x0);
67         x_max = fmaxf(x_max, x1);
68         x_max = fmaxf(x_max, x2);
69         x_max = fmaxf(x_max, x3);
70 
71         float s2 = x0*x0 + x1*x1 + x2*x2 + x3*x3;
72         e[i] = 28.f/20 * 10 * (s2 > 0 ? log10f(s2) : -10);
73     }
74 
75     /* --- Determine gain index --- */
76 
77     int nbits = nbits_budget + nbits_off + 0.5f;
78     int g_int = 255 - g_off;
79 
80     for (int i = 128; i > 0; i >>= 1) {
81         const float *e_ptr = e + ne-1;
82         float v = 0;
83 
84         g_int -= i;
85 
86         for ( ; e_ptr >= e && *e_ptr < g_int; e_ptr--);
87 
88         while (e_ptr >= e) {
89             float e_diff = *(e_ptr--) - g_int;
90 
91             if (e_diff < 0) {
92                 v += 2.7f * 28.f/20;
93             } else {
94                 v += e_diff + 7 * 28.f/20;
95                 if (e_diff > 43 * 28.f/20)
96                     v += e_diff - 43 * 28.f/20;
97             }
98         }
99 
100         if (v > nbits * 1.4 * 28./20)
101             g_int += i;
102     }
103 
104     /* --- Limit gain index --- */
105 
106     int g_min = x_max == 0 ? -g_off :
107         ceilf(28 * log10f(x_max / (32768 - 0.375f)));
108 
109     *reset_off = g_int < g_min || x_max == 0;
110     if (*reset_off)
111         g_int = g_min;
112 
113     return g_int;
114 }
115 
116 /**
117  * Global Gain Adjustment
118  * sr              Samplerate of the frame
119  * g_idx           The estimated quantized gain index
120  * nbits           Computed number of bits coding the spectrum
121  * nbits_budget    Number of bits available for coding the spectrum
122  * return          Gain adjust value (-1 to 2)
123  */
124 static int adjust_gain(enum lc3_srate sr,
125     int g_idx, int nbits, int nbits_budget)
126 {
127     /* --- Compute delta threshold --- */
128 
129     const int *t = (const int [LC3_NUM_SRATE][3]){
130         {  80,  500,  850 }, { 230, 1025, 1700 }, { 380, 1550, 2550 },
131         { 530, 2075, 3400 }, { 680, 2600, 4250 }
132     }[sr];
133 
134     int delta, den = 48;
135 
136     if (nbits < t[0]) {
137         delta = 3*(nbits + 48);
138 
139     } else if (nbits < t[1]) {
140         int n0 = 3*(t[0] + 48), range = t[1] - t[0];
141         delta = n0 * range + (nbits - t[0]) * (t[1] - n0);
142         den *= range;
143 
144     } else {
145         delta = LC3_MIN(nbits, t[2]);
146     }
147 
148     delta = (delta + den/2) / den;
149 
150     /* --- Adjust gain --- */
151 
152     if (nbits < nbits_budget - (delta + 2))
153         return -(g_idx > 0);
154 
155     if (nbits > nbits_budget)
156         return (g_idx < 255) + (g_idx < 254 && nbits >= nbits_budget + delta);
157 
158     return 0;
159 }
160 
161 /**
162  * Unquantize gain
163  * g_int           Quantization gain value
164  * return          Unquantized gain value
165  */
166 static float unquantize_gain(int g_int)
167 {
168     /* Unquantization gain table :
169      * G[i] = 10 ^ (i / 28) , i = [0..64] */
170 
171     static const float iq_table[] = {
172         1.00000000e+00, 1.08571112e+00, 1.17876863e+00, 1.27980221e+00,
173         1.38949549e+00, 1.50859071e+00, 1.63789371e+00, 1.77827941e+00,
174         1.93069773e+00, 2.09617999e+00, 2.27584593e+00, 2.47091123e+00,
175         2.68269580e+00, 2.91263265e+00, 3.16227766e+00, 3.43332002e+00,
176         3.72759372e+00, 4.04708995e+00, 4.39397056e+00, 4.77058270e+00,
177         5.17947468e+00, 5.62341325e+00, 6.10540230e+00, 6.62870316e+00,
178         7.19685673e+00, 7.81370738e+00, 8.48342898e+00, 9.21055318e+00,
179         1.00000000e+01, 1.08571112e+01, 1.17876863e+01, 1.27980221e+01,
180         1.38949549e+01, 1.50859071e+01, 1.63789371e+01, 1.77827941e+01,
181         1.93069773e+01, 2.09617999e+01, 2.27584593e+01, 2.47091123e+01,
182         2.68269580e+01, 2.91263265e+01, 3.16227766e+01, 3.43332002e+01,
183         3.72759372e+01, 4.04708995e+01, 4.39397056e+01, 4.77058270e+01,
184         5.17947468e+01, 5.62341325e+01, 6.10540230e+01, 6.62870316e+01,
185         7.19685673e+01, 7.81370738e+01, 8.48342898e+01, 9.21055318e+01,
186         1.00000000e+02, 1.08571112e+02, 1.17876863e+02, 1.27980221e+02,
187         1.38949549e+02, 1.50859071e+02, 1.63789371e+02, 1.77827941e+02,
188         1.93069773e+02
189     };
190 
191     float g = iq_table[LC3_ABS(g_int) & 0x3f];
192     for(int n64 = LC3_ABS(g_int) >> 6; n64--; )
193         g *= iq_table[64];
194 
195     return g_int >= 0 ? g : 1 / g;
196 }
197 
198 /**
199  * Spectrum quantization
200  * dt, sr          Duration and samplerate of the frame
201  * g_int           Quantization gain value
202  * x               Spectral coefficients, scaled as output
203  * xq, nq          Output spectral quantized coefficients, and count
204  */
205 static void quantize(enum lc3_dt dt, enum lc3_srate sr,
206     int g_int, float *x, int16_t *xq, int *nq)
207 {
208     float g_inv = 1 / unquantize_gain(g_int);
209     int ne = LC3_NE(dt, sr);
210 
211     *nq = ne;
212 
213     for (int i = 0; i < ne; i += 2) {
214         int16_t x0, x1;
215 
216         x[i+0] *= g_inv;
217         x0 = fminf(floorf(fabsf(x[i+0]) + 6.f/16), INT16_MAX);
218         xq[i+0] = x[i+0] < 0 ? -x0 : x0;
219 
220         x[i+1] *= g_inv;
221         x1 = fminf(floorf(fabsf(x[i+1]) + 6.f/16), INT16_MAX);
222         xq[i+1] = x[i+1] < 0 ? -x1 : x1;
223 
224         *nq = x0 || x1 ? ne : *nq - 2;
225     }
226 }
227 
228 /**
229  * Spectrum quantization inverse
230  * dt, sr          Duration and samplerate of the frame
231  * g_int           Quantization gain value
232  * x, nq           Spectral quantized, and count of significants
233  * return          Unquantized gain value
234  */
235 static float unquantize(enum lc3_dt dt, enum lc3_srate sr,
236     int g_int, float *x, int nq)
237 {
238     float g = unquantize_gain(g_int);
239     int i, ne = LC3_NE(dt, sr);
240 
241     for (i = 0; i < nq; i++)
242         x[i] = x[i] * g;
243 
244     for ( ; i < ne; i++)
245         x[i] = 0;
246 
247     return g;
248 }
249 
250 
251 /* ----------------------------------------------------------------------------
252  *  Spectrum coding
253  * -------------------------------------------------------------------------- */
254 
255 /**
256  * Resolve High-bitrate mode according size of the frame
257  * sr, nbytes      Samplerate and size of the frame
258  * return          True when High-Rate mode enabled
259  */
260 static int resolve_high_rate(enum lc3_srate sr, int nbytes)
261 {
262     return nbytes > 20 * (1 + (int)sr);
263 }
264 
265 /**
266  * Bit consumption
267  * dt, sr, nbytes  Duration, samplerate and size of the frame
268  * x               Spectral quantized coefficients
269  * n               Count of significant coefficients, updated on truncation
270  * nbits_budget    Truncate to stay in budget, when not zero
271  * p_lsb_mode      Return True when LSB's are not AC coded, or NULL
272  * return          The number of bits coding the spectrum
273  */
274 static int compute_nbits(
275     enum lc3_dt dt, enum lc3_srate sr, int nbytes,
276     const int16_t *x, int *n, int nbits_budget, bool *p_lsb_mode)
277 {
278     int ne = LC3_NE(dt, sr);
279 
280     /* --- Mode and rate --- */
281 
282     bool lsb_mode  = nbytes >= 20 * (3 + (int)sr);
283     bool high_rate = resolve_high_rate(sr, nbytes);
284 
285     /* --- Loop on quantized coefficients --- */
286 
287     int nbits = 0, nbits_lsb = 0;
288     uint8_t state = 0;
289 
290     int nbits_end = 0;
291     int n_end = 0;
292 
293     nbits_budget = nbits_budget ? nbits_budget * 2048 : INT_MAX;
294 
295     for (int i = 0, h = 0; h < 2; h++) {
296         const uint8_t (*lut_coeff)[4] = lc3_spectrum_lookup[high_rate][h];
297 
298         for ( ; i < LC3_MIN(*n, (ne + 2) >> (1 - h))
299                 && nbits <= nbits_budget; i += 2) {
300 
301             const uint8_t *lut = lut_coeff[state];
302             int a = LC3_ABS(x[i]), b = LC3_ABS(x[i+1]);
303 
304             /* --- Sign values --- */
305 
306             int s = (a != 0) + (b != 0);
307             nbits += s * 2048;
308 
309             /* --- LSB values Reduce to 2*2 bits MSB values ---
310              * Reduce to 2x2 bits MSB values. The LSB's pair are arithmetic
311              * coded with an escape code followed by 1 bit for each values.
312              * The LSB mode does not arthmetic code the first LSB,
313              * add the sign of the LSB when one of pair was at value 1 */
314 
315             int k = 0;
316             int m = (a | b) >> 2;
317 
318             if (m) {
319                 if (lsb_mode) {
320                     nbits += lc3_spectrum_bits[lut[k++]][16] - 2*2048;
321                     nbits_lsb += 2 + (a == 1) + (b == 1);
322                 }
323 
324                 for (m >>= lsb_mode; m; m >>= 1, k++)
325                     nbits += lc3_spectrum_bits[lut[LC3_MIN(k, 3)]][16];
326 
327                 nbits += k * 2*2048;
328                 a >>= k;
329                 b >>= k;
330 
331                 k = LC3_MIN(k, 3);
332             }
333 
334             /* --- MSB values --- */
335 
336             nbits += lc3_spectrum_bits[lut[k]][a + 4*b];
337 
338             /* --- Update state --- */
339 
340             if (s && nbits <= nbits_budget) {
341                 n_end = i + 2;
342                 nbits_end = nbits;
343             }
344 
345             state = (state << 4) + (k > 1 ? 12 + k : 1 + (a + b) * (k + 1));
346         }
347     }
348 
349     /* --- Return --- */
350 
351     *n = n_end;
352 
353     if (p_lsb_mode)
354         *p_lsb_mode = lsb_mode &&
355             nbits_end + nbits_lsb * 2048 > nbits_budget;
356 
357     if (nbits_budget >= INT_MAX)
358         nbits_end += nbits_lsb * 2048;
359 
360     return (nbits_end + 2047) / 2048;
361 }
362 
363 /**
364  * Put quantized spectrum
365  * bits            Bitstream context
366  * dt, sr, nbytes  Duration, samplerate and size of the frame
367  * x               Spectral quantized
368  * nq, lsb_mode    Count of significants, and LSB discard indication
369  */
370 static void put_quantized(lc3_bits_t *bits,
371     enum lc3_dt dt, enum lc3_srate sr, int nbytes,
372     const int16_t *x, int nq, bool lsb_mode)
373 {
374     int ne = LC3_NE(dt, sr);
375     bool high_rate = resolve_high_rate(sr, nbytes);
376 
377     /* --- Loop on quantized coefficients --- */
378 
379     uint8_t state = 0;
380 
381     for (int i = 0, h = 0; h < 2; h++) {
382         const uint8_t (*lut_coeff)[4] = lc3_spectrum_lookup[high_rate][h];
383 
384         for ( ; i < LC3_MIN(nq, (ne + 2) >> (1 - h)); i += 2) {
385 
386             const uint8_t *lut = lut_coeff[state];
387             bool a_neg = x[i] < 0, b_neg = x[i+1] < 0;
388             int a = LC3_ABS(x[i]), b = LC3_ABS(x[i+1]);
389 
390             /* --- LSB values Reduce to 2*2 bits MSB values ---
391              * Reduce to 2x2 bits MSB values. The LSB's pair are arithmetic
392              * coded with an escape code and 1 bits for each values.
393              * The LSB mode discard the first LSB (at this step) */
394 
395             int m = (a | b) >> 2;
396             int k = 0, shr = 0;
397 
398             if (m) {
399 
400                 if (lsb_mode)
401                     lc3_put_symbol(bits,
402                         lc3_spectrum_models + lut[k++], 16);
403 
404                 for (m >>= lsb_mode; m; m >>= 1, k++) {
405                     lc3_put_bit(bits, (a >> k) & 1);
406                     lc3_put_bit(bits, (b >> k) & 1);
407                     lc3_put_symbol(bits,
408                         lc3_spectrum_models + lut[LC3_MIN(k, 3)], 16);
409                 }
410 
411                 a >>= lsb_mode;
412                 b >>= lsb_mode;
413 
414                 shr = k - lsb_mode;
415                 k = LC3_MIN(k, 3);
416             }
417 
418             /* --- Sign values --- */
419 
420             if (a) lc3_put_bit(bits, a_neg);
421             if (b) lc3_put_bit(bits, b_neg);
422 
423             /* --- MSB values --- */
424 
425             a >>= shr;
426             b >>= shr;
427 
428             lc3_put_symbol(bits, lc3_spectrum_models + lut[k], a + 4*b);
429 
430             /* --- Update state --- */
431 
432             state = (state << 4) + (k > 1 ? 12 + k : 1 + (a + b) * (k + 1));
433         }
434     }
435 }
436 
437 /**
438  * Get quantized spectrum
439  * bits            Bitstream context
440  * dt, sr, nbytes  Duration, samplerate and size of the frame
441  * nq, lsb_mode    Count of significants, and LSB discard indication
442  * xq              Return `nq` spectral quantized coefficients
443  * nf_seed         Return the noise factor seed associated
444  * return          0: Ok  -1: Invalid bitstream data
445  */
446 static int get_quantized(lc3_bits_t *bits,
447     enum lc3_dt dt, enum lc3_srate sr, int nbytes,
448     int nq, bool lsb_mode, float *xq, uint16_t *nf_seed)
449 {
450     int ne = LC3_NE(dt, sr);
451     bool high_rate = resolve_high_rate(sr, nbytes);
452 
453      *nf_seed = 0;
454 
455     /* --- Loop on quantized coefficients --- */
456 
457     uint8_t state = 0;
458 
459     for (int i = 0, h = 0; h < 2; h++) {
460         const uint8_t (*lut_coeff)[4] = lc3_spectrum_lookup[high_rate][h];
461 
462         for ( ; i < LC3_MIN(nq, (ne + 2) >> (1 - h)); i += 2) {
463 
464             const uint8_t *lut = lut_coeff[state];
465 
466             /* --- LSB values ---
467              * Until the symbol read indicates the escape value 16,
468              * read an LSB bit for each values.
469              * The LSB mode discard the first LSB (at this step) */
470 
471             int u = 0, v = 0;
472             int k = 0, shl = 0;
473 
474             unsigned s = lc3_get_symbol(bits, lc3_spectrum_models + lut[k]);
475 
476             if (lsb_mode && s >= 16) {
477                 s = lc3_get_symbol(bits, lc3_spectrum_models + lut[++k]);
478                 shl++;
479             }
480 
481             for ( ; s >= 16 && shl < 14; shl++) {
482                 u |= lc3_get_bit(bits) << shl;
483                 v |= lc3_get_bit(bits) << shl;
484 
485                 k += (k < 3);
486                 s  = lc3_get_symbol(bits, lc3_spectrum_models + lut[k]);
487             }
488 
489             if (s >= 16)
490                 return -1;
491 
492             /* --- MSB & sign values --- */
493 
494             int a = s % 4;
495             int b = s / 4;
496 
497             u |= a << shl;
498             v |= b << shl;
499 
500             xq[i  ] = u && lc3_get_bit(bits) ? -u : u;
501             xq[i+1] = v && lc3_get_bit(bits) ? -v : v;
502 
503             *nf_seed = (*nf_seed + u * i + v * (i+1)) & 0xffff;
504 
505             /* --- Update state --- */
506 
507             state = (state << 4) + (k > 1 ? 12 + k : 1 + (a + b) * (k + 1));
508         }
509     }
510 
511     return 0;
512 }
513 
514 /**
515  * Put residual bits of quantization
516  * bits            Bitstream context
517  * nbits           Maximum number of bits to output
518  * xq, n           Spectral quantized, and count of significants
519  * xf              Scaled spectral coefficients
520  */
521 static void put_residual(lc3_bits_t *bits, int nbits,
522     const int16_t *xq, int n, const float *xf)
523 {
524     for (int i = 0; i < n && nbits > 0; i++) {
525 
526         if (xq[i] == 0)
527             continue;
528 
529         lc3_put_bit(bits, xf[i] >= xq[i]);
530         nbits--;
531     }
532 }
533 
534 /**
535  * Get residual bits of quantization
536  * bits            Bitstream context
537  * nbits           Maximum number of bits to output
538  * x, nq           Spectral quantized, and count of significants
539  */
540 static void get_residual(lc3_bits_t *bits, int nbits, float *x, int nq)
541 {
542     for (int i = 0; i < nq && nbits > 0; i++) {
543 
544         if (x[i] == 0)
545             continue;
546 
547         if (lc3_get_bit(bits) == 0)
548             x[i] -= x[i] < 0 ? 5.f/16 : 3.f/16;
549         else
550             x[i] += x[i] > 0 ? 5.f/16 : 3.f/16;
551 
552         nbits--;
553     }
554 }
555 
556 /**
557  * Put LSB values of quantized spectrum values
558  * bits            Bitstream context
559  * nbits           Maximum number of bits to output
560  * x, n            Spectral quantized, and count of significants
561  */
562 static void put_lsb(lc3_bits_t *bits, int nbits, const int16_t *x, int n)
563 {
564     for (int i = 0; i < n && nbits > 0; i += 2) {
565 
566         bool a_neg = x[i] < 0, b_neg = x[i+1] < 0;
567         int a = LC3_ABS(x[i]), b = LC3_ABS(x[i+1]);
568 
569         if ((a | b) >> 2 == 0)
570             continue;
571 
572         if (nbits-- > 0)
573             lc3_put_bit(bits, a & 1);
574 
575         if (a == 1 && nbits-- > 0)
576             lc3_put_bit(bits, a_neg);
577 
578         if (nbits-- > 0)
579             lc3_put_bit(bits, b & 1);
580 
581         if (b == 1 && nbits-- > 0)
582             lc3_put_bit(bits, b_neg);
583     }
584 }
585 
586 /**
587  * Get LSB values of quantized spectrum values
588  * bits            Bitstream context
589  * nbits           Maximum number of bits to output
590  * x, nq           Spectral quantized, and count of significants
591  * nf_seed         Update the noise factor seed according
592  */
593 static void get_lsb(lc3_bits_t *bits,
594     int nbits, float *x, int nq, uint16_t *nf_seed)
595 {
596     for (int i = 0; i < nq && nbits > 0; i += 2) {
597 
598         float a = fabsf(x[i]), b = fabsf(x[i+1]);
599 
600         if (fmaxf(a, b) < 4)
601             continue;
602 
603         if (nbits-- > 0 && lc3_get_bit(bits)) {
604             if (a) {
605                 x[i] += x[i] < 0 ? -1 : 1;
606                 *nf_seed = (*nf_seed + i) & 0xffff;
607             } else if (nbits-- > 0) {
608                 x[i] = lc3_get_bit(bits) ? -1 : 1;
609                 *nf_seed = (*nf_seed + i) & 0xffff;
610             }
611         }
612 
613         if (nbits-- > 0 && lc3_get_bit(bits)) {
614             if (b) {
615                 x[i+1] += x[i+1] < 0 ? -1 : 1;
616                 *nf_seed = (*nf_seed + i+1) & 0xffff;
617             } else if (nbits-- > 0) {
618                 x[i+1] = lc3_get_bit(bits) ? -1 : 1;
619                 *nf_seed = (*nf_seed + i+1) & 0xffff;
620             }
621         }
622     }
623 }
624 
625 
626 /* ----------------------------------------------------------------------------
627  *  Noise coding
628  * -------------------------------------------------------------------------- */
629 
630 /**
631  * Estimate noise level
632  * dt, bw          Duration and bandwidth of the frame
633  * xq, nq          Quantized spectral coefficients
634  * x               Quantization scaled spectrum coefficients
635  * return          Noise factor (0 to 7)
636  */
637 static int estimate_noise(enum lc3_dt dt, enum lc3_bandwidth bw,
638     const int16_t *xq, int nq, const float *x)
639 {
640     int bw_stop = (dt == LC3_DT_7M5 ? 60 : 80) * (1 + bw);
641     int w = 2 + dt;
642 
643     float sum = 0;
644     int i, n = 0, z = 0;
645 
646     for (i = 6*(3 + dt) - w; i < LC3_MIN(nq, bw_stop); i++) {
647         z = xq[i] ? 0 : z + 1;
648         if (z > 2*w)
649             sum += fabs(x[i - w]), n++;
650     }
651 
652     for ( ; i < bw_stop + w; i++)
653         if (++z > 2*w)
654             sum += fabs(x[i - w]), n++;
655 
656     int nf = n ? 8 - (int)((16 * sum) / n + 0.5f) : 0;
657 
658     return LC3_CLIP(nf, 0, 7);
659 }
660 
661 /**
662  * Noise filling
663  * dt, bw          Duration and bandwidth of the frame
664  * nf, nf_seed     The noise factor and pseudo-random seed
665  * g               Quantization gain
666  * x, nq           Spectral quantized, and count of significants
667  */
668 static void fill_noise(enum lc3_dt dt, enum lc3_bandwidth bw,
669     int nf, uint16_t nf_seed, float g, float *x, int nq)
670 {
671     int bw_stop = (dt == LC3_DT_7M5 ? 60 : 80) * (1 + bw);
672     int w = 2 + dt;
673 
674     float s = g * (float)(8 - nf) / 16;
675     int i, z = 0;
676 
677     for (i = 6*(3 + dt) - w; i < LC3_MIN(nq, bw_stop); i++) {
678         z = x[i] ? 0 : z + 1;
679         if (z > 2*w) {
680             nf_seed = (13849 + nf_seed*31821) & 0xffff;
681             x[i - w] = nf_seed & 0x8000 ? -s : s;
682         }
683     }
684 
685     for ( ; i < bw_stop + w; i++)
686         if (++z > 2*w) {
687             nf_seed = (13849 + nf_seed*31821) & 0xffff;
688             x[i - w] = nf_seed & 0x8000 ? -s : s;
689         }
690 }
691 
692 /**
693  * Put noise factor
694  * bits            Bitstream context
695  * nf              Noise factor (0 to 7)
696  */
697 static void put_noise_factor(lc3_bits_t *bits, int nf)
698 {
699     lc3_put_bits(bits, nf, 3);
700 }
701 
702 /**
703  * Get noise factor
704  * bits            Bitstream context
705  * return          Noise factor (0 to 7)
706  */
707 static int get_noise_factor(lc3_bits_t *bits)
708 {
709     return lc3_get_bits(bits, 3);
710 }
711 
712 
713 /* ----------------------------------------------------------------------------
714  *  Encoding
715  * -------------------------------------------------------------------------- */
716 
717 /**
718  * Bit consumption of the number of coded coefficients
719  * dt, sr          Duration, samplerate of the frame
720  * return          Bit consumpution of the number of coded coefficients
721  */
722 static int get_nbits_nq(enum lc3_dt dt, enum lc3_srate sr)
723 {
724     int ne = LC3_NE(dt, sr);
725     return 4 + (ne > 32) + (ne > 64) + (ne > 128) + (ne > 256);
726 }
727 
728 /**
729  * Bit consumption of the arithmetic coder
730  * dt, sr, nbytes  Duration, samplerate and size of the frame
731  * return          Bit consumption of bitstream data
732  */
733 static int get_nbits_ac(enum lc3_dt dt, enum lc3_srate sr, int nbytes)
734 {
735     return get_nbits_nq(dt, sr) + 3 + LC3_MIN((nbytes-1) / 160, 2);
736 }
737 
738 /**
739  * Spectrum analysis
740  */
741 void lc3_spec_analyze(enum lc3_dt dt, enum lc3_srate sr,
742     int nbytes, bool pitch, const lc3_tns_data_t *tns,
743     struct lc3_spec_analysis *spec, float *x,
744     int16_t *xq, struct lc3_spec_side *side)
745 {
746     bool reset_off;
747 
748     /* --- Bit budget --- */
749 
750     const int nbits_gain = 8;
751     const int nbits_nf = 3;
752 
753     int nbits_budget = 8*nbytes - get_nbits_ac(dt, sr, nbytes) -
754         lc3_bwdet_get_nbits(sr) - lc3_ltpf_get_nbits(pitch) -
755         lc3_sns_get_nbits() - lc3_tns_get_nbits(tns) - nbits_gain - nbits_nf;
756 
757     /* --- Global gain --- */
758 
759     float nbits_off = spec->nbits_off + spec->nbits_spare;
760     nbits_off = fminf(fmaxf(nbits_off, -40), 40);
761     nbits_off = 0.8 * spec->nbits_off + 0.2 * nbits_off;
762 
763     int g_off = resolve_gain_offset(sr, nbytes);
764 
765     int g_int = estimate_gain(dt, sr,
766         x, nbits_budget, nbits_off, g_off, &reset_off);
767 
768     /* --- Quantization --- */
769 
770     quantize(dt, sr, g_int, x, xq, &side->nq);
771 
772     int nbits = compute_nbits(dt, sr, nbytes, xq, &side->nq, 0, NULL);
773 
774     spec->nbits_off = reset_off ? 0 : nbits_off;
775     spec->nbits_spare = reset_off ? 0 : nbits_budget - nbits;
776 
777     /* --- Adjust gain and requantize --- */
778 
779     int g_adj = adjust_gain(sr, g_int + g_off, nbits, nbits_budget);
780 
781     if (g_adj)
782         quantize(dt, sr, g_adj, x, xq, &side->nq);
783 
784     side->g_idx = g_int + g_adj + g_off;
785     nbits = compute_nbits(dt, sr, nbytes,
786         xq, &side->nq, nbits_budget, &side->lsb_mode);
787 }
788 
789 /**
790  * Put spectral quantization side data
791  */
792 void lc3_spec_put_side(lc3_bits_t *bits,
793     enum lc3_dt dt, enum lc3_srate sr, const struct lc3_spec_side *side)
794 {
795     int nbits_nq = get_nbits_nq(dt, sr);
796 
797     lc3_put_bits(bits, LC3_MAX(side->nq >> 1, 1) - 1, nbits_nq);
798     lc3_put_bits(bits, side->lsb_mode, 1);
799     lc3_put_bits(bits, side->g_idx, 8);
800 }
801 
802 /**
803  * Encode spectral coefficients
804  */
805 void lc3_spec_encode(lc3_bits_t *bits,
806     enum lc3_dt dt, enum lc3_srate sr, enum lc3_bandwidth bw, int nbytes,
807     const int16_t *xq, const lc3_spec_side_t *side, const float *x)
808 {
809     bool lsb_mode = side->lsb_mode;
810     int nq = side->nq;
811 
812     put_noise_factor(bits, estimate_noise(dt, bw, xq, nq, x));
813 
814     put_quantized(bits, dt, sr, nbytes, xq, nq, lsb_mode);
815 
816     int nbits_left = lc3_get_bits_left(bits);
817 
818     if (lsb_mode)
819         put_lsb(bits, nbits_left, xq, nq);
820     else
821         put_residual(bits, nbits_left, xq, nq, x);
822 }
823 
824 
825 /* ----------------------------------------------------------------------------
826  *  Decoding
827  * -------------------------------------------------------------------------- */
828 
829 /**
830  * Get spectral quantization side data
831  */
832 int lc3_spec_get_side(lc3_bits_t *bits,
833     enum lc3_dt dt, enum lc3_srate sr, struct lc3_spec_side *side)
834 {
835     int nbits_nq = get_nbits_nq(dt, sr);
836     int ne = LC3_NE(dt, sr);
837 
838     side->nq = (lc3_get_bits(bits, nbits_nq) + 1) << 1;
839     side->lsb_mode = lc3_get_bit(bits);
840     side->g_idx = lc3_get_bits(bits, 8);
841 
842     return side->nq > ne ? (side->nq = ne), -1 : 0;
843 }
844 
845 /**
846  * Decode spectral coefficients
847  */
848 int lc3_spec_decode(lc3_bits_t *bits,
849     enum lc3_dt dt, enum lc3_srate sr, enum lc3_bandwidth bw,
850     int nbytes, const lc3_spec_side_t *side, float *x)
851 {
852     bool lsb_mode = side->lsb_mode;
853     int nq = side->nq;
854     int ret = 0;
855 
856     int nf = get_noise_factor(bits);
857     uint16_t nf_seed;
858 
859     if ((ret = get_quantized(bits, dt, sr, nbytes,
860                     nq, lsb_mode, x, &nf_seed)) < 0)
861         return ret;
862 
863     int nbits_left = lc3_get_bits_left(bits);
864 
865     if (lsb_mode)
866         get_lsb(bits, nbits_left, x, nq, &nf_seed);
867     else
868         get_residual(bits, nbits_left, x, nq);
869 
870     int g_int = side->g_idx - resolve_gain_offset(sr, nbytes);
871     float g = unquantize(dt, sr, g_int, x, nq);
872 
873     if (nq > 2 || x[0] || x[1] || side->g_idx > 0 || nf < 7)
874         fill_noise(dt, bw, nf, nf_seed, g, x, nq);
875 
876     return 0;
877 }
878