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