]> git.sesse.net Git - ffmpeg/blob - libavcodec/opus_pvq.c
a2f5088aa98d081ce1da395b8421a48b867acca8
[ffmpeg] / libavcodec / opus_pvq.c
1 /*
2  * Copyright (c) 2012 Andrew D'Addesio
3  * Copyright (c) 2013-2014 Mozilla Corporation
4  * Copyright (c) 2017 Rostislav Pehlivanov <atomnuker@gmail.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "opustab.h"
24 #include "opus_pvq.h"
25
26 #define CELT_PVQ_U(n, k) (ff_celt_pvq_u_row[FFMIN(n, k)][FFMAX(n, k)])
27 #define CELT_PVQ_V(n, k) (CELT_PVQ_U(n, k) + CELT_PVQ_U(n, (k) + 1))
28
29 static inline int16_t celt_cos(int16_t x)
30 {
31     x = (MUL16(x, x) + 4096) >> 13;
32     x = (32767-x) + ROUND_MUL16(x, (-7651 + ROUND_MUL16(x, (8277 + ROUND_MUL16(-626, x)))));
33     return 1+x;
34 }
35
36 static inline int celt_log2tan(int isin, int icos)
37 {
38     int lc, ls;
39     lc = opus_ilog(icos);
40     ls = opus_ilog(isin);
41     icos <<= 15 - lc;
42     isin <<= 15 - ls;
43     return (ls << 11) - (lc << 11) +
44            ROUND_MUL16(isin, ROUND_MUL16(isin, -2597) + 7932) -
45            ROUND_MUL16(icos, ROUND_MUL16(icos, -2597) + 7932);
46 }
47
48 static inline int celt_bits2pulses(const uint8_t *cache, int bits)
49 {
50     // TODO: Find the size of cache and make it into an array in the parameters list
51     int i, low = 0, high;
52
53     high = cache[0];
54     bits--;
55
56     for (i = 0; i < 6; i++) {
57         int center = (low + high + 1) >> 1;
58         if (cache[center] >= bits)
59             high = center;
60         else
61             low = center;
62     }
63
64     return (bits - (low == 0 ? -1 : cache[low]) <= cache[high] - bits) ? low : high;
65 }
66
67 static inline int celt_pulses2bits(const uint8_t *cache, int pulses)
68 {
69     // TODO: Find the size of cache and make it into an array in the parameters list
70    return (pulses == 0) ? 0 : cache[pulses] + 1;
71 }
72
73 static inline void celt_normalize_residual(const int * av_restrict iy, float * av_restrict X,
74                                            int N, float g)
75 {
76     int i;
77     for (i = 0; i < N; i++)
78         X[i] = g * iy[i];
79 }
80
81 static void celt_exp_rotation_impl(float *X, uint32_t len, uint32_t stride,
82                                    float c, float s)
83 {
84     float *Xptr;
85     int i;
86
87     Xptr = X;
88     for (i = 0; i < len - stride; i++) {
89         float x1, x2;
90         x1           = Xptr[0];
91         x2           = Xptr[stride];
92         Xptr[stride] = c * x2 + s * x1;
93         *Xptr++      = c * x1 - s * x2;
94     }
95
96     Xptr = &X[len - 2 * stride - 1];
97     for (i = len - 2 * stride - 1; i >= 0; i--) {
98         float x1, x2;
99         x1           = Xptr[0];
100         x2           = Xptr[stride];
101         Xptr[stride] = c * x2 + s * x1;
102         *Xptr--      = c * x1 - s * x2;
103     }
104 }
105
106 static inline void celt_exp_rotation(float *X, uint32_t len,
107                                      uint32_t stride, uint32_t K,
108                                      enum CeltSpread spread, const int encode)
109 {
110     uint32_t stride2 = 0;
111     float c, s;
112     float gain, theta;
113     int i;
114
115     if (2*K >= len || spread == CELT_SPREAD_NONE)
116         return;
117
118     gain = (float)len / (len + (20 - 5*spread) * K);
119     theta = M_PI * gain * gain / 4;
120
121     c = cosf(theta);
122     s = sinf(theta);
123
124     if (len >= stride << 3) {
125         stride2 = 1;
126         /* This is just a simple (equivalent) way of computing sqrt(len/stride) with rounding.
127         It's basically incrementing long as (stride2+0.5)^2 < len/stride. */
128         while ((stride2 * stride2 + stride2) * stride + (stride >> 2) < len)
129             stride2++;
130     }
131
132     /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
133     extract_collapse_mask().*/
134     len /= stride;
135     for (i = 0; i < stride; i++) {
136         if (encode) {
137             celt_exp_rotation_impl(X + i * len, len, 1, c, -s);
138             if (stride2)
139                 celt_exp_rotation_impl(X + i * len, len, stride2, s, -c);
140         } else {
141             if (stride2)
142                 celt_exp_rotation_impl(X + i * len, len, stride2, s, c);
143             celt_exp_rotation_impl(X + i * len, len, 1, c, s);
144         }
145     }
146 }
147
148 static inline uint32_t celt_extract_collapse_mask(const int *iy, uint32_t N, uint32_t B)
149 {
150     uint32_t collapse_mask;
151     int N0;
152     int i, j;
153
154     if (B <= 1)
155         return 1;
156
157     /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
158     exp_rotation().*/
159     N0 = N/B;
160     collapse_mask = 0;
161     for (i = 0; i < B; i++)
162         for (j = 0; j < N0; j++)
163             collapse_mask |= (iy[i*N0+j]!=0)<<i;
164     return collapse_mask;
165 }
166
167 static inline void celt_stereo_merge(float *X, float *Y, float mid, int N)
168 {
169     int i;
170     float xp = 0, side = 0;
171     float E[2];
172     float mid2;
173     float t, gain[2];
174
175     /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
176     for (i = 0; i < N; i++) {
177         xp   += X[i] * Y[i];
178         side += Y[i] * Y[i];
179     }
180
181     /* Compensating for the mid normalization */
182     xp *= mid;
183     mid2 = mid;
184     E[0] = mid2 * mid2 + side - 2 * xp;
185     E[1] = mid2 * mid2 + side + 2 * xp;
186     if (E[0] < 6e-4f || E[1] < 6e-4f) {
187         for (i = 0; i < N; i++)
188             Y[i] = X[i];
189         return;
190     }
191
192     t = E[0];
193     gain[0] = 1.0f / sqrtf(t);
194     t = E[1];
195     gain[1] = 1.0f / sqrtf(t);
196
197     for (i = 0; i < N; i++) {
198         float value[2];
199         /* Apply mid scaling (side is already scaled) */
200         value[0] = mid * X[i];
201         value[1] = Y[i];
202         X[i] = gain[0] * (value[0] - value[1]);
203         Y[i] = gain[1] * (value[0] + value[1]);
204     }
205 }
206
207 static void celt_interleave_hadamard(float *tmp, float *X, int N0,
208                                      int stride, int hadamard)
209 {
210     int i, j;
211     int N = N0*stride;
212
213     if (hadamard) {
214         const uint8_t *ordery = ff_celt_hadamard_ordery + stride - 2;
215         for (i = 0; i < stride; i++)
216             for (j = 0; j < N0; j++)
217                 tmp[j*stride+i] = X[ordery[i]*N0+j];
218     } else {
219         for (i = 0; i < stride; i++)
220             for (j = 0; j < N0; j++)
221                 tmp[j*stride+i] = X[i*N0+j];
222     }
223
224     for (i = 0; i < N; i++)
225         X[i] = tmp[i];
226 }
227
228 static void celt_deinterleave_hadamard(float *tmp, float *X, int N0,
229                                        int stride, int hadamard)
230 {
231     int i, j;
232     int N = N0*stride;
233
234     if (hadamard) {
235         const uint8_t *ordery = ff_celt_hadamard_ordery + stride - 2;
236         for (i = 0; i < stride; i++)
237             for (j = 0; j < N0; j++)
238                 tmp[ordery[i]*N0+j] = X[j*stride+i];
239     } else {
240         for (i = 0; i < stride; i++)
241             for (j = 0; j < N0; j++)
242                 tmp[i*N0+j] = X[j*stride+i];
243     }
244
245     for (i = 0; i < N; i++)
246         X[i] = tmp[i];
247 }
248
249 static void celt_haar1(float *X, int N0, int stride)
250 {
251     int i, j;
252     N0 >>= 1;
253     for (i = 0; i < stride; i++) {
254         for (j = 0; j < N0; j++) {
255             float x0 = X[stride * (2 * j + 0) + i];
256             float x1 = X[stride * (2 * j + 1) + i];
257             X[stride * (2 * j + 0) + i] = (x0 + x1) * M_SQRT1_2;
258             X[stride * (2 * j + 1) + i] = (x0 - x1) * M_SQRT1_2;
259         }
260     }
261 }
262
263 static inline int celt_compute_qn(int N, int b, int offset, int pulse_cap,
264                                   int dualstereo)
265 {
266     int qn, qb;
267     int N2 = 2 * N - 1;
268     if (dualstereo && N == 2)
269         N2--;
270
271     /* The upper limit ensures that in a stereo split with itheta==16384, we'll
272      * always have enough bits left over to code at least one pulse in the
273      * side; otherwise it would collapse, since it doesn't get folded. */
274     qb = FFMIN3(b - pulse_cap - (4 << 3), (b + N2 * offset) / N2, 8 << 3);
275     qn = (qb < (1 << 3 >> 1)) ? 1 : ((ff_celt_qn_exp2[qb & 0x7] >> (14 - (qb >> 3))) + 1) >> 1 << 1;
276     return qn;
277 }
278
279 /* Convert the quantized vector to an index */
280 static inline uint32_t celt_icwrsi(uint32_t N, const int *y)
281 {
282     int i, idx = 0, sum = 0;
283     for (i = N - 1; i >= 0; i--) {
284         const uint32_t i_s = CELT_PVQ_U(N - i, sum + FFABS(y[i]) + 1);
285         idx += CELT_PVQ_U(N - i, sum) + (y[i] < 0)*i_s;
286         sum += FFABS(y[i]);
287     }
288     return idx;
289 }
290
291 // this code was adapted from libopus
292 static inline uint64_t celt_cwrsi(uint32_t N, uint32_t K, uint32_t i, int *y)
293 {
294     uint64_t norm = 0;
295     uint32_t p;
296     int s, val;
297     int k0;
298
299     while (N > 2) {
300         uint32_t q;
301
302         /*Lots of pulses case:*/
303         if (K >= N) {
304             const uint32_t *row = ff_celt_pvq_u_row[N];
305
306             /* Are the pulses in this dimension negative? */
307             p  = row[K + 1];
308             s  = -(i >= p);
309             i -= p & s;
310
311             /*Count how many pulses were placed in this dimension.*/
312             k0 = K;
313             q = row[N];
314             if (q > i) {
315                 K = N;
316                 do {
317                     p = ff_celt_pvq_u_row[--K][N];
318                 } while (p > i);
319             } else
320                 for (p = row[K]; p > i; p = row[K])
321                     K--;
322
323             i    -= p;
324             val   = (k0 - K + s) ^ s;
325             norm += val * val;
326             *y++  = val;
327         } else { /*Lots of dimensions case:*/
328             /*Are there any pulses in this dimension at all?*/
329             p = ff_celt_pvq_u_row[K    ][N];
330             q = ff_celt_pvq_u_row[K + 1][N];
331
332             if (p <= i && i < q) {
333                 i -= p;
334                 *y++ = 0;
335             } else {
336                 /*Are the pulses in this dimension negative?*/
337                 s  = -(i >= q);
338                 i -= q & s;
339
340                 /*Count how many pulses were placed in this dimension.*/
341                 k0 = K;
342                 do p = ff_celt_pvq_u_row[--K][N];
343                 while (p > i);
344
345                 i    -= p;
346                 val   = (k0 - K + s) ^ s;
347                 norm += val * val;
348                 *y++  = val;
349             }
350         }
351         N--;
352     }
353
354     /* N == 2 */
355     p  = 2 * K + 1;
356     s  = -(i >= p);
357     i -= p & s;
358     k0 = K;
359     K  = (i + 1) / 2;
360
361     if (K)
362         i -= 2 * K - 1;
363
364     val   = (k0 - K + s) ^ s;
365     norm += val * val;
366     *y++  = val;
367
368     /* N==1 */
369     s     = -i;
370     val   = (K + s) ^ s;
371     norm += val * val;
372     *y    = val;
373
374     return norm;
375 }
376
377 static inline void celt_encode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
378 {
379     ff_opus_rc_enc_uint(rc, celt_icwrsi(N, y), CELT_PVQ_V(N, K));
380 }
381
382 static inline float celt_decode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
383 {
384     const uint32_t idx = ff_opus_rc_dec_uint(rc, CELT_PVQ_V(N, K));
385     return celt_cwrsi(N, K, idx, y);
386 }
387
388 /*
389  * Faster than libopus's search, operates entirely in the signed domain.
390  * Slightly worse/better depending on N, K and the input vector.
391  */
392 static void celt_pvq_search(float *X, int *y, int K, int N)
393 {
394     int i;
395     float res = 0.0f, y_norm = 0.0f, xy_norm = 0.0f;
396
397     for (i = 0; i < N; i++)
398         res += FFABS(X[i]);
399
400     res = K/res;
401
402     for (i = 0; i < N; i++) {
403         y[i] = lrintf(res*X[i]);
404         y_norm  += y[i]*y[i];
405         xy_norm += y[i]*X[i];
406         K -= FFABS(y[i]);
407     }
408
409     while (K) {
410         int max_idx = 0, phase = FFSIGN(K);
411         float max_den = 1.0f, max_num = 0.0f;
412         y_norm += 1.0f;
413
414         for (i = 0; i < N; i++) {
415             float xy_new = xy_norm + 1*phase*FFABS(X[i]);
416             float y_new  = y_norm  + 2*phase*FFABS(y[i]);
417             xy_new = xy_new * xy_new;
418             if ((max_den*xy_new) > (y_new*max_num)) {
419                 max_den = y_new;
420                 max_num = xy_new;
421                 max_idx = i;
422             }
423         }
424
425         K -= phase;
426
427         phase *= FFSIGN(X[max_idx]);
428         xy_norm += 1*phase*X[max_idx];
429         y_norm  += 2*phase*y[max_idx];
430         y[max_idx] += phase;
431     }
432 }
433
434 static uint32_t celt_alg_quant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
435                                enum CeltSpread spread, uint32_t blocks, float gain)
436 {
437     int y[176];
438
439     celt_exp_rotation(X, N, blocks, K, spread, 1);
440     celt_pvq_search(X, y, K, N);
441     celt_encode_pulses(rc, y,  N, K);
442     return celt_extract_collapse_mask(y, N, blocks);
443 }
444
445 /** Decode pulse vector and combine the result with the pitch vector to produce
446     the final normalised signal in the current band. */
447 static uint32_t celt_alg_unquant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
448                                  enum CeltSpread spread, uint32_t blocks, float gain)
449 {
450     int y[176];
451
452     gain /= sqrtf(celt_decode_pulses(rc, y, N, K));
453     celt_normalize_residual(y, X, N, gain);
454     celt_exp_rotation(X, N, blocks, K, spread, 0);
455     return celt_extract_collapse_mask(y, N, blocks);
456 }
457
458 uint32_t ff_celt_decode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
459                              float *X, float *Y, int N, int b, uint32_t blocks,
460                              float *lowband, int duration, float *lowband_out, int level,
461                              float gain, float *lowband_scratch, int fill)
462 {
463     const uint8_t *cache;
464     int dualstereo, split;
465     int imid = 0, iside = 0;
466     uint32_t N0 = N;
467     int N_B;
468     int N_B0;
469     int B0 = blocks;
470     int time_divide = 0;
471     int recombine = 0;
472     int inv = 0;
473     float mid = 0, side = 0;
474     int longblocks = (B0 == 1);
475     uint32_t cm = 0;
476
477     N_B0 = N_B = N / blocks;
478     split = dualstereo = (Y != NULL);
479
480     if (N == 1) {
481         /* special case for one sample */
482         int i;
483         float *x = X;
484         for (i = 0; i <= dualstereo; i++) {
485             int sign = 0;
486             if (f->remaining2 >= 1<<3) {
487                 sign           = ff_opus_rc_get_raw(rc, 1);
488                 f->remaining2 -= 1 << 3;
489                 b             -= 1 << 3;
490             }
491             x[0] = sign ? -1.0f : 1.0f;
492             x = Y;
493         }
494         if (lowband_out)
495             lowband_out[0] = X[0];
496         return 1;
497     }
498
499     if (!dualstereo && level == 0) {
500         int tf_change = f->tf_change[band];
501         int k;
502         if (tf_change > 0)
503             recombine = tf_change;
504         /* Band recombining to increase frequency resolution */
505
506         if (lowband &&
507             (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
508             int j;
509             for (j = 0; j < N; j++)
510                 lowband_scratch[j] = lowband[j];
511             lowband = lowband_scratch;
512         }
513
514         for (k = 0; k < recombine; k++) {
515             if (lowband)
516                 celt_haar1(lowband, N >> k, 1 << k);
517             fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
518         }
519         blocks >>= recombine;
520         N_B <<= recombine;
521
522         /* Increasing the time resolution */
523         while ((N_B & 1) == 0 && tf_change < 0) {
524             if (lowband)
525                 celt_haar1(lowband, N_B, blocks);
526             fill |= fill << blocks;
527             blocks <<= 1;
528             N_B >>= 1;
529             time_divide++;
530             tf_change++;
531         }
532         B0 = blocks;
533         N_B0 = N_B;
534
535         /* Reorganize the samples in time order instead of frequency order */
536         if (B0 > 1 && lowband)
537             celt_deinterleave_hadamard(f->scratch, lowband, N_B >> recombine,
538                                        B0 << recombine, longblocks);
539     }
540
541     /* If we need 1.5 more bit than we can produce, split the band in two. */
542     cache = ff_celt_cache_bits +
543             ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
544     if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
545         N >>= 1;
546         Y = X + N;
547         split = 1;
548         duration -= 1;
549         if (blocks == 1)
550             fill = (fill & 1) | (fill << 1);
551         blocks = (blocks + 1) >> 1;
552     }
553
554     if (split) {
555         int qn;
556         int itheta = 0;
557         int mbits, sbits, delta;
558         int qalloc;
559         int pulse_cap;
560         int offset;
561         int orig_fill;
562         int tell;
563
564         /* Decide on the resolution to give to the split parameter theta */
565         pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
566         offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
567                                                           CELT_QTHETA_OFFSET);
568         qn = (dualstereo && band >= f->intensity_stereo) ? 1 :
569              celt_compute_qn(N, b, offset, pulse_cap, dualstereo);
570         tell = opus_rc_tell_frac(rc);
571         if (qn != 1) {
572             /* Entropy coding of the angle. We use a uniform pdf for the
573             time split, a step for stereo, and a triangular one for the rest. */
574             if (dualstereo && N > 2)
575                 itheta = ff_opus_rc_dec_uint_step(rc, qn/2);
576             else if (dualstereo || B0 > 1)
577                 itheta = ff_opus_rc_dec_uint(rc, qn+1);
578             else
579                 itheta = ff_opus_rc_dec_uint_tri(rc, qn);
580             itheta = itheta * 16384 / qn;
581             /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.
582             Let's do that at higher complexity */
583         } else if (dualstereo) {
584             inv = (b > 2 << 3 && f->remaining2 > 2 << 3) ? ff_opus_rc_dec_log(rc, 2) : 0;
585             itheta = 0;
586         }
587         qalloc = opus_rc_tell_frac(rc) - tell;
588         b -= qalloc;
589
590         orig_fill = fill;
591         if (itheta == 0) {
592             imid = 32767;
593             iside = 0;
594             fill = av_mod_uintp2(fill, blocks);
595             delta = -16384;
596         } else if (itheta == 16384) {
597             imid = 0;
598             iside = 32767;
599             fill &= ((1 << blocks) - 1) << blocks;
600             delta = 16384;
601         } else {
602             imid = celt_cos(itheta);
603             iside = celt_cos(16384-itheta);
604             /* This is the mid vs side allocation that minimizes squared error
605             in that band. */
606             delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
607         }
608
609         mid  = imid  / 32768.0f;
610         side = iside / 32768.0f;
611
612         /* This is a special case for N=2 that only works for stereo and takes
613         advantage of the fact that mid and side are orthogonal to encode
614         the side with just one bit. */
615         if (N == 2 && dualstereo) {
616             int c;
617             int sign = 0;
618             float tmp;
619             float *x2, *y2;
620             mbits = b;
621             /* Only need one bit for the side */
622             sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
623             mbits -= sbits;
624             c = (itheta > 8192);
625             f->remaining2 -= qalloc+sbits;
626
627             x2 = c ? Y : X;
628             y2 = c ? X : Y;
629             if (sbits)
630                 sign = ff_opus_rc_get_raw(rc, 1);
631             sign = 1 - 2 * sign;
632             /* We use orig_fill here because we want to fold the side, but if
633             itheta==16384, we'll have cleared the low bits of fill. */
634             cm = ff_celt_decode_band(f, rc, band, x2, NULL, N, mbits, blocks,
635                                      lowband, duration, lowband_out, level, gain,
636                                      lowband_scratch, orig_fill);
637             /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
638             and there's no need to worry about mixing with the other channel. */
639             y2[0] = -sign * x2[1];
640             y2[1] =  sign * x2[0];
641             X[0] *= mid;
642             X[1] *= mid;
643             Y[0] *= side;
644             Y[1] *= side;
645             tmp = X[0];
646             X[0] = tmp - Y[0];
647             Y[0] = tmp + Y[0];
648             tmp = X[1];
649             X[1] = tmp - Y[1];
650             Y[1] = tmp + Y[1];
651         } else {
652             /* "Normal" split code */
653             float *next_lowband2     = NULL;
654             float *next_lowband_out1 = NULL;
655             int next_level = 0;
656             int rebalance;
657
658             /* Give more bits to low-energy MDCTs than they would
659              * otherwise deserve */
660             if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {
661                 if (itheta > 8192)
662                     /* Rough approximation for pre-echo masking */
663                     delta -= delta >> (4 - duration);
664                 else
665                     /* Corresponds to a forward-masking slope of
666                      * 1.5 dB per 10 ms */
667                     delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
668             }
669             mbits = av_clip((b - delta) / 2, 0, b);
670             sbits = b - mbits;
671             f->remaining2 -= qalloc;
672
673             if (lowband && !dualstereo)
674                 next_lowband2 = lowband + N; /* >32-bit split case */
675
676             /* Only stereo needs to pass on lowband_out.
677              * Otherwise, it's handled at the end */
678             if (dualstereo)
679                 next_lowband_out1 = lowband_out;
680             else
681                 next_level = level + 1;
682
683             rebalance = f->remaining2;
684             if (mbits >= sbits) {
685                 /* In stereo mode, we do not apply a scaling to the mid
686                  * because we need the normalized mid for folding later */
687                 cm = ff_celt_decode_band(f, rc, band, X, NULL, N, mbits, blocks,
688                                          lowband, duration, next_lowband_out1,
689                                          next_level, dualstereo ? 1.0f : (gain * mid),
690                                          lowband_scratch, fill);
691
692                 rebalance = mbits - (rebalance - f->remaining2);
693                 if (rebalance > 3 << 3 && itheta != 0)
694                     sbits += rebalance - (3 << 3);
695
696                 /* For a stereo split, the high bits of fill are always zero,
697                  * so no folding will be done to the side. */
698                 cm |= ff_celt_decode_band(f, rc, band, Y, NULL, N, sbits, blocks,
699                                           next_lowband2, duration, NULL,
700                                           next_level, gain * side, NULL,
701                                           fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
702             } else {
703                 /* For a stereo split, the high bits of fill are always zero,
704                  * so no folding will be done to the side. */
705                 cm = ff_celt_decode_band(f, rc, band, Y, NULL, N, sbits, blocks,
706                                          next_lowband2, duration, NULL,
707                                          next_level, gain * side, NULL,
708                                          fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
709
710                 rebalance = sbits - (rebalance - f->remaining2);
711                 if (rebalance > 3 << 3 && itheta != 16384)
712                     mbits += rebalance - (3 << 3);
713
714                 /* In stereo mode, we do not apply a scaling to the mid because
715                  * we need the normalized mid for folding later */
716                 cm |= ff_celt_decode_band(f, rc, band, X, NULL, N, mbits, blocks,
717                                           lowband, duration, next_lowband_out1,
718                                           next_level, dualstereo ? 1.0f : (gain * mid),
719                                           lowband_scratch, fill);
720             }
721         }
722     } else {
723         /* This is the basic no-split case */
724         uint32_t q         = celt_bits2pulses(cache, b);
725         uint32_t curr_bits = celt_pulses2bits(cache, q);
726         f->remaining2 -= curr_bits;
727
728         /* Ensures we can never bust the budget */
729         while (f->remaining2 < 0 && q > 0) {
730             f->remaining2 += curr_bits;
731             curr_bits      = celt_pulses2bits(cache, --q);
732             f->remaining2 -= curr_bits;
733         }
734
735         if (q != 0) {
736             /* Finally do the actual quantization */
737             cm = celt_alg_unquant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
738                                   f->spread, blocks, gain);
739         } else {
740             /* If there's no pulse, fill the band anyway */
741             int j;
742             uint32_t cm_mask = (1 << blocks) - 1;
743             fill &= cm_mask;
744             if (!fill) {
745                 for (j = 0; j < N; j++)
746                     X[j] = 0.0f;
747             } else {
748                 if (!lowband) {
749                     /* Noise */
750                     for (j = 0; j < N; j++)
751                         X[j] = (((int32_t)celt_rng(f)) >> 20);
752                     cm = cm_mask;
753                 } else {
754                     /* Folded spectrum */
755                     for (j = 0; j < N; j++) {
756                         /* About 48 dB below the "normal" folding level */
757                         X[j] = lowband[j] + (((celt_rng(f)) & 0x8000) ? 1.0f / 256 : -1.0f / 256);
758                     }
759                     cm = fill;
760                 }
761                 celt_renormalize_vector(X, N, gain);
762             }
763         }
764     }
765
766     /* This code is used by the decoder and by the resynthesis-enabled encoder */
767     if (dualstereo) {
768         int j;
769         if (N != 2)
770             celt_stereo_merge(X, Y, mid, N);
771         if (inv) {
772             for (j = 0; j < N; j++)
773                 Y[j] *= -1;
774         }
775     } else if (level == 0) {
776         int k;
777
778         /* Undo the sample reorganization going from time order to frequency order */
779         if (B0 > 1)
780             celt_interleave_hadamard(f->scratch, X, N_B>>recombine,
781                                      B0<<recombine, longblocks);
782
783         /* Undo time-freq changes that we did earlier */
784         N_B = N_B0;
785         blocks = B0;
786         for (k = 0; k < time_divide; k++) {
787             blocks >>= 1;
788             N_B <<= 1;
789             cm |= cm >> blocks;
790             celt_haar1(X, N_B, blocks);
791         }
792
793         for (k = 0; k < recombine; k++) {
794             cm = ff_celt_bit_deinterleave[cm];
795             celt_haar1(X, N0>>k, 1<<k);
796         }
797         blocks <<= recombine;
798
799         /* Scale output for later folding */
800         if (lowband_out) {
801             int j;
802             float n = sqrtf(N0);
803             for (j = 0; j < N0; j++)
804                 lowband_out[j] = n * X[j];
805         }
806         cm = av_mod_uintp2(cm, blocks);
807     }
808
809     return cm;
810 }
811
812 /* This has to be, AND MUST BE done by the psychoacoustic system, this has a very
813  * big impact on the entire quantization and especially huge on transients */
814 static int celt_calc_theta(const float *X, const float *Y, int coupling, int N)
815 {
816     int j;
817     float e[2] = { 0.0f, 0.0f };
818     for (j = 0; j < N; j++) {
819         if (coupling) { /* Coupling case */
820             e[0] += (X[j] + Y[j])*(X[j] + Y[j]);
821             e[1] += (X[j] - Y[j])*(X[j] - Y[j]);
822         } else {
823             e[0] += X[j]*X[j];
824             e[1] += Y[j]*Y[j];
825         }
826     }
827     return lrintf(32768.0f*atan2f(sqrtf(e[1]), sqrtf(e[0]))/M_PI);
828 }
829
830 static void celt_stereo_is_decouple(float *X, float *Y, float e_l, float e_r, int N)
831 {
832     int i;
833     const float energy_n = 1.0f/(sqrtf(e_l*e_l + e_r*e_r) + FLT_EPSILON);
834     e_l *= energy_n;
835     e_r *= energy_n;
836     for (i = 0; i < N; i++)
837         X[i] = e_l*X[i] + e_r*Y[i];
838 }
839
840 static void celt_stereo_ms_decouple(float *X, float *Y, int N)
841 {
842     int i;
843     const float decouple_norm = 1.0f/sqrtf(2.0f);
844     for (i = 0; i < N; i++) {
845         const float Xret = X[i];
846         X[i] = (X[i] + Y[i])*decouple_norm;
847         Y[i] = (Y[i] - Xret)*decouple_norm;
848     }
849 }
850
851 uint32_t ff_celt_encode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
852                              float *X, float *Y, int N, int b, uint32_t blocks,
853                              float *lowband, int duration, float *lowband_out, int level,
854                              float gain, float *lowband_scratch, int fill)
855 {
856     const uint8_t *cache;
857     int dualstereo, split;
858     int imid = 0, iside = 0;
859     //uint32_t N0 = N;
860     int N_B;
861     //int N_B0;
862     int B0 = blocks;
863     int time_divide = 0;
864     int recombine = 0;
865     int inv = 0;
866     float mid = 0, side = 0;
867     int longblocks = (B0 == 1);
868     uint32_t cm = 0;
869
870     //N_B0 = N_B = N / blocks;
871     split = dualstereo = (Y != NULL);
872
873     if (N == 1) {
874         /* special case for one sample - the decoder's output will be +- 1.0f!!! */
875         int i;
876         float *x = X;
877         for (i = 0; i <= dualstereo; i++) {
878             if (f->remaining2 >= 1<<3) {
879                 ff_opus_rc_put_raw(rc, x[0] < 0, 1);
880                 f->remaining2 -= 1 << 3;
881                 b             -= 1 << 3;
882             }
883             x = Y;
884         }
885         if (lowband_out)
886             lowband_out[0] = X[0];
887         return 1;
888     }
889
890     if (!dualstereo && level == 0) {
891         int tf_change = f->tf_change[band];
892         int k;
893         if (tf_change > 0)
894             recombine = tf_change;
895         /* Band recombining to increase frequency resolution */
896
897         if (lowband &&
898             (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
899             int j;
900             for (j = 0; j < N; j++)
901                 lowband_scratch[j] = lowband[j];
902             lowband = lowband_scratch;
903         }
904
905         for (k = 0; k < recombine; k++) {
906             celt_haar1(X, N >> k, 1 << k);
907             fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
908         }
909         blocks >>= recombine;
910         N_B <<= recombine;
911
912         /* Increasing the time resolution */
913         while ((N_B & 1) == 0 && tf_change < 0) {
914             celt_haar1(X, N_B, blocks);
915             fill |= fill << blocks;
916             blocks <<= 1;
917             N_B >>= 1;
918             time_divide++;
919             tf_change++;
920         }
921         B0 = blocks;
922         //N_B0 = N_B;
923
924         /* Reorganize the samples in time order instead of frequency order */
925         if (B0 > 1)
926             celt_deinterleave_hadamard(f->scratch, X, N_B >> recombine,
927                                        B0 << recombine, longblocks);
928     }
929
930     /* If we need 1.5 more bit than we can produce, split the band in two. */
931     cache = ff_celt_cache_bits +
932             ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
933     if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
934         N >>= 1;
935         Y = X + N;
936         split = 1;
937         duration -= 1;
938         if (blocks == 1)
939             fill = (fill & 1) | (fill << 1);
940         blocks = (blocks + 1) >> 1;
941     }
942
943     if (split) {
944         int qn;
945         int itheta = celt_calc_theta(X, Y, dualstereo, N);
946         int mbits, sbits, delta;
947         int qalloc;
948         int pulse_cap;
949         int offset;
950         int orig_fill;
951         int tell;
952
953         /* Decide on the resolution to give to the split parameter theta */
954         pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
955         offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
956                                                           CELT_QTHETA_OFFSET);
957         qn = (dualstereo && band >= f->intensity_stereo) ? 1 :
958              celt_compute_qn(N, b, offset, pulse_cap, dualstereo);
959         tell = opus_rc_tell_frac(rc);
960
961         if (qn != 1) {
962
963             itheta = (itheta*qn + 8192) >> 14;
964
965             /* Entropy coding of the angle. We use a uniform pdf for the
966              * time split, a step for stereo, and a triangular one for the rest. */
967             if (dualstereo && N > 2)
968                 ff_opus_rc_enc_uint_step(rc, itheta, qn / 2);
969             else if (dualstereo || B0 > 1)
970                 ff_opus_rc_enc_uint(rc, itheta, qn + 1);
971             else
972                 ff_opus_rc_enc_uint_tri(rc, itheta, qn);
973             itheta = itheta * 16384 / qn;
974
975             if (dualstereo) {
976                 if (itheta == 0)
977                     celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);
978                 else
979                     celt_stereo_ms_decouple(X, Y, N);
980             }
981         } else if (dualstereo) {
982              inv = itheta > 8192;
983              if (inv)
984              {
985                 int j;
986                 for (j=0;j<N;j++)
987                    Y[j] = -Y[j];
988              }
989              celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);
990
991             if (b > 2 << 3 && f->remaining2 > 2 << 3) {
992                 ff_opus_rc_enc_log(rc, inv, 2);
993             } else {
994                 inv = 0;
995             }
996
997             itheta = 0;
998         }
999         qalloc = opus_rc_tell_frac(rc) - tell;
1000         b -= qalloc;
1001
1002         orig_fill = fill;
1003         if (itheta == 0) {
1004             imid = 32767;
1005             iside = 0;
1006             fill = av_mod_uintp2(fill, blocks);
1007             delta = -16384;
1008         } else if (itheta == 16384) {
1009             imid = 0;
1010             iside = 32767;
1011             fill &= ((1 << blocks) - 1) << blocks;
1012             delta = 16384;
1013         } else {
1014             imid = celt_cos(itheta);
1015             iside = celt_cos(16384-itheta);
1016             /* This is the mid vs side allocation that minimizes squared error
1017             in that band. */
1018             delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
1019         }
1020
1021         mid  = imid  / 32768.0f;
1022         side = iside / 32768.0f;
1023
1024         /* This is a special case for N=2 that only works for stereo and takes
1025         advantage of the fact that mid and side are orthogonal to encode
1026         the side with just one bit. */
1027         if (N == 2 && dualstereo) {
1028             int c;
1029             int sign = 0;
1030             float tmp;
1031             float *x2, *y2;
1032             mbits = b;
1033             /* Only need one bit for the side */
1034             sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
1035             mbits -= sbits;
1036             c = (itheta > 8192);
1037             f->remaining2 -= qalloc+sbits;
1038
1039             x2 = c ? Y : X;
1040             y2 = c ? X : Y;
1041             if (sbits) {
1042                 sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
1043                 ff_opus_rc_put_raw(rc, sign, 1);
1044             }
1045             sign = 1 - 2 * sign;
1046             /* We use orig_fill here because we want to fold the side, but if
1047             itheta==16384, we'll have cleared the low bits of fill. */
1048             cm = ff_celt_encode_band(f, rc, band, x2, NULL, N, mbits, blocks,
1049                                      lowband, duration, lowband_out, level, gain,
1050                                      lowband_scratch, orig_fill);
1051             /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
1052             and there's no need to worry about mixing with the other channel. */
1053             y2[0] = -sign * x2[1];
1054             y2[1] =  sign * x2[0];
1055             X[0] *= mid;
1056             X[1] *= mid;
1057             Y[0] *= side;
1058             Y[1] *= side;
1059             tmp = X[0];
1060             X[0] = tmp - Y[0];
1061             Y[0] = tmp + Y[0];
1062             tmp = X[1];
1063             X[1] = tmp - Y[1];
1064             Y[1] = tmp + Y[1];
1065         } else {
1066             /* "Normal" split code */
1067             float *next_lowband2     = NULL;
1068             float *next_lowband_out1 = NULL;
1069             int next_level = 0;
1070             int rebalance;
1071
1072             /* Give more bits to low-energy MDCTs than they would
1073              * otherwise deserve */
1074             if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {
1075                 if (itheta > 8192)
1076                     /* Rough approximation for pre-echo masking */
1077                     delta -= delta >> (4 - duration);
1078                 else
1079                     /* Corresponds to a forward-masking slope of
1080                      * 1.5 dB per 10 ms */
1081                     delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
1082             }
1083             mbits = av_clip((b - delta) / 2, 0, b);
1084             sbits = b - mbits;
1085             f->remaining2 -= qalloc;
1086
1087             if (lowband && !dualstereo)
1088                 next_lowband2 = lowband + N; /* >32-bit split case */
1089
1090             /* Only stereo needs to pass on lowband_out.
1091              * Otherwise, it's handled at the end */
1092             if (dualstereo)
1093                 next_lowband_out1 = lowband_out;
1094             else
1095                 next_level = level + 1;
1096
1097             rebalance = f->remaining2;
1098             if (mbits >= sbits) {
1099                 /* In stereo mode, we do not apply a scaling to the mid
1100                  * because we need the normalized mid for folding later */
1101                 cm = ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1102                                          lowband, duration, next_lowband_out1,
1103                                          next_level, dualstereo ? 1.0f : (gain * mid),
1104                                          lowband_scratch, fill);
1105
1106                 rebalance = mbits - (rebalance - f->remaining2);
1107                 if (rebalance > 3 << 3 && itheta != 0)
1108                     sbits += rebalance - (3 << 3);
1109
1110                 /* For a stereo split, the high bits of fill are always zero,
1111                  * so no folding will be done to the side. */
1112                 cm |= ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1113                                           next_lowband2, duration, NULL,
1114                                           next_level, gain * side, NULL,
1115                                           fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
1116             } else {
1117                 /* For a stereo split, the high bits of fill are always zero,
1118                  * so no folding will be done to the side. */
1119                 cm = ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1120                                          next_lowband2, duration, NULL,
1121                                          next_level, gain * side, NULL,
1122                                          fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
1123
1124                 rebalance = sbits - (rebalance - f->remaining2);
1125                 if (rebalance > 3 << 3 && itheta != 16384)
1126                     mbits += rebalance - (3 << 3);
1127
1128                 /* In stereo mode, we do not apply a scaling to the mid because
1129                  * we need the normalized mid for folding later */
1130                 cm |= ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1131                                           lowband, duration, next_lowband_out1,
1132                                           next_level, dualstereo ? 1.0f : (gain * mid),
1133                                           lowband_scratch, fill);
1134             }
1135         }
1136     } else {
1137         /* This is the basic no-split case */
1138         uint32_t q         = celt_bits2pulses(cache, b);
1139         uint32_t curr_bits = celt_pulses2bits(cache, q);
1140         f->remaining2 -= curr_bits;
1141
1142         /* Ensures we can never bust the budget */
1143         while (f->remaining2 < 0 && q > 0) {
1144             f->remaining2 += curr_bits;
1145             curr_bits      = celt_pulses2bits(cache, --q);
1146             f->remaining2 -= curr_bits;
1147         }
1148
1149         if (q != 0) {
1150             /* Finally do the actual quantization */
1151             cm = celt_alg_quant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
1152                                 f->spread, blocks, gain);
1153         }
1154     }
1155
1156     return cm;
1157 }