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