2 * Copyright (c) 2012 Andrew D'Addesio
3 * Copyright (c) 2013-2014 Mozilla Corporation
4 * Copyright (c) 2017 Rostislav Pehlivanov <atomnuker@gmail.com>
6 * This file is part of FFmpeg.
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.
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.
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
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))
29 static inline int16_t celt_cos(int16_t x)
31 x = (MUL16(x, x) + 4096) >> 13;
32 x = (32767-x) + ROUND_MUL16(x, (-7651 + ROUND_MUL16(x, (8277 + ROUND_MUL16(-626, x)))));
36 static inline int celt_log2tan(int isin, int icos)
43 return (ls << 11) - (lc << 11) +
44 ROUND_MUL16(isin, ROUND_MUL16(isin, -2597) + 7932) -
45 ROUND_MUL16(icos, ROUND_MUL16(icos, -2597) + 7932);
48 static inline int celt_bits2pulses(const uint8_t *cache, int bits)
50 // TODO: Find the size of cache and make it into an array in the parameters list
56 for (i = 0; i < 6; i++) {
57 int center = (low + high + 1) >> 1;
58 if (cache[center] >= bits)
64 return (bits - (low == 0 ? -1 : cache[low]) <= cache[high] - bits) ? low : high;
67 static inline int celt_pulses2bits(const uint8_t *cache, int pulses)
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;
73 static inline void celt_normalize_residual(const int * av_restrict iy, float * av_restrict X,
77 for (i = 0; i < N; i++)
81 static void celt_exp_rotation_impl(float *X, uint32_t len, uint32_t stride,
88 for (i = 0; i < len - stride; i++) {
92 Xptr[stride] = c * x2 + s * x1;
93 *Xptr++ = c * x1 - s * x2;
96 Xptr = &X[len - 2 * stride - 1];
97 for (i = len - 2 * stride - 1; i >= 0; i--) {
101 Xptr[stride] = c * x2 + s * x1;
102 *Xptr-- = c * x1 - s * x2;
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)
110 uint32_t stride2 = 0;
115 if (2*K >= len || spread == CELT_SPREAD_NONE)
118 gain = (float)len / (len + (20 - 5*spread) * K);
119 theta = M_PI * gain * gain / 4;
124 if (len >= stride << 3) {
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)
132 /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
133 extract_collapse_mask().*/
135 for (i = 0; i < stride; i++) {
137 celt_exp_rotation_impl(X + i * len, len, 1, c, -s);
139 celt_exp_rotation_impl(X + i * len, len, stride2, s, -c);
142 celt_exp_rotation_impl(X + i * len, len, stride2, s, c);
143 celt_exp_rotation_impl(X + i * len, len, 1, c, s);
148 static inline uint32_t celt_extract_collapse_mask(const int *iy, uint32_t N, uint32_t B)
150 uint32_t collapse_mask;
157 /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
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;
167 static inline void celt_stereo_merge(float *X, float *Y, float mid, int N)
170 float xp = 0, side = 0;
175 /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
176 for (i = 0; i < N; i++) {
181 /* Compensating for the mid normalization */
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++)
193 gain[0] = 1.0f / sqrtf(t);
195 gain[1] = 1.0f / sqrtf(t);
197 for (i = 0; i < N; i++) {
199 /* Apply mid scaling (side is already scaled) */
200 value[0] = mid * X[i];
202 X[i] = gain[0] * (value[0] - value[1]);
203 Y[i] = gain[1] * (value[0] + value[1]);
207 static void celt_interleave_hadamard(float *tmp, float *X, int N0,
208 int stride, int 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];
219 for (i = 0; i < stride; i++)
220 for (j = 0; j < N0; j++)
221 tmp[j*stride+i] = X[i*N0+j];
224 for (i = 0; i < N; i++)
228 static void celt_deinterleave_hadamard(float *tmp, float *X, int N0,
229 int stride, int 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];
240 for (i = 0; i < stride; i++)
241 for (j = 0; j < N0; j++)
242 tmp[i*N0+j] = X[j*stride+i];
245 for (i = 0; i < N; i++)
249 static void celt_haar1(float *X, int N0, int stride)
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;
263 static inline int celt_compute_qn(int N, int b, int offset, int pulse_cap,
268 if (dualstereo && N == 2)
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;
279 /* Convert the quantized vector to an index */
280 static inline uint32_t celt_icwrsi(uint32_t N, uint32_t K, const int *y)
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;
291 // this code was adapted from libopus
292 static inline uint64_t celt_cwrsi(uint32_t N, uint32_t K, uint32_t i, int *y)
302 /*Lots of pulses case:*/
304 const uint32_t *row = ff_celt_pvq_u_row[N];
306 /* Are the pulses in this dimension negative? */
311 /*Count how many pulses were placed in this dimension.*/
317 p = ff_celt_pvq_u_row[--K][N];
320 for (p = row[K]; p > i; p = row[K])
324 val = (k0 - K + s) ^ s;
327 } else { /*Lots of dimensions case:*/
328 /*Are there any pulses in this dimension at all?*/
329 p = ff_celt_pvq_u_row[K ][N];
330 q = ff_celt_pvq_u_row[K + 1][N];
332 if (p <= i && i < q) {
336 /*Are the pulses in this dimension negative?*/
340 /*Count how many pulses were placed in this dimension.*/
342 do p = ff_celt_pvq_u_row[--K][N];
346 val = (k0 - K + s) ^ s;
364 val = (k0 - K + s) ^ s;
377 static inline void celt_encode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
379 ff_opus_rc_enc_uint(rc, celt_icwrsi(N, K, y), CELT_PVQ_V(N, K));
382 static inline float celt_decode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
384 const uint32_t idx = ff_opus_rc_dec_uint(rc, CELT_PVQ_V(N, K));
385 return celt_cwrsi(N, K, idx, y);
389 * Faster than libopus's search, operates entirely in the signed domain.
390 * Slightly worse/better depending on N, K and the input vector.
392 static void celt_pvq_search(float *X, int *y, int K, int N)
395 float res = 0.0f, y_norm = 0.0f, xy_norm = 0.0f;
397 for (i = 0; i < N; i++)
400 res = K/(res + FLT_EPSILON);
402 for (i = 0; i < N; i++) {
403 y[i] = lrintf(res*X[i]);
405 xy_norm += y[i]*X[i];
410 int max_idx = 0, phase = FFSIGN(K);
411 float max_den = 1.0f, max_num = 0.0f;
414 for (i = 0; i < N; i++) {
415 /* If the sum has been overshot and the best place has 0 pulses allocated
416 * to it, attempting to decrease it further will actually increase the
417 * sum. Prevent this by disregarding any 0 positions when decrementing. */
418 const int ca = 1 ^ ((y[i] == 0) & (phase < 0));
419 float xy_new = xy_norm + 1*phase*FFABS(X[i]);
420 float y_new = y_norm + 2*phase*FFABS(y[i]);
421 xy_new = xy_new * xy_new;
422 if (ca && (max_den*xy_new) > (y_new*max_num)) {
431 phase *= FFSIGN(X[max_idx]);
432 xy_norm += 1*phase*X[max_idx];
433 y_norm += 2*phase*y[max_idx];
438 static uint32_t celt_alg_quant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
439 enum CeltSpread spread, uint32_t blocks, float gain)
443 celt_exp_rotation(X, N, blocks, K, spread, 1);
444 celt_pvq_search(X, y, K, N);
445 celt_encode_pulses(rc, y, N, K);
446 return celt_extract_collapse_mask(y, N, blocks);
449 /** Decode pulse vector and combine the result with the pitch vector to produce
450 the final normalised signal in the current band. */
451 static uint32_t celt_alg_unquant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
452 enum CeltSpread spread, uint32_t blocks, float gain)
456 gain /= sqrtf(celt_decode_pulses(rc, y, N, K));
457 celt_normalize_residual(y, X, N, gain);
458 celt_exp_rotation(X, N, blocks, K, spread, 0);
459 return celt_extract_collapse_mask(y, N, blocks);
462 uint32_t ff_celt_decode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
463 float *X, float *Y, int N, int b, uint32_t blocks,
464 float *lowband, int duration, float *lowband_out, int level,
465 float gain, float *lowband_scratch, int fill)
467 const uint8_t *cache;
468 int dualstereo, split;
469 int imid = 0, iside = 0;
477 float mid = 0, side = 0;
478 int longblocks = (B0 == 1);
481 N_B0 = N_B = N / blocks;
482 split = dualstereo = (Y != NULL);
485 /* special case for one sample */
488 for (i = 0; i <= dualstereo; i++) {
490 if (f->remaining2 >= 1<<3) {
491 sign = ff_opus_rc_get_raw(rc, 1);
492 f->remaining2 -= 1 << 3;
495 x[0] = sign ? -1.0f : 1.0f;
499 lowband_out[0] = X[0];
503 if (!dualstereo && level == 0) {
504 int tf_change = f->tf_change[band];
507 recombine = tf_change;
508 /* Band recombining to increase frequency resolution */
511 (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
513 for (j = 0; j < N; j++)
514 lowband_scratch[j] = lowband[j];
515 lowband = lowband_scratch;
518 for (k = 0; k < recombine; k++) {
520 celt_haar1(lowband, N >> k, 1 << k);
521 fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
523 blocks >>= recombine;
526 /* Increasing the time resolution */
527 while ((N_B & 1) == 0 && tf_change < 0) {
529 celt_haar1(lowband, N_B, blocks);
530 fill |= fill << blocks;
539 /* Reorganize the samples in time order instead of frequency order */
540 if (B0 > 1 && lowband)
541 celt_deinterleave_hadamard(f->scratch, lowband, N_B >> recombine,
542 B0 << recombine, longblocks);
545 /* If we need 1.5 more bit than we can produce, split the band in two. */
546 cache = ff_celt_cache_bits +
547 ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
548 if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
554 fill = (fill & 1) | (fill << 1);
555 blocks = (blocks + 1) >> 1;
561 int mbits, sbits, delta;
568 /* Decide on the resolution to give to the split parameter theta */
569 pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
570 offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
572 qn = (dualstereo && band >= f->intensity_stereo) ? 1 :
573 celt_compute_qn(N, b, offset, pulse_cap, dualstereo);
574 tell = opus_rc_tell_frac(rc);
576 /* Entropy coding of the angle. We use a uniform pdf for the
577 time split, a step for stereo, and a triangular one for the rest. */
578 if (dualstereo && N > 2)
579 itheta = ff_opus_rc_dec_uint_step(rc, qn/2);
580 else if (dualstereo || B0 > 1)
581 itheta = ff_opus_rc_dec_uint(rc, qn+1);
583 itheta = ff_opus_rc_dec_uint_tri(rc, qn);
584 itheta = itheta * 16384 / qn;
585 /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.
586 Let's do that at higher complexity */
587 } else if (dualstereo) {
588 inv = (b > 2 << 3 && f->remaining2 > 2 << 3) ? ff_opus_rc_dec_log(rc, 2) : 0;
591 qalloc = opus_rc_tell_frac(rc) - tell;
598 fill = av_mod_uintp2(fill, blocks);
600 } else if (itheta == 16384) {
603 fill &= ((1 << blocks) - 1) << blocks;
606 imid = celt_cos(itheta);
607 iside = celt_cos(16384-itheta);
608 /* This is the mid vs side allocation that minimizes squared error
610 delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
613 mid = imid / 32768.0f;
614 side = iside / 32768.0f;
616 /* This is a special case for N=2 that only works for stereo and takes
617 advantage of the fact that mid and side are orthogonal to encode
618 the side with just one bit. */
619 if (N == 2 && dualstereo) {
625 /* Only need one bit for the side */
626 sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
629 f->remaining2 -= qalloc+sbits;
634 sign = ff_opus_rc_get_raw(rc, 1);
636 /* We use orig_fill here because we want to fold the side, but if
637 itheta==16384, we'll have cleared the low bits of fill. */
638 cm = ff_celt_decode_band(f, rc, band, x2, NULL, N, mbits, blocks,
639 lowband, duration, lowband_out, level, gain,
640 lowband_scratch, orig_fill);
641 /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
642 and there's no need to worry about mixing with the other channel. */
643 y2[0] = -sign * x2[1];
644 y2[1] = sign * x2[0];
656 /* "Normal" split code */
657 float *next_lowband2 = NULL;
658 float *next_lowband_out1 = NULL;
662 /* Give more bits to low-energy MDCTs than they would
663 * otherwise deserve */
664 if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {
666 /* Rough approximation for pre-echo masking */
667 delta -= delta >> (4 - duration);
669 /* Corresponds to a forward-masking slope of
670 * 1.5 dB per 10 ms */
671 delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
673 mbits = av_clip((b - delta) / 2, 0, b);
675 f->remaining2 -= qalloc;
677 if (lowband && !dualstereo)
678 next_lowband2 = lowband + N; /* >32-bit split case */
680 /* Only stereo needs to pass on lowband_out.
681 * Otherwise, it's handled at the end */
683 next_lowband_out1 = lowband_out;
685 next_level = level + 1;
687 rebalance = f->remaining2;
688 if (mbits >= sbits) {
689 /* In stereo mode, we do not apply a scaling to the mid
690 * because we need the normalized mid for folding later */
691 cm = ff_celt_decode_band(f, rc, band, X, NULL, N, mbits, blocks,
692 lowband, duration, next_lowband_out1,
693 next_level, dualstereo ? 1.0f : (gain * mid),
694 lowband_scratch, fill);
696 rebalance = mbits - (rebalance - f->remaining2);
697 if (rebalance > 3 << 3 && itheta != 0)
698 sbits += rebalance - (3 << 3);
700 /* For a stereo split, the high bits of fill are always zero,
701 * so no folding will be done to the side. */
702 cm |= ff_celt_decode_band(f, rc, band, Y, NULL, N, sbits, blocks,
703 next_lowband2, duration, NULL,
704 next_level, gain * side, NULL,
705 fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
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));
714 rebalance = sbits - (rebalance - f->remaining2);
715 if (rebalance > 3 << 3 && itheta != 16384)
716 mbits += rebalance - (3 << 3);
718 /* In stereo mode, we do not apply a scaling to the mid because
719 * we need the normalized mid for folding later */
720 cm |= ff_celt_decode_band(f, rc, band, X, NULL, N, mbits, blocks,
721 lowband, duration, next_lowband_out1,
722 next_level, dualstereo ? 1.0f : (gain * mid),
723 lowband_scratch, fill);
727 /* This is the basic no-split case */
728 uint32_t q = celt_bits2pulses(cache, b);
729 uint32_t curr_bits = celt_pulses2bits(cache, q);
730 f->remaining2 -= curr_bits;
732 /* Ensures we can never bust the budget */
733 while (f->remaining2 < 0 && q > 0) {
734 f->remaining2 += curr_bits;
735 curr_bits = celt_pulses2bits(cache, --q);
736 f->remaining2 -= curr_bits;
740 /* Finally do the actual quantization */
741 cm = celt_alg_unquant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
742 f->spread, blocks, gain);
744 /* If there's no pulse, fill the band anyway */
746 uint32_t cm_mask = (1 << blocks) - 1;
749 for (j = 0; j < N; j++)
754 for (j = 0; j < N; j++)
755 X[j] = (((int32_t)celt_rng(f)) >> 20);
758 /* Folded spectrum */
759 for (j = 0; j < N; j++) {
760 /* About 48 dB below the "normal" folding level */
761 X[j] = lowband[j] + (((celt_rng(f)) & 0x8000) ? 1.0f / 256 : -1.0f / 256);
765 celt_renormalize_vector(X, N, gain);
770 /* This code is used by the decoder and by the resynthesis-enabled encoder */
774 celt_stereo_merge(X, Y, mid, N);
776 for (j = 0; j < N; j++)
779 } else if (level == 0) {
782 /* Undo the sample reorganization going from time order to frequency order */
784 celt_interleave_hadamard(f->scratch, X, N_B>>recombine,
785 B0<<recombine, longblocks);
787 /* Undo time-freq changes that we did earlier */
790 for (k = 0; k < time_divide; k++) {
794 celt_haar1(X, N_B, blocks);
797 for (k = 0; k < recombine; k++) {
798 cm = ff_celt_bit_deinterleave[cm];
799 celt_haar1(X, N0>>k, 1<<k);
801 blocks <<= recombine;
803 /* Scale output for later folding */
807 for (j = 0; j < N0; j++)
808 lowband_out[j] = n * X[j];
810 cm = av_mod_uintp2(cm, blocks);
816 /* This has to be, AND MUST BE done by the psychoacoustic system, this has a very
817 * big impact on the entire quantization and especially huge on transients */
818 static int celt_calc_theta(const float *X, const float *Y, int coupling, int N)
821 float e[2] = { 0.0f, 0.0f };
822 for (j = 0; j < N; j++) {
823 if (coupling) { /* Coupling case */
824 e[0] += (X[j] + Y[j])*(X[j] + Y[j]);
825 e[1] += (X[j] - Y[j])*(X[j] - Y[j]);
831 return lrintf(32768.0f*atan2f(sqrtf(e[1]), sqrtf(e[0]))/M_PI);
834 static void celt_stereo_is_decouple(float *X, float *Y, float e_l, float e_r, int N)
837 const float energy_n = 1.0f/(sqrtf(e_l*e_l + e_r*e_r) + FLT_EPSILON);
840 for (i = 0; i < N; i++)
841 X[i] = e_l*X[i] + e_r*Y[i];
844 static void celt_stereo_ms_decouple(float *X, float *Y, int N)
847 const float decouple_norm = 1.0f/sqrtf(2.0f);
848 for (i = 0; i < N; i++) {
849 const float Xret = X[i];
850 X[i] = (X[i] + Y[i])*decouple_norm;
851 Y[i] = (Y[i] - Xret)*decouple_norm;
855 uint32_t ff_celt_encode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
856 float *X, float *Y, int N, int b, uint32_t blocks,
857 float *lowband, int duration, float *lowband_out, int level,
858 float gain, float *lowband_scratch, int fill)
860 const uint8_t *cache;
861 int dualstereo, split;
862 int imid = 0, iside = 0;
864 int N_B = N / blocks;
870 float mid = 0, side = 0;
871 int longblocks = (B0 == 1);
874 split = dualstereo = (Y != NULL);
877 /* special case for one sample - the decoder's output will be +- 1.0f!!! */
880 for (i = 0; i <= dualstereo; i++) {
881 if (f->remaining2 >= 1<<3) {
882 ff_opus_rc_put_raw(rc, x[0] < 0, 1);
883 f->remaining2 -= 1 << 3;
889 lowband_out[0] = X[0];
893 if (!dualstereo && level == 0) {
894 int tf_change = f->tf_change[band];
897 recombine = tf_change;
898 /* Band recombining to increase frequency resolution */
901 (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
903 for (j = 0; j < N; j++)
904 lowband_scratch[j] = lowband[j];
905 lowband = lowband_scratch;
908 for (k = 0; k < recombine; k++) {
909 celt_haar1(X, N >> k, 1 << k);
910 fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
912 blocks >>= recombine;
915 /* Increasing the time resolution */
916 while ((N_B & 1) == 0 && tf_change < 0) {
917 celt_haar1(X, N_B, blocks);
918 fill |= fill << blocks;
927 /* Reorganize the samples in time order instead of frequency order */
929 celt_deinterleave_hadamard(f->scratch, X, N_B >> recombine,
930 B0 << recombine, longblocks);
933 /* If we need 1.5 more bit than we can produce, split the band in two. */
934 cache = ff_celt_cache_bits +
935 ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
936 if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
942 fill = (fill & 1) | (fill << 1);
943 blocks = (blocks + 1) >> 1;
948 int itheta = celt_calc_theta(X, Y, dualstereo, N);
949 int mbits, sbits, delta;
956 /* Decide on the resolution to give to the split parameter theta */
957 pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
958 offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
960 qn = (dualstereo && band >= f->intensity_stereo) ? 1 :
961 celt_compute_qn(N, b, offset, pulse_cap, dualstereo);
962 tell = opus_rc_tell_frac(rc);
966 itheta = (itheta*qn + 8192) >> 14;
968 /* Entropy coding of the angle. We use a uniform pdf for the
969 * time split, a step for stereo, and a triangular one for the rest. */
970 if (dualstereo && N > 2)
971 ff_opus_rc_enc_uint_step(rc, itheta, qn / 2);
972 else if (dualstereo || B0 > 1)
973 ff_opus_rc_enc_uint(rc, itheta, qn + 1);
975 ff_opus_rc_enc_uint_tri(rc, itheta, qn);
976 itheta = itheta * 16384 / qn;
980 celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);
982 celt_stereo_ms_decouple(X, Y, N);
984 } else if (dualstereo) {
992 celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);
994 if (b > 2 << 3 && f->remaining2 > 2 << 3) {
995 ff_opus_rc_enc_log(rc, inv, 2);
1002 qalloc = opus_rc_tell_frac(rc) - tell;
1009 fill = av_mod_uintp2(fill, blocks);
1011 } else if (itheta == 16384) {
1014 fill &= ((1 << blocks) - 1) << blocks;
1017 imid = celt_cos(itheta);
1018 iside = celt_cos(16384-itheta);
1019 /* This is the mid vs side allocation that minimizes squared error
1021 delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
1024 mid = imid / 32768.0f;
1025 side = iside / 32768.0f;
1027 /* This is a special case for N=2 that only works for stereo and takes
1028 advantage of the fact that mid and side are orthogonal to encode
1029 the side with just one bit. */
1030 if (N == 2 && dualstereo) {
1036 /* Only need one bit for the side */
1037 sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
1039 c = (itheta > 8192);
1040 f->remaining2 -= qalloc+sbits;
1045 sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
1046 ff_opus_rc_put_raw(rc, sign, 1);
1048 sign = 1 - 2 * sign;
1049 /* We use orig_fill here because we want to fold the side, but if
1050 itheta==16384, we'll have cleared the low bits of fill. */
1051 cm = ff_celt_encode_band(f, rc, band, x2, NULL, N, mbits, blocks,
1052 lowband, duration, lowband_out, level, gain,
1053 lowband_scratch, orig_fill);
1054 /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
1055 and there's no need to worry about mixing with the other channel. */
1056 y2[0] = -sign * x2[1];
1057 y2[1] = sign * x2[0];
1069 /* "Normal" split code */
1070 float *next_lowband2 = NULL;
1071 float *next_lowband_out1 = NULL;
1075 /* Give more bits to low-energy MDCTs than they would
1076 * otherwise deserve */
1077 if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {
1079 /* Rough approximation for pre-echo masking */
1080 delta -= delta >> (4 - duration);
1082 /* Corresponds to a forward-masking slope of
1083 * 1.5 dB per 10 ms */
1084 delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
1086 mbits = av_clip((b - delta) / 2, 0, b);
1088 f->remaining2 -= qalloc;
1090 if (lowband && !dualstereo)
1091 next_lowband2 = lowband + N; /* >32-bit split case */
1093 /* Only stereo needs to pass on lowband_out.
1094 * Otherwise, it's handled at the end */
1096 next_lowband_out1 = lowband_out;
1098 next_level = level + 1;
1100 rebalance = f->remaining2;
1101 if (mbits >= sbits) {
1102 /* In stereo mode, we do not apply a scaling to the mid
1103 * because we need the normalized mid for folding later */
1104 cm = ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1105 lowband, duration, next_lowband_out1,
1106 next_level, dualstereo ? 1.0f : (gain * mid),
1107 lowband_scratch, fill);
1109 rebalance = mbits - (rebalance - f->remaining2);
1110 if (rebalance > 3 << 3 && itheta != 0)
1111 sbits += rebalance - (3 << 3);
1113 /* For a stereo split, the high bits of fill are always zero,
1114 * so no folding will be done to the side. */
1115 cm |= ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1116 next_lowband2, duration, NULL,
1117 next_level, gain * side, NULL,
1118 fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
1120 /* For a stereo split, the high bits of fill are always zero,
1121 * so no folding will be done to the side. */
1122 cm = ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1123 next_lowband2, duration, NULL,
1124 next_level, gain * side, NULL,
1125 fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
1127 rebalance = sbits - (rebalance - f->remaining2);
1128 if (rebalance > 3 << 3 && itheta != 16384)
1129 mbits += rebalance - (3 << 3);
1131 /* In stereo mode, we do not apply a scaling to the mid because
1132 * we need the normalized mid for folding later */
1133 cm |= ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1134 lowband, duration, next_lowband_out1,
1135 next_level, dualstereo ? 1.0f : (gain * mid),
1136 lowband_scratch, fill);
1140 /* This is the basic no-split case */
1141 uint32_t q = celt_bits2pulses(cache, b);
1142 uint32_t curr_bits = celt_pulses2bits(cache, q);
1143 f->remaining2 -= curr_bits;
1145 /* Ensures we can never bust the budget */
1146 while (f->remaining2 < 0 && q > 0) {
1147 f->remaining2 += curr_bits;
1148 curr_bits = celt_pulses2bits(cache, --q);
1149 f->remaining2 -= curr_bits;
1153 /* Finally do the actual quantization */
1154 cm = celt_alg_quant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
1155 f->spread, blocks, gain);