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>
9 * This file is part of FFmpeg.
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.
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.
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
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))
32 static inline int16_t celt_cos(int16_t x)
34 x = (MUL16(x, x) + 4096) >> 13;
35 x = (32767-x) + ROUND_MUL16(x, (-7651 + ROUND_MUL16(x, (8277 + ROUND_MUL16(-626, x)))));
39 static inline int celt_log2tan(int isin, int icos)
46 return (ls << 11) - (lc << 11) +
47 ROUND_MUL16(isin, ROUND_MUL16(isin, -2597) + 7932) -
48 ROUND_MUL16(icos, ROUND_MUL16(icos, -2597) + 7932);
51 static inline int celt_bits2pulses(const uint8_t *cache, int bits)
53 // TODO: Find the size of cache and make it into an array in the parameters list
59 for (i = 0; i < 6; i++) {
60 int center = (low + high + 1) >> 1;
61 if (cache[center] >= bits)
67 return (bits - (low == 0 ? -1 : cache[low]) <= cache[high] - bits) ? low : high;
70 static inline int celt_pulses2bits(const uint8_t *cache, int pulses)
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;
76 static inline void celt_normalize_residual(const int * av_restrict iy, float * av_restrict X,
80 for (i = 0; i < N; i++)
84 static void celt_exp_rotation_impl(float *X, uint32_t len, uint32_t stride,
91 for (i = 0; i < len - stride; i++) {
93 float x2 = Xptr[stride];
94 Xptr[stride] = c * x2 + s * x1;
95 *Xptr++ = c * x1 - s * x2;
98 Xptr = &X[len - 2 * stride - 1];
99 for (i = len - 2 * stride - 1; i >= 0; i--) {
101 float x2 = Xptr[stride];
102 Xptr[stride] = c * x2 + s * x1;
103 *Xptr-- = c * x1 - s * x2;
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)
111 uint32_t stride2 = 0;
116 if (2*K >= len || spread == CELT_SPREAD_NONE)
119 gain = (float)len / (len + (20 - 5*spread) * K);
120 theta = M_PI * gain * gain / 4;
125 if (len >= stride << 3) {
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)
134 for (i = 0; i < stride; i++) {
136 celt_exp_rotation_impl(X + i * len, len, 1, c, -s);
138 celt_exp_rotation_impl(X + i * len, len, stride2, s, -c);
141 celt_exp_rotation_impl(X + i * len, len, stride2, s, c);
142 celt_exp_rotation_impl(X + i * len, len, 1, c, s);
147 static inline uint32_t celt_extract_collapse_mask(const int *iy, uint32_t N, uint32_t B)
149 int i, j, N0 = N / B;
150 uint32_t collapse_mask = 0;
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;
161 static inline void celt_stereo_merge(float *X, float *Y, float mid, int N)
164 float xp = 0, side = 0;
169 /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
170 for (i = 0; i < N; i++) {
175 /* Compensating for the mid normalization */
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++)
186 gain[0] = 1.0f / sqrtf(E[0]);
187 gain[1] = 1.0f / sqrtf(E[1]);
189 for (i = 0; i < N; i++) {
191 /* Apply mid scaling (side is already scaled) */
192 value[0] = mid * X[i];
194 X[i] = gain[0] * (value[0] - value[1]);
195 Y[i] = gain[1] * (value[0] + value[1]);
199 static void celt_interleave_hadamard(float *tmp, float *X, int N0,
200 int stride, int hadamard)
202 int i, j, N = N0*stride;
203 const uint8_t *order = &ff_celt_hadamard_order[hadamard ? stride - 2 : 30];
205 for (i = 0; i < stride; i++)
206 for (j = 0; j < N0; j++)
207 tmp[j*stride+i] = X[order[i]*N0+j];
209 memcpy(X, tmp, N*sizeof(float));
212 static void celt_deinterleave_hadamard(float *tmp, float *X, int N0,
213 int stride, int hadamard)
215 int i, j, N = N0*stride;
216 const uint8_t *order = &ff_celt_hadamard_order[hadamard ? stride - 2 : 30];
218 for (i = 0; i < stride; i++)
219 for (j = 0; j < N0; j++)
220 tmp[order[i]*N0+j] = X[j*stride+i];
222 memcpy(X, tmp, N*sizeof(float));
225 static void celt_haar1(float *X, int N0, int stride)
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;
239 static inline int celt_compute_qn(int N, int b, int offset, int pulse_cap,
244 if (stereo && N == 2)
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;
255 /* Convert the quantized vector to an index */
256 static inline uint32_t celt_icwrsi(uint32_t N, uint32_t K, const int *y)
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;
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)
276 /*Lots of pulses case:*/
278 const uint32_t *row = ff_celt_pvq_u_row[N];
280 /* Are the pulses in this dimension negative? */
285 /*Count how many pulses were placed in this dimension.*/
291 p = ff_celt_pvq_u_row[--K][N];
294 for (p = row[K]; p > i; p = row[K])
298 val = (k0 - K + s) ^ s;
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];
306 if (p <= i && i < q) {
310 /*Are the pulses in this dimension negative?*/
314 /*Count how many pulses were placed in this dimension.*/
316 do p = ff_celt_pvq_u_row[--K][N];
320 val = (k0 - K + s) ^ s;
338 val = (k0 - K + s) ^ s;
351 static inline void celt_encode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
353 ff_opus_rc_enc_uint(rc, celt_icwrsi(N, K, y), CELT_PVQ_V(N, K));
356 static inline float celt_decode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
358 const uint32_t idx = ff_opus_rc_dec_uint(rc, CELT_PVQ_V(N, K));
359 return celt_cwrsi(N, K, idx, y);
363 * Faster than libopus's search, operates entirely in the signed domain.
364 * Slightly worse/better depending on N, K and the input vector.
366 static int celt_pvq_search(float *X, int *y, int K, int N)
369 float res = 0.0f, xy_norm = 0.0f;
371 for (i = 0; i < N; i++)
374 res = K/(res + FLT_EPSILON);
376 for (i = 0; i < N; i++) {
377 y[i] = lrintf(res*X[i]);
379 xy_norm += y[i]*X[i];
384 int max_idx = 0, max_den = 1, phase = FFSIGN(K);
385 float max_num = 0.0f;
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)) {
405 phase *= FFSIGN(X[max_idx]);
406 xy_norm += 1*phase*X[max_idx];
407 y_norm += 2*phase*y[max_idx];
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)
419 celt_exp_rotation(X, N, blocks, K, spread, 1);
420 gain /= sqrtf(celt_pvq_search(X, y, K, N));
421 celt_encode_pulses(rc, y, N, K);
422 celt_normalize_residual(y, X, N, gain);
423 celt_exp_rotation(X, N, blocks, K, spread, 0);
424 return celt_extract_collapse_mask(y, N, blocks);
427 /** Decode pulse vector and combine the result with the pitch vector to produce
428 the final normalised signal in the current band. */
429 static uint32_t celt_alg_unquant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
430 enum CeltSpread spread, uint32_t blocks, float gain)
434 gain /= sqrtf(celt_decode_pulses(rc, y, N, K));
435 celt_normalize_residual(y, X, N, gain);
436 celt_exp_rotation(X, N, blocks, K, spread, 0);
437 return celt_extract_collapse_mask(y, N, blocks);
440 uint32_t ff_celt_decode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
441 float *X, float *Y, int N, int b, uint32_t blocks,
442 float *lowband, int duration, float *lowband_out, int level,
443 float gain, float *lowband_scratch, int fill)
446 const uint8_t *cache;
447 int stereo = !!Y, split = !!Y;
448 int imid = 0, iside = 0;
450 int N_B = N / blocks;
456 float mid = 0, side = 0;
457 int longblocks = (B0 == 1);
461 /* special case for one sample */
463 for (i = 0; i <= stereo; i++) {
465 if (f->remaining2 >= 1<<3) {
466 sign = ff_opus_rc_get_raw(rc, 1);
467 f->remaining2 -= 1 << 3;
470 x[0] = sign ? -1.0f : 1.0f;
474 lowband_out[0] = X[0];
478 if (!stereo && level == 0) {
479 int tf_change = f->tf_change[band];
482 recombine = tf_change;
483 /* Band recombining to increase frequency resolution */
486 (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
487 for (i = 0; i < N; i++)
488 lowband_scratch[i] = lowband[i];
489 lowband = lowband_scratch;
492 for (k = 0; k < recombine; k++) {
494 celt_haar1(lowband, N >> k, 1 << k);
495 fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
497 blocks >>= recombine;
500 /* Increasing the time resolution */
501 while ((N_B & 1) == 0 && tf_change < 0) {
503 celt_haar1(lowband, N_B, blocks);
504 fill |= fill << blocks;
513 /* Reorganize the samples in time order instead of frequency order */
514 if (B0 > 1 && lowband)
515 celt_deinterleave_hadamard(f->scratch, lowband, N_B >> recombine,
516 B0 << recombine, longblocks);
519 /* If we need 1.5 more bit than we can produce, split the band in two. */
520 cache = ff_celt_cache_bits +
521 ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
522 if (!stereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
528 fill = (fill & 1) | (fill << 1);
529 blocks = (blocks + 1) >> 1;
535 int mbits, sbits, delta;
542 /* Decide on the resolution to give to the split parameter theta */
543 pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
544 offset = (pulse_cap >> 1) - (stereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
546 qn = (stereo && band >= f->intensity_stereo) ? 1 :
547 celt_compute_qn(N, b, offset, pulse_cap, stereo);
548 tell = opus_rc_tell_frac(rc);
550 /* Entropy coding of the angle. We use a uniform pdf for the
551 time split, a step for stereo, and a triangular one for the rest. */
553 itheta = ff_opus_rc_dec_uint_step(rc, qn/2);
554 else if (stereo || B0 > 1)
555 itheta = ff_opus_rc_dec_uint(rc, qn+1);
557 itheta = ff_opus_rc_dec_uint_tri(rc, qn);
558 itheta = itheta * 16384 / qn;
559 /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.
560 Let's do that at higher complexity */
562 inv = (b > 2 << 3 && f->remaining2 > 2 << 3) ? ff_opus_rc_dec_log(rc, 2) : 0;
565 qalloc = opus_rc_tell_frac(rc) - tell;
572 fill = av_mod_uintp2(fill, blocks);
574 } else if (itheta == 16384) {
577 fill &= ((1 << blocks) - 1) << blocks;
580 imid = celt_cos(itheta);
581 iside = celt_cos(16384-itheta);
582 /* This is the mid vs side allocation that minimizes squared error
584 delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
587 mid = imid / 32768.0f;
588 side = iside / 32768.0f;
590 /* This is a special case for N=2 that only works for stereo and takes
591 advantage of the fact that mid and side are orthogonal to encode
592 the side with just one bit. */
593 if (N == 2 && stereo) {
599 /* Only need one bit for the side */
600 sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
603 f->remaining2 -= qalloc+sbits;
608 sign = ff_opus_rc_get_raw(rc, 1);
610 /* We use orig_fill here because we want to fold the side, but if
611 itheta==16384, we'll have cleared the low bits of fill. */
612 cm = ff_celt_decode_band(f, rc, band, x2, NULL, N, mbits, blocks,
613 lowband, duration, lowband_out, level, gain,
614 lowband_scratch, orig_fill);
615 /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
616 and there's no need to worry about mixing with the other channel. */
617 y2[0] = -sign * x2[1];
618 y2[1] = sign * x2[0];
630 /* "Normal" split code */
631 float *next_lowband2 = NULL;
632 float *next_lowband_out1 = NULL;
636 /* Give more bits to low-energy MDCTs than they would
637 * otherwise deserve */
638 if (B0 > 1 && !stereo && (itheta & 0x3fff)) {
640 /* Rough approximation for pre-echo masking */
641 delta -= delta >> (4 - duration);
643 /* Corresponds to a forward-masking slope of
644 * 1.5 dB per 10 ms */
645 delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
647 mbits = av_clip((b - delta) / 2, 0, b);
649 f->remaining2 -= qalloc;
651 if (lowband && !stereo)
652 next_lowband2 = lowband + N; /* >32-bit split case */
654 /* Only stereo needs to pass on lowband_out.
655 * Otherwise, it's handled at the end */
657 next_lowband_out1 = lowband_out;
659 next_level = level + 1;
661 rebalance = f->remaining2;
662 if (mbits >= sbits) {
663 /* In stereo mode, we do not apply a scaling to the mid
664 * because we need the normalized mid for folding later */
665 cm = ff_celt_decode_band(f, rc, band, X, NULL, N, mbits, blocks,
666 lowband, duration, next_lowband_out1,
667 next_level, stereo ? 1.0f : (gain * mid),
668 lowband_scratch, fill);
670 rebalance = mbits - (rebalance - f->remaining2);
671 if (rebalance > 3 << 3 && itheta != 0)
672 sbits += rebalance - (3 << 3);
674 /* For a stereo split, the high bits of fill are always zero,
675 * so no folding will be done to the side. */
676 cm |= ff_celt_decode_band(f, rc, band, Y, NULL, N, sbits, blocks,
677 next_lowband2, duration, NULL,
678 next_level, gain * side, NULL,
679 fill >> blocks) << ((B0 >> 1) & (stereo - 1));
681 /* For a stereo split, the high bits of fill are always zero,
682 * so no folding will be done to the side. */
683 cm = ff_celt_decode_band(f, rc, band, Y, NULL, N, sbits, blocks,
684 next_lowband2, duration, NULL,
685 next_level, gain * side, NULL,
686 fill >> blocks) << ((B0 >> 1) & (stereo - 1));
688 rebalance = sbits - (rebalance - f->remaining2);
689 if (rebalance > 3 << 3 && itheta != 16384)
690 mbits += rebalance - (3 << 3);
692 /* In stereo mode, we do not apply a scaling to the mid because
693 * we need the normalized mid for folding later */
694 cm |= ff_celt_decode_band(f, rc, band, X, NULL, N, mbits, blocks,
695 lowband, duration, next_lowband_out1,
696 next_level, stereo ? 1.0f : (gain * mid),
697 lowband_scratch, fill);
701 /* This is the basic no-split case */
702 uint32_t q = celt_bits2pulses(cache, b);
703 uint32_t curr_bits = celt_pulses2bits(cache, q);
704 f->remaining2 -= curr_bits;
706 /* Ensures we can never bust the budget */
707 while (f->remaining2 < 0 && q > 0) {
708 f->remaining2 += curr_bits;
709 curr_bits = celt_pulses2bits(cache, --q);
710 f->remaining2 -= curr_bits;
714 /* Finally do the actual quantization */
715 cm = celt_alg_unquant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
716 f->spread, blocks, gain);
718 /* If there's no pulse, fill the band anyway */
719 uint32_t cm_mask = (1 << blocks) - 1;
724 for (i = 0; i < N; i++)
725 X[i] = (((int32_t)celt_rng(f)) >> 20);
728 /* Folded spectrum */
729 for (i = 0; i < N; i++) {
730 /* About 48 dB below the "normal" folding level */
731 X[i] = lowband[i] + (((celt_rng(f)) & 0x8000) ? 1.0f / 256 : -1.0f / 256);
735 celt_renormalize_vector(X, N, gain);
737 memset(X, 0, N*sizeof(float));
742 /* This code is used by the decoder and by the resynthesis-enabled encoder */
745 celt_stereo_merge(X, Y, mid, N);
747 for (i = 0; i < N; i++)
750 } else if (level == 0) {
753 /* Undo the sample reorganization going from time order to frequency order */
755 celt_interleave_hadamard(f->scratch, X, N_B >> recombine,
756 B0 << recombine, longblocks);
758 /* Undo time-freq changes that we did earlier */
761 for (k = 0; k < time_divide; k++) {
765 celt_haar1(X, N_B, blocks);
768 for (k = 0; k < recombine; k++) {
769 cm = ff_celt_bit_deinterleave[cm];
770 celt_haar1(X, N0>>k, 1<<k);
772 blocks <<= recombine;
774 /* Scale output for later folding */
777 for (i = 0; i < N0; i++)
778 lowband_out[i] = n * X[i];
780 cm = av_mod_uintp2(cm, blocks);
786 /* This has to be, AND MUST BE done by the psychoacoustic system, this has a very
787 * big impact on the entire quantization and especially huge on transients */
788 static int celt_calc_theta(const float *X, const float *Y, int coupling, int N)
791 float e[2] = { 0.0f, 0.0f };
792 if (coupling) { /* Coupling case */
793 for (i = 0; i < N; i++) {
794 e[0] += (X[i] + Y[i])*(X[i] + Y[i]);
795 e[1] += (X[i] - Y[i])*(X[i] - Y[i]);
798 for (i = 0; i < N; i++) {
803 return lrintf(32768.0f*atan2f(sqrtf(e[1]), sqrtf(e[0]))/M_PI);
806 static void celt_stereo_is_decouple(float *X, float *Y, float e_l, float e_r, int N)
809 const float energy_n = 1.0f/(sqrtf(e_l*e_l + e_r*e_r) + FLT_EPSILON);
812 for (i = 0; i < N; i++)
813 X[i] = e_l*X[i] + e_r*Y[i];
816 static void celt_stereo_ms_decouple(float *X, float *Y, int N)
819 for (i = 0; i < N; i++) {
820 const float Xret = X[i];
821 X[i] = (X[i] + Y[i])*M_SQRT1_2;
822 Y[i] = (Y[i] - Xret)*M_SQRT1_2;
826 uint32_t ff_celt_encode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
827 float *X, float *Y, int N, int b, uint32_t blocks,
828 float *lowband, int duration, float *lowband_out, int level,
829 float gain, float *lowband_scratch, int fill)
832 const uint8_t *cache;
833 int stereo = !!Y, split = !!Y;
834 int imid = 0, iside = 0;
836 int N_B = N / blocks;
842 float mid = 0, side = 0;
843 int longblocks = (B0 == 1);
847 /* special case for one sample - the decoder's output will be +- 1.0f!!! */
849 for (i = 0; i <= stereo; i++) {
850 if (f->remaining2 >= 1<<3) {
851 ff_opus_rc_put_raw(rc, x[0] < 0, 1);
852 f->remaining2 -= 1 << 3;
855 x[0] = 1.0f - 2.0f*(x[0] < 0);
859 lowband_out[0] = X[0];
863 if (!stereo && level == 0) {
864 int tf_change = f->tf_change[band];
867 recombine = tf_change;
868 /* Band recombining to increase frequency resolution */
871 (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
872 for (i = 0; i < N; i++)
873 lowband_scratch[i] = lowband[i];
874 lowband = lowband_scratch;
877 for (k = 0; k < recombine; k++) {
878 celt_haar1(X, N >> k, 1 << k);
879 fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
881 blocks >>= recombine;
884 /* Increasing the time resolution */
885 while ((N_B & 1) == 0 && tf_change < 0) {
886 celt_haar1(X, N_B, blocks);
887 fill |= fill << blocks;
896 /* Reorganize the samples in time order instead of frequency order */
898 celt_deinterleave_hadamard(f->scratch, X, N_B >> recombine,
899 B0 << recombine, longblocks);
902 /* If we need 1.5 more bit than we can produce, split the band in two. */
903 cache = ff_celt_cache_bits +
904 ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
905 if (!stereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
911 fill = (fill & 1) | (fill << 1);
912 blocks = (blocks + 1) >> 1;
917 int itheta = celt_calc_theta(X, Y, stereo, N);
918 int mbits, sbits, delta;
925 /* Decide on the resolution to give to the split parameter theta */
926 pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
927 offset = (pulse_cap >> 1) - (stereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
929 qn = (stereo && band >= f->intensity_stereo) ? 1 :
930 celt_compute_qn(N, b, offset, pulse_cap, stereo);
931 tell = opus_rc_tell_frac(rc);
935 itheta = (itheta*qn + 8192) >> 14;
937 /* Entropy coding of the angle. We use a uniform pdf for the
938 * time split, a step for stereo, and a triangular one for the rest. */
940 ff_opus_rc_enc_uint_step(rc, itheta, qn / 2);
941 else if (stereo || B0 > 1)
942 ff_opus_rc_enc_uint(rc, itheta, qn + 1);
944 ff_opus_rc_enc_uint_tri(rc, itheta, qn);
945 itheta = itheta * 16384 / qn;
949 celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band],
950 f->block[1].lin_energy[band], N);
952 celt_stereo_ms_decouple(X, Y, N);
957 for (i = 0; i < N; i++)
960 celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band],
961 f->block[1].lin_energy[band], N);
963 if (b > 2 << 3 && f->remaining2 > 2 << 3) {
964 ff_opus_rc_enc_log(rc, inv, 2);
971 qalloc = opus_rc_tell_frac(rc) - tell;
978 fill = av_mod_uintp2(fill, blocks);
980 } else if (itheta == 16384) {
983 fill &= ((1 << blocks) - 1) << blocks;
986 imid = celt_cos(itheta);
987 iside = celt_cos(16384-itheta);
988 /* This is the mid vs side allocation that minimizes squared error
990 delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
993 mid = imid / 32768.0f;
994 side = iside / 32768.0f;
996 /* This is a special case for N=2 that only works for stereo and takes
997 advantage of the fact that mid and side are orthogonal to encode
998 the side with just one bit. */
999 if (N == 2 && stereo) {
1005 /* Only need one bit for the side */
1006 sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
1008 c = (itheta > 8192);
1009 f->remaining2 -= qalloc+sbits;
1014 sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
1015 ff_opus_rc_put_raw(rc, sign, 1);
1017 sign = 1 - 2 * sign;
1018 /* We use orig_fill here because we want to fold the side, but if
1019 itheta==16384, we'll have cleared the low bits of fill. */
1020 cm = ff_celt_encode_band(f, rc, band, x2, NULL, N, mbits, blocks,
1021 lowband, duration, lowband_out, level, gain,
1022 lowband_scratch, orig_fill);
1023 /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
1024 and there's no need to worry about mixing with the other channel. */
1025 y2[0] = -sign * x2[1];
1026 y2[1] = sign * x2[0];
1038 /* "Normal" split code */
1039 float *next_lowband2 = NULL;
1040 float *next_lowband_out1 = NULL;
1044 /* Give more bits to low-energy MDCTs than they would
1045 * otherwise deserve */
1046 if (B0 > 1 && !stereo && (itheta & 0x3fff)) {
1048 /* Rough approximation for pre-echo masking */
1049 delta -= delta >> (4 - duration);
1051 /* Corresponds to a forward-masking slope of
1052 * 1.5 dB per 10 ms */
1053 delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
1055 mbits = av_clip((b - delta) / 2, 0, b);
1057 f->remaining2 -= qalloc;
1059 if (lowband && !stereo)
1060 next_lowband2 = lowband + N; /* >32-bit split case */
1062 /* Only stereo needs to pass on lowband_out.
1063 * Otherwise, it's handled at the end */
1065 next_lowband_out1 = lowband_out;
1067 next_level = level + 1;
1069 rebalance = f->remaining2;
1070 if (mbits >= sbits) {
1071 /* In stereo mode, we do not apply a scaling to the mid
1072 * because we need the normalized mid for folding later */
1073 cm = ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1074 lowband, duration, next_lowband_out1,
1075 next_level, stereo ? 1.0f : (gain * mid),
1076 lowband_scratch, fill);
1078 rebalance = mbits - (rebalance - f->remaining2);
1079 if (rebalance > 3 << 3 && itheta != 0)
1080 sbits += rebalance - (3 << 3);
1082 /* For a stereo split, the high bits of fill are always zero,
1083 * so no folding will be done to the side. */
1084 cm |= ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1085 next_lowband2, duration, NULL,
1086 next_level, gain * side, NULL,
1087 fill >> blocks) << ((B0 >> 1) & (stereo - 1));
1089 /* For a stereo split, the high bits of fill are always zero,
1090 * so no folding will be done to the side. */
1091 cm = ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1092 next_lowband2, duration, NULL,
1093 next_level, gain * side, NULL,
1094 fill >> blocks) << ((B0 >> 1) & (stereo - 1));
1096 rebalance = sbits - (rebalance - f->remaining2);
1097 if (rebalance > 3 << 3 && itheta != 16384)
1098 mbits += rebalance - (3 << 3);
1100 /* In stereo mode, we do not apply a scaling to the mid because
1101 * we need the normalized mid for folding later */
1102 cm |= ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1103 lowband, duration, next_lowband_out1,
1104 next_level, stereo ? 1.0f : (gain * mid),
1105 lowband_scratch, fill);
1109 /* This is the basic no-split case */
1110 uint32_t q = celt_bits2pulses(cache, b);
1111 uint32_t curr_bits = celt_pulses2bits(cache, q);
1112 f->remaining2 -= curr_bits;
1114 /* Ensures we can never bust the budget */
1115 while (f->remaining2 < 0 && q > 0) {
1116 f->remaining2 += curr_bits;
1117 curr_bits = celt_pulses2bits(cache, --q);
1118 f->remaining2 -= curr_bits;
1122 /* Finally do the actual quantization */
1123 cm = celt_alg_quant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
1124 f->spread, blocks, gain);
1126 /* If there's no pulse, fill the band anyway */
1127 uint32_t cm_mask = (1 << blocks) - 1;
1132 for (i = 0; i < N; i++)
1133 X[i] = (((int32_t)celt_rng(f)) >> 20);
1136 /* Folded spectrum */
1137 for (i = 0; i < N; i++) {
1138 /* About 48 dB below the "normal" folding level */
1139 X[i] = lowband[i] + (((celt_rng(f)) & 0x8000) ? 1.0f / 256 : -1.0f / 256);
1143 celt_renormalize_vector(X, N, gain);
1145 memset(X, 0, N*sizeof(float));
1150 /* This code is used by the decoder and by the resynthesis-enabled encoder */
1153 celt_stereo_merge(X, Y, mid, N);
1155 for (i = 0; i < N; i++)
1158 } else if (level == 0) {
1161 /* Undo the sample reorganization going from time order to frequency order */
1163 celt_interleave_hadamard(f->scratch, X, N_B >> recombine,
1164 B0 << recombine, longblocks);
1166 /* Undo time-freq changes that we did earlier */
1169 for (k = 0; k < time_divide; k++) {
1173 celt_haar1(X, N_B, blocks);
1176 for (k = 0; k < recombine; k++) {
1177 cm = ff_celt_bit_deinterleave[cm];
1178 celt_haar1(X, N0>>k, 1<<k);
1180 blocks <<= recombine;
1182 /* Scale output for later folding */
1184 float n = sqrtf(N0);
1185 for (i = 0; i < N0; i++)
1186 lowband_out[i] = n * X[i];
1188 cm = av_mod_uintp2(cm, blocks);
1194 float ff_celt_quant_band_cost(CeltFrame *f, OpusRangeCoder *rc, int band, float *bits,
1198 uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
1199 const int band_size = ff_celt_freq_range[band] << f->size;
1200 float buf[352], lowband_scratch[176], norm1[176], norm2[176];
1201 float dist, cost, err_x = 0.0f, err_y = 0.0f;
1203 float *X_orig = f->block[0].coeffs + (ff_celt_freq_bands[band] << f->size);
1204 float *Y = (f->channels == 2) ? &buf[176] : NULL;
1205 float *Y_orig = f->block[1].coeffs + (ff_celt_freq_bands[band] << f->size);
1206 OPUS_RC_CHECKPOINT_SPAWN(rc);
1208 memcpy(X, X_orig, band_size*sizeof(float));
1210 memcpy(Y, Y_orig, band_size*sizeof(float));
1212 f->remaining2 = ((f->framebits << 3) - f->anticollapse_needed) - opus_rc_tell_frac(rc) - 1;
1213 if (band <= f->coded_bands - 1) {
1214 int curr_balance = f->remaining / FFMIN(3, f->coded_bands - band);
1215 b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[band] + curr_balance), 14);
1218 if (f->dual_stereo) {
1219 ff_celt_encode_band(f, rc, band, X, NULL, band_size, b / 2, f->blocks, NULL,
1220 f->size, norm1, 0, 1.0f, lowband_scratch, cm[0]);
1222 ff_celt_encode_band(f, rc, band, Y, NULL, band_size, b / 2, f->blocks, NULL,
1223 f->size, norm2, 0, 1.0f, lowband_scratch, cm[1]);
1225 ff_celt_encode_band(f, rc, band, X, Y, band_size, b, f->blocks, NULL, f->size,
1226 norm1, 0, 1.0f, lowband_scratch, cm[0] | cm[1]);
1229 for (i = 0; i < band_size; i++) {
1230 err_x += (X[i] - X_orig[i])*(X[i] - X_orig[i]);
1231 err_y += (Y[i] - Y_orig[i])*(Y[i] - Y_orig[i]);
1234 dist = sqrtf(err_x) + sqrtf(err_y);
1235 cost = OPUS_RC_CHECKPOINT_BITS(rc)/8.0f;
1238 OPUS_RC_CHECKPOINT_ROLLBACK(rc);
1240 return lambda*dist*cost;