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