OSDN Git Service

opus_pvq: improve PVQ search for low Ks
[android-x86/external-ffmpeg.git] / 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, uint32_t K, 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     av_assert0(sum == K);
289     return idx;
290 }
291
292 // this code was adapted from libopus
293 static inline uint64_t celt_cwrsi(uint32_t N, uint32_t K, uint32_t i, int *y)
294 {
295     uint64_t norm = 0;
296     uint32_t p;
297     int s, val;
298     int k0;
299
300     while (N > 2) {
301         uint32_t q;
302
303         /*Lots of pulses case:*/
304         if (K >= N) {
305             const uint32_t *row = ff_celt_pvq_u_row[N];
306
307             /* Are the pulses in this dimension negative? */
308             p  = row[K + 1];
309             s  = -(i >= p);
310             i -= p & s;
311
312             /*Count how many pulses were placed in this dimension.*/
313             k0 = K;
314             q = row[N];
315             if (q > i) {
316                 K = N;
317                 do {
318                     p = ff_celt_pvq_u_row[--K][N];
319                 } while (p > i);
320             } else
321                 for (p = row[K]; p > i; p = row[K])
322                     K--;
323
324             i    -= p;
325             val   = (k0 - K + s) ^ s;
326             norm += val * val;
327             *y++  = val;
328         } else { /*Lots of dimensions case:*/
329             /*Are there any pulses in this dimension at all?*/
330             p = ff_celt_pvq_u_row[K    ][N];
331             q = ff_celt_pvq_u_row[K + 1][N];
332
333             if (p <= i && i < q) {
334                 i -= p;
335                 *y++ = 0;
336             } else {
337                 /*Are the pulses in this dimension negative?*/
338                 s  = -(i >= q);
339                 i -= q & s;
340
341                 /*Count how many pulses were placed in this dimension.*/
342                 k0 = K;
343                 do p = ff_celt_pvq_u_row[--K][N];
344                 while (p > i);
345
346                 i    -= p;
347                 val   = (k0 - K + s) ^ s;
348                 norm += val * val;
349                 *y++  = val;
350             }
351         }
352         N--;
353     }
354
355     /* N == 2 */
356     p  = 2 * K + 1;
357     s  = -(i >= p);
358     i -= p & s;
359     k0 = K;
360     K  = (i + 1) / 2;
361
362     if (K)
363         i -= 2 * K - 1;
364
365     val   = (k0 - K + s) ^ s;
366     norm += val * val;
367     *y++  = val;
368
369     /* N==1 */
370     s     = -i;
371     val   = (K + s) ^ s;
372     norm += val * val;
373     *y    = val;
374
375     return norm;
376 }
377
378 static inline void celt_encode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
379 {
380     ff_opus_rc_enc_uint(rc, celt_icwrsi(N, K, y), CELT_PVQ_V(N, K));
381 }
382
383 static inline float celt_decode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
384 {
385     const uint32_t idx = ff_opus_rc_dec_uint(rc, CELT_PVQ_V(N, K));
386     return celt_cwrsi(N, K, idx, y);
387 }
388
389 /*
390  * Faster than libopus's search, operates entirely in the signed domain.
391  * Slightly worse/better depending on N, K and the input vector.
392  */
393 static void celt_pvq_search(float *X, int *y, int K, int N)
394 {
395     int i;
396     float res = 0.0f, y_norm = 0.0f, xy_norm = 0.0f;
397
398     for (i = 0; i < N; i++)
399         res += FFABS(X[i]);
400
401     res = K/res;
402
403     for (i = 0; i < N; i++) {
404         y[i] = lrintf(res*X[i]);
405         y_norm  += y[i]*y[i];
406         xy_norm += y[i]*X[i];
407         K -= FFABS(y[i]);
408     }
409
410     while (K) {
411         int max_idx = 0, phase = FFSIGN(K);
412         float max_den = 1.0f, max_num = 0.0f;
413         y_norm += 1.0f;
414
415         for (i = 0; i < N; i++) {
416             /* If the sum has been overshot and the best place has 0 pulses allocated
417              * to it, attempting to decrease it further will actually increase the
418              * sum. Prevent this by disregarding any 0 positions when decrementing. */
419             const int ca = 1 ^ ((y[i] == 0) & (phase < 0));
420             float xy_new = xy_norm + 1*phase*FFABS(X[i]);
421             float y_new  = y_norm  + 2*phase*FFABS(y[i]);
422             xy_new = xy_new * xy_new;
423             if (ca && (max_den*xy_new) > (y_new*max_num)) {
424                 max_den = y_new;
425                 max_num = xy_new;
426                 max_idx = i;
427             }
428         }
429
430         K -= phase;
431
432         phase *= FFSIGN(X[max_idx]);
433         xy_norm += 1*phase*X[max_idx];
434         y_norm  += 2*phase*y[max_idx];
435         y[max_idx] += phase;
436     }
437 }
438
439 static uint32_t celt_alg_quant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
440                                enum CeltSpread spread, uint32_t blocks, float gain)
441 {
442     int y[176];
443
444     celt_exp_rotation(X, N, blocks, K, spread, 1);
445     celt_pvq_search(X, y, K, N);
446     celt_encode_pulses(rc, y,  N, K);
447     return celt_extract_collapse_mask(y, N, blocks);
448 }
449
450 /** Decode pulse vector and combine the result with the pitch vector to produce
451     the final normalised signal in the current band. */
452 static uint32_t celt_alg_unquant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
453                                  enum CeltSpread spread, uint32_t blocks, float gain)
454 {
455     int y[176];
456
457     gain /= sqrtf(celt_decode_pulses(rc, y, N, K));
458     celt_normalize_residual(y, X, N, gain);
459     celt_exp_rotation(X, N, blocks, K, spread, 0);
460     return celt_extract_collapse_mask(y, N, blocks);
461 }
462
463 uint32_t ff_celt_decode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
464                              float *X, float *Y, int N, int b, uint32_t blocks,
465                              float *lowband, int duration, float *lowband_out, int level,
466                              float gain, float *lowband_scratch, int fill)
467 {
468     const uint8_t *cache;
469     int dualstereo, split;
470     int imid = 0, iside = 0;
471     uint32_t N0 = N;
472     int N_B;
473     int N_B0;
474     int B0 = blocks;
475     int time_divide = 0;
476     int recombine = 0;
477     int inv = 0;
478     float mid = 0, side = 0;
479     int longblocks = (B0 == 1);
480     uint32_t cm = 0;
481
482     N_B0 = N_B = N / blocks;
483     split = dualstereo = (Y != NULL);
484
485     if (N == 1) {
486         /* special case for one sample */
487         int i;
488         float *x = X;
489         for (i = 0; i <= dualstereo; i++) {
490             int sign = 0;
491             if (f->remaining2 >= 1<<3) {
492                 sign           = ff_opus_rc_get_raw(rc, 1);
493                 f->remaining2 -= 1 << 3;
494                 b             -= 1 << 3;
495             }
496             x[0] = sign ? -1.0f : 1.0f;
497             x = Y;
498         }
499         if (lowband_out)
500             lowband_out[0] = X[0];
501         return 1;
502     }
503
504     if (!dualstereo && level == 0) {
505         int tf_change = f->tf_change[band];
506         int k;
507         if (tf_change > 0)
508             recombine = tf_change;
509         /* Band recombining to increase frequency resolution */
510
511         if (lowband &&
512             (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
513             int j;
514             for (j = 0; j < N; j++)
515                 lowband_scratch[j] = lowband[j];
516             lowband = lowband_scratch;
517         }
518
519         for (k = 0; k < recombine; k++) {
520             if (lowband)
521                 celt_haar1(lowband, N >> k, 1 << k);
522             fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
523         }
524         blocks >>= recombine;
525         N_B <<= recombine;
526
527         /* Increasing the time resolution */
528         while ((N_B & 1) == 0 && tf_change < 0) {
529             if (lowband)
530                 celt_haar1(lowband, N_B, blocks);
531             fill |= fill << blocks;
532             blocks <<= 1;
533             N_B >>= 1;
534             time_divide++;
535             tf_change++;
536         }
537         B0 = blocks;
538         N_B0 = N_B;
539
540         /* Reorganize the samples in time order instead of frequency order */
541         if (B0 > 1 && lowband)
542             celt_deinterleave_hadamard(f->scratch, lowband, N_B >> recombine,
543                                        B0 << recombine, longblocks);
544     }
545
546     /* If we need 1.5 more bit than we can produce, split the band in two. */
547     cache = ff_celt_cache_bits +
548             ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
549     if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
550         N >>= 1;
551         Y = X + N;
552         split = 1;
553         duration -= 1;
554         if (blocks == 1)
555             fill = (fill & 1) | (fill << 1);
556         blocks = (blocks + 1) >> 1;
557     }
558
559     if (split) {
560         int qn;
561         int itheta = 0;
562         int mbits, sbits, delta;
563         int qalloc;
564         int pulse_cap;
565         int offset;
566         int orig_fill;
567         int tell;
568
569         /* Decide on the resolution to give to the split parameter theta */
570         pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
571         offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
572                                                           CELT_QTHETA_OFFSET);
573         qn = (dualstereo && band >= f->intensity_stereo) ? 1 :
574              celt_compute_qn(N, b, offset, pulse_cap, dualstereo);
575         tell = opus_rc_tell_frac(rc);
576         if (qn != 1) {
577             /* Entropy coding of the angle. We use a uniform pdf for the
578             time split, a step for stereo, and a triangular one for the rest. */
579             if (dualstereo && N > 2)
580                 itheta = ff_opus_rc_dec_uint_step(rc, qn/2);
581             else if (dualstereo || B0 > 1)
582                 itheta = ff_opus_rc_dec_uint(rc, qn+1);
583             else
584                 itheta = ff_opus_rc_dec_uint_tri(rc, qn);
585             itheta = itheta * 16384 / qn;
586             /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.
587             Let's do that at higher complexity */
588         } else if (dualstereo) {
589             inv = (b > 2 << 3 && f->remaining2 > 2 << 3) ? ff_opus_rc_dec_log(rc, 2) : 0;
590             itheta = 0;
591         }
592         qalloc = opus_rc_tell_frac(rc) - tell;
593         b -= qalloc;
594
595         orig_fill = fill;
596         if (itheta == 0) {
597             imid = 32767;
598             iside = 0;
599             fill = av_mod_uintp2(fill, blocks);
600             delta = -16384;
601         } else if (itheta == 16384) {
602             imid = 0;
603             iside = 32767;
604             fill &= ((1 << blocks) - 1) << blocks;
605             delta = 16384;
606         } else {
607             imid = celt_cos(itheta);
608             iside = celt_cos(16384-itheta);
609             /* This is the mid vs side allocation that minimizes squared error
610             in that band. */
611             delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
612         }
613
614         mid  = imid  / 32768.0f;
615         side = iside / 32768.0f;
616
617         /* This is a special case for N=2 that only works for stereo and takes
618         advantage of the fact that mid and side are orthogonal to encode
619         the side with just one bit. */
620         if (N == 2 && dualstereo) {
621             int c;
622             int sign = 0;
623             float tmp;
624             float *x2, *y2;
625             mbits = b;
626             /* Only need one bit for the side */
627             sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
628             mbits -= sbits;
629             c = (itheta > 8192);
630             f->remaining2 -= qalloc+sbits;
631
632             x2 = c ? Y : X;
633             y2 = c ? X : Y;
634             if (sbits)
635                 sign = ff_opus_rc_get_raw(rc, 1);
636             sign = 1 - 2 * sign;
637             /* We use orig_fill here because we want to fold the side, but if
638             itheta==16384, we'll have cleared the low bits of fill. */
639             cm = ff_celt_decode_band(f, rc, band, x2, NULL, N, mbits, blocks,
640                                      lowband, duration, lowband_out, level, gain,
641                                      lowband_scratch, orig_fill);
642             /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
643             and there's no need to worry about mixing with the other channel. */
644             y2[0] = -sign * x2[1];
645             y2[1] =  sign * x2[0];
646             X[0] *= mid;
647             X[1] *= mid;
648             Y[0] *= side;
649             Y[1] *= side;
650             tmp = X[0];
651             X[0] = tmp - Y[0];
652             Y[0] = tmp + Y[0];
653             tmp = X[1];
654             X[1] = tmp - Y[1];
655             Y[1] = tmp + Y[1];
656         } else {
657             /* "Normal" split code */
658             float *next_lowband2     = NULL;
659             float *next_lowband_out1 = NULL;
660             int next_level = 0;
661             int rebalance;
662
663             /* Give more bits to low-energy MDCTs than they would
664              * otherwise deserve */
665             if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {
666                 if (itheta > 8192)
667                     /* Rough approximation for pre-echo masking */
668                     delta -= delta >> (4 - duration);
669                 else
670                     /* Corresponds to a forward-masking slope of
671                      * 1.5 dB per 10 ms */
672                     delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
673             }
674             mbits = av_clip((b - delta) / 2, 0, b);
675             sbits = b - mbits;
676             f->remaining2 -= qalloc;
677
678             if (lowband && !dualstereo)
679                 next_lowband2 = lowband + N; /* >32-bit split case */
680
681             /* Only stereo needs to pass on lowband_out.
682              * Otherwise, it's handled at the end */
683             if (dualstereo)
684                 next_lowband_out1 = lowband_out;
685             else
686                 next_level = level + 1;
687
688             rebalance = f->remaining2;
689             if (mbits >= sbits) {
690                 /* In stereo mode, we do not apply a scaling to the mid
691                  * because we need the normalized mid for folding later */
692                 cm = ff_celt_decode_band(f, rc, band, X, NULL, N, mbits, blocks,
693                                          lowband, duration, next_lowband_out1,
694                                          next_level, dualstereo ? 1.0f : (gain * mid),
695                                          lowband_scratch, fill);
696
697                 rebalance = mbits - (rebalance - f->remaining2);
698                 if (rebalance > 3 << 3 && itheta != 0)
699                     sbits += rebalance - (3 << 3);
700
701                 /* For a stereo split, the high bits of fill are always zero,
702                  * so no folding will be done to the side. */
703                 cm |= ff_celt_decode_band(f, rc, band, Y, NULL, N, sbits, blocks,
704                                           next_lowband2, duration, NULL,
705                                           next_level, gain * side, NULL,
706                                           fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
707             } else {
708                 /* For a stereo split, the high bits of fill are always zero,
709                  * so no folding will be done to the side. */
710                 cm = ff_celt_decode_band(f, rc, band, Y, NULL, N, sbits, blocks,
711                                          next_lowband2, duration, NULL,
712                                          next_level, gain * side, NULL,
713                                          fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
714
715                 rebalance = sbits - (rebalance - f->remaining2);
716                 if (rebalance > 3 << 3 && itheta != 16384)
717                     mbits += rebalance - (3 << 3);
718
719                 /* In stereo mode, we do not apply a scaling to the mid because
720                  * we need the normalized mid for folding later */
721                 cm |= ff_celt_decode_band(f, rc, band, X, NULL, N, mbits, blocks,
722                                           lowband, duration, next_lowband_out1,
723                                           next_level, dualstereo ? 1.0f : (gain * mid),
724                                           lowband_scratch, fill);
725             }
726         }
727     } else {
728         /* This is the basic no-split case */
729         uint32_t q         = celt_bits2pulses(cache, b);
730         uint32_t curr_bits = celt_pulses2bits(cache, q);
731         f->remaining2 -= curr_bits;
732
733         /* Ensures we can never bust the budget */
734         while (f->remaining2 < 0 && q > 0) {
735             f->remaining2 += curr_bits;
736             curr_bits      = celt_pulses2bits(cache, --q);
737             f->remaining2 -= curr_bits;
738         }
739
740         if (q != 0) {
741             /* Finally do the actual quantization */
742             cm = celt_alg_unquant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
743                                   f->spread, blocks, gain);
744         } else {
745             /* If there's no pulse, fill the band anyway */
746             int j;
747             uint32_t cm_mask = (1 << blocks) - 1;
748             fill &= cm_mask;
749             if (!fill) {
750                 for (j = 0; j < N; j++)
751                     X[j] = 0.0f;
752             } else {
753                 if (!lowband) {
754                     /* Noise */
755                     for (j = 0; j < N; j++)
756                         X[j] = (((int32_t)celt_rng(f)) >> 20);
757                     cm = cm_mask;
758                 } else {
759                     /* Folded spectrum */
760                     for (j = 0; j < N; j++) {
761                         /* About 48 dB below the "normal" folding level */
762                         X[j] = lowband[j] + (((celt_rng(f)) & 0x8000) ? 1.0f / 256 : -1.0f / 256);
763                     }
764                     cm = fill;
765                 }
766                 celt_renormalize_vector(X, N, gain);
767             }
768         }
769     }
770
771     /* This code is used by the decoder and by the resynthesis-enabled encoder */
772     if (dualstereo) {
773         int j;
774         if (N != 2)
775             celt_stereo_merge(X, Y, mid, N);
776         if (inv) {
777             for (j = 0; j < N; j++)
778                 Y[j] *= -1;
779         }
780     } else if (level == 0) {
781         int k;
782
783         /* Undo the sample reorganization going from time order to frequency order */
784         if (B0 > 1)
785             celt_interleave_hadamard(f->scratch, X, N_B>>recombine,
786                                      B0<<recombine, longblocks);
787
788         /* Undo time-freq changes that we did earlier */
789         N_B = N_B0;
790         blocks = B0;
791         for (k = 0; k < time_divide; k++) {
792             blocks >>= 1;
793             N_B <<= 1;
794             cm |= cm >> blocks;
795             celt_haar1(X, N_B, blocks);
796         }
797
798         for (k = 0; k < recombine; k++) {
799             cm = ff_celt_bit_deinterleave[cm];
800             celt_haar1(X, N0>>k, 1<<k);
801         }
802         blocks <<= recombine;
803
804         /* Scale output for later folding */
805         if (lowband_out) {
806             int j;
807             float n = sqrtf(N0);
808             for (j = 0; j < N0; j++)
809                 lowband_out[j] = n * X[j];
810         }
811         cm = av_mod_uintp2(cm, blocks);
812     }
813
814     return cm;
815 }
816
817 /* This has to be, AND MUST BE done by the psychoacoustic system, this has a very
818  * big impact on the entire quantization and especially huge on transients */
819 static int celt_calc_theta(const float *X, const float *Y, int coupling, int N)
820 {
821     int j;
822     float e[2] = { 0.0f, 0.0f };
823     for (j = 0; j < N; j++) {
824         if (coupling) { /* Coupling case */
825             e[0] += (X[j] + Y[j])*(X[j] + Y[j]);
826             e[1] += (X[j] - Y[j])*(X[j] - Y[j]);
827         } else {
828             e[0] += X[j]*X[j];
829             e[1] += Y[j]*Y[j];
830         }
831     }
832     return lrintf(32768.0f*atan2f(sqrtf(e[1]), sqrtf(e[0]))/M_PI);
833 }
834
835 static void celt_stereo_is_decouple(float *X, float *Y, float e_l, float e_r, int N)
836 {
837     int i;
838     const float energy_n = 1.0f/(sqrtf(e_l*e_l + e_r*e_r) + FLT_EPSILON);
839     e_l *= energy_n;
840     e_r *= energy_n;
841     for (i = 0; i < N; i++)
842         X[i] = e_l*X[i] + e_r*Y[i];
843 }
844
845 static void celt_stereo_ms_decouple(float *X, float *Y, int N)
846 {
847     int i;
848     const float decouple_norm = 1.0f/sqrtf(2.0f);
849     for (i = 0; i < N; i++) {
850         const float Xret = X[i];
851         X[i] = (X[i] + Y[i])*decouple_norm;
852         Y[i] = (Y[i] - Xret)*decouple_norm;
853     }
854 }
855
856 uint32_t ff_celt_encode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
857                              float *X, float *Y, int N, int b, uint32_t blocks,
858                              float *lowband, int duration, float *lowband_out, int level,
859                              float gain, float *lowband_scratch, int fill)
860 {
861     const uint8_t *cache;
862     int dualstereo, split;
863     int imid = 0, iside = 0;
864     //uint32_t N0 = N;
865     int N_B = N / blocks;
866     //int N_B0 = N_B;
867     int B0 = blocks;
868     int time_divide = 0;
869     int recombine = 0;
870     int inv = 0;
871     float mid = 0, side = 0;
872     int longblocks = (B0 == 1);
873     uint32_t cm = 0;
874
875     split = dualstereo = (Y != NULL);
876
877     if (N == 1) {
878         /* special case for one sample - the decoder's output will be +- 1.0f!!! */
879         int i;
880         float *x = X;
881         for (i = 0; i <= dualstereo; i++) {
882             if (f->remaining2 >= 1<<3) {
883                 ff_opus_rc_put_raw(rc, x[0] < 0, 1);
884                 f->remaining2 -= 1 << 3;
885                 b             -= 1 << 3;
886             }
887             x = Y;
888         }
889         if (lowband_out)
890             lowband_out[0] = X[0];
891         return 1;
892     }
893
894     if (!dualstereo && level == 0) {
895         int tf_change = f->tf_change[band];
896         int k;
897         if (tf_change > 0)
898             recombine = tf_change;
899         /* Band recombining to increase frequency resolution */
900
901         if (lowband &&
902             (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
903             int j;
904             for (j = 0; j < N; j++)
905                 lowband_scratch[j] = lowband[j];
906             lowband = lowband_scratch;
907         }
908
909         for (k = 0; k < recombine; k++) {
910             celt_haar1(X, N >> k, 1 << k);
911             fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
912         }
913         blocks >>= recombine;
914         N_B <<= recombine;
915
916         /* Increasing the time resolution */
917         while ((N_B & 1) == 0 && tf_change < 0) {
918             celt_haar1(X, N_B, blocks);
919             fill |= fill << blocks;
920             blocks <<= 1;
921             N_B >>= 1;
922             time_divide++;
923             tf_change++;
924         }
925         B0 = blocks;
926         //N_B0 = N_B;
927
928         /* Reorganize the samples in time order instead of frequency order */
929         if (B0 > 1)
930             celt_deinterleave_hadamard(f->scratch, X, N_B >> recombine,
931                                        B0 << recombine, longblocks);
932     }
933
934     /* If we need 1.5 more bit than we can produce, split the band in two. */
935     cache = ff_celt_cache_bits +
936             ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
937     if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
938         N >>= 1;
939         Y = X + N;
940         split = 1;
941         duration -= 1;
942         if (blocks == 1)
943             fill = (fill & 1) | (fill << 1);
944         blocks = (blocks + 1) >> 1;
945     }
946
947     if (split) {
948         int qn;
949         int itheta = celt_calc_theta(X, Y, dualstereo, N);
950         int mbits, sbits, delta;
951         int qalloc;
952         int pulse_cap;
953         int offset;
954         int orig_fill;
955         int tell;
956
957         /* Decide on the resolution to give to the split parameter theta */
958         pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
959         offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
960                                                           CELT_QTHETA_OFFSET);
961         qn = (dualstereo && band >= f->intensity_stereo) ? 1 :
962              celt_compute_qn(N, b, offset, pulse_cap, dualstereo);
963         tell = opus_rc_tell_frac(rc);
964
965         if (qn != 1) {
966
967             itheta = (itheta*qn + 8192) >> 14;
968
969             /* Entropy coding of the angle. We use a uniform pdf for the
970              * time split, a step for stereo, and a triangular one for the rest. */
971             if (dualstereo && N > 2)
972                 ff_opus_rc_enc_uint_step(rc, itheta, qn / 2);
973             else if (dualstereo || B0 > 1)
974                 ff_opus_rc_enc_uint(rc, itheta, qn + 1);
975             else
976                 ff_opus_rc_enc_uint_tri(rc, itheta, qn);
977             itheta = itheta * 16384 / qn;
978
979             if (dualstereo) {
980                 if (itheta == 0)
981                     celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);
982                 else
983                     celt_stereo_ms_decouple(X, Y, N);
984             }
985         } else if (dualstereo) {
986              inv = itheta > 8192;
987              if (inv)
988              {
989                 int j;
990                 for (j=0;j<N;j++)
991                    Y[j] = -Y[j];
992              }
993              celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);
994
995             if (b > 2 << 3 && f->remaining2 > 2 << 3) {
996                 ff_opus_rc_enc_log(rc, inv, 2);
997             } else {
998                 inv = 0;
999             }
1000
1001             itheta = 0;
1002         }
1003         qalloc = opus_rc_tell_frac(rc) - tell;
1004         b -= qalloc;
1005
1006         orig_fill = fill;
1007         if (itheta == 0) {
1008             imid = 32767;
1009             iside = 0;
1010             fill = av_mod_uintp2(fill, blocks);
1011             delta = -16384;
1012         } else if (itheta == 16384) {
1013             imid = 0;
1014             iside = 32767;
1015             fill &= ((1 << blocks) - 1) << blocks;
1016             delta = 16384;
1017         } else {
1018             imid = celt_cos(itheta);
1019             iside = celt_cos(16384-itheta);
1020             /* This is the mid vs side allocation that minimizes squared error
1021             in that band. */
1022             delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
1023         }
1024
1025         mid  = imid  / 32768.0f;
1026         side = iside / 32768.0f;
1027
1028         /* This is a special case for N=2 that only works for stereo and takes
1029         advantage of the fact that mid and side are orthogonal to encode
1030         the side with just one bit. */
1031         if (N == 2 && dualstereo) {
1032             int c;
1033             int sign = 0;
1034             float tmp;
1035             float *x2, *y2;
1036             mbits = b;
1037             /* Only need one bit for the side */
1038             sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
1039             mbits -= sbits;
1040             c = (itheta > 8192);
1041             f->remaining2 -= qalloc+sbits;
1042
1043             x2 = c ? Y : X;
1044             y2 = c ? X : Y;
1045             if (sbits) {
1046                 sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
1047                 ff_opus_rc_put_raw(rc, sign, 1);
1048             }
1049             sign = 1 - 2 * sign;
1050             /* We use orig_fill here because we want to fold the side, but if
1051             itheta==16384, we'll have cleared the low bits of fill. */
1052             cm = ff_celt_encode_band(f, rc, band, x2, NULL, N, mbits, blocks,
1053                                      lowband, duration, lowband_out, level, gain,
1054                                      lowband_scratch, orig_fill);
1055             /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
1056             and there's no need to worry about mixing with the other channel. */
1057             y2[0] = -sign * x2[1];
1058             y2[1] =  sign * x2[0];
1059             X[0] *= mid;
1060             X[1] *= mid;
1061             Y[0] *= side;
1062             Y[1] *= side;
1063             tmp = X[0];
1064             X[0] = tmp - Y[0];
1065             Y[0] = tmp + Y[0];
1066             tmp = X[1];
1067             X[1] = tmp - Y[1];
1068             Y[1] = tmp + Y[1];
1069         } else {
1070             /* "Normal" split code */
1071             float *next_lowband2     = NULL;
1072             float *next_lowband_out1 = NULL;
1073             int next_level = 0;
1074             int rebalance;
1075
1076             /* Give more bits to low-energy MDCTs than they would
1077              * otherwise deserve */
1078             if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {
1079                 if (itheta > 8192)
1080                     /* Rough approximation for pre-echo masking */
1081                     delta -= delta >> (4 - duration);
1082                 else
1083                     /* Corresponds to a forward-masking slope of
1084                      * 1.5 dB per 10 ms */
1085                     delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
1086             }
1087             mbits = av_clip((b - delta) / 2, 0, b);
1088             sbits = b - mbits;
1089             f->remaining2 -= qalloc;
1090
1091             if (lowband && !dualstereo)
1092                 next_lowband2 = lowband + N; /* >32-bit split case */
1093
1094             /* Only stereo needs to pass on lowband_out.
1095              * Otherwise, it's handled at the end */
1096             if (dualstereo)
1097                 next_lowband_out1 = lowband_out;
1098             else
1099                 next_level = level + 1;
1100
1101             rebalance = f->remaining2;
1102             if (mbits >= sbits) {
1103                 /* In stereo mode, we do not apply a scaling to the mid
1104                  * because we need the normalized mid for folding later */
1105                 cm = ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1106                                          lowband, duration, next_lowband_out1,
1107                                          next_level, dualstereo ? 1.0f : (gain * mid),
1108                                          lowband_scratch, fill);
1109
1110                 rebalance = mbits - (rebalance - f->remaining2);
1111                 if (rebalance > 3 << 3 && itheta != 0)
1112                     sbits += rebalance - (3 << 3);
1113
1114                 /* For a stereo split, the high bits of fill are always zero,
1115                  * so no folding will be done to the side. */
1116                 cm |= ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1117                                           next_lowband2, duration, NULL,
1118                                           next_level, gain * side, NULL,
1119                                           fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
1120             } else {
1121                 /* For a stereo split, the high bits of fill are always zero,
1122                  * so no folding will be done to the side. */
1123                 cm = ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1124                                          next_lowband2, duration, NULL,
1125                                          next_level, gain * side, NULL,
1126                                          fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
1127
1128                 rebalance = sbits - (rebalance - f->remaining2);
1129                 if (rebalance > 3 << 3 && itheta != 16384)
1130                     mbits += rebalance - (3 << 3);
1131
1132                 /* In stereo mode, we do not apply a scaling to the mid because
1133                  * we need the normalized mid for folding later */
1134                 cm |= ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1135                                           lowband, duration, next_lowband_out1,
1136                                           next_level, dualstereo ? 1.0f : (gain * mid),
1137                                           lowband_scratch, fill);
1138             }
1139         }
1140     } else {
1141         /* This is the basic no-split case */
1142         uint32_t q         = celt_bits2pulses(cache, b);
1143         uint32_t curr_bits = celt_pulses2bits(cache, q);
1144         f->remaining2 -= curr_bits;
1145
1146         /* Ensures we can never bust the budget */
1147         while (f->remaining2 < 0 && q > 0) {
1148             f->remaining2 += curr_bits;
1149             curr_bits      = celt_pulses2bits(cache, --q);
1150             f->remaining2 -= curr_bits;
1151         }
1152
1153         if (q != 0) {
1154             /* Finally do the actual quantization */
1155             cm = celt_alg_quant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
1156                                 f->spread, blocks, gain);
1157         }
1158     }
1159
1160     return cm;
1161 }