2 * Copyright (c) 2012 Andrew D'Addesio
3 * Copyright (c) 2013-2014 Mozilla Corporation
4 * Copyright (c) 2016 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_rotation1(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)
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_rotation1(X + i * len, len, stride2, s, c);
138 celt_exp_rotation1(X + i * len, len, 1, c, s);
142 static inline uint32_t celt_extract_collapse_mask(const int *iy, uint32_t N, uint32_t B)
144 uint32_t collapse_mask;
151 /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
155 for (i = 0; i < B; i++)
156 for (j = 0; j < N0; j++)
157 collapse_mask |= (iy[i*N0+j]!=0)<<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++)
187 gain[0] = 1.0f / sqrtf(t);
189 gain[1] = 1.0f / sqrtf(t);
191 for (i = 0; i < N; i++) {
193 /* Apply mid scaling (side is already scaled) */
194 value[0] = mid * X[i];
196 X[i] = gain[0] * (value[0] - value[1]);
197 Y[i] = gain[1] * (value[0] + value[1]);
201 static void celt_interleave_hadamard(float *tmp, float *X, int N0,
202 int stride, int hadamard)
208 const uint8_t *ordery = ff_celt_hadamard_ordery + stride - 2;
209 for (i = 0; i < stride; i++)
210 for (j = 0; j < N0; j++)
211 tmp[j*stride+i] = X[ordery[i]*N0+j];
213 for (i = 0; i < stride; i++)
214 for (j = 0; j < N0; j++)
215 tmp[j*stride+i] = X[i*N0+j];
218 for (i = 0; i < N; i++)
222 static void celt_deinterleave_hadamard(float *tmp, float *X, int N0,
223 int stride, int hadamard)
229 const uint8_t *ordery = ff_celt_hadamard_ordery + stride - 2;
230 for (i = 0; i < stride; i++)
231 for (j = 0; j < N0; j++)
232 tmp[ordery[i]*N0+j] = X[j*stride+i];
234 for (i = 0; i < stride; i++)
235 for (j = 0; j < N0; j++)
236 tmp[i*N0+j] = X[j*stride+i];
239 for (i = 0; i < N; i++)
243 static void celt_haar1(float *X, int N0, int stride)
247 for (i = 0; i < stride; i++) {
248 for (j = 0; j < N0; j++) {
249 float x0 = X[stride * (2 * j + 0) + i];
250 float x1 = X[stride * (2 * j + 1) + i];
251 X[stride * (2 * j + 0) + i] = (x0 + x1) * M_SQRT1_2;
252 X[stride * (2 * j + 1) + i] = (x0 - x1) * M_SQRT1_2;
257 static inline int celt_compute_qn(int N, int b, int offset, int pulse_cap,
262 if (dualstereo && N == 2)
265 /* The upper limit ensures that in a stereo split with itheta==16384, we'll
266 * always have enough bits left over to code at least one pulse in the
267 * side; otherwise it would collapse, since it doesn't get folded. */
268 qb = FFMIN3(b - pulse_cap - (4 << 3), (b + N2 * offset) / N2, 8 << 3);
269 qn = (qb < (1 << 3 >> 1)) ? 1 : ((ff_celt_qn_exp2[qb & 0x7] >> (14 - (qb >> 3))) + 1) >> 1 << 1;
273 // this code was adapted from libopus
274 static inline uint64_t celt_cwrsi(uint32_t N, uint32_t K, uint32_t i, int *y)
284 /*Lots of pulses case:*/
286 const uint32_t *row = ff_celt_pvq_u_row[N];
288 /* Are the pulses in this dimension negative? */
293 /*Count how many pulses were placed in this dimension.*/
299 p = ff_celt_pvq_u_row[--K][N];
302 for (p = row[K]; p > i; p = row[K])
306 val = (k0 - K + s) ^ s;
309 } else { /*Lots of dimensions case:*/
310 /*Are there any pulses in this dimension at all?*/
311 p = ff_celt_pvq_u_row[K ][N];
312 q = ff_celt_pvq_u_row[K + 1][N];
314 if (p <= i && i < q) {
318 /*Are the pulses in this dimension negative?*/
322 /*Count how many pulses were placed in this dimension.*/
324 do p = ff_celt_pvq_u_row[--K][N];
328 val = (k0 - K + s) ^ s;
346 val = (k0 - K + s) ^ s;
359 static inline float celt_decode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
361 const uint32_t idx = ff_opus_rc_dec_uint(rc, CELT_PVQ_V(N, K));
362 return celt_cwrsi(N, K, idx, y);
365 /** Decode pulse vector and combine the result with the pitch vector to produce
366 the final normalised signal in the current band. */
367 static uint32_t celt_alg_unquant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
368 enum CeltSpread spread, uint32_t blocks, float gain)
372 gain /= sqrtf(celt_decode_pulses(rc, y, N, K));
373 celt_normalize_residual(y, X, N, gain);
374 celt_exp_rotation(X, N, blocks, K, spread);
375 return celt_extract_collapse_mask(y, N, blocks);
378 uint32_t ff_celt_decode_band(CeltContext *s, OpusRangeCoder *rc, const int band,
379 float *X, float *Y, int N, int b, uint32_t blocks,
380 float *lowband, int duration, float *lowband_out, int level,
381 float gain, float *lowband_scratch, int fill)
383 const uint8_t *cache;
384 int dualstereo, split;
385 int imid = 0, iside = 0;
393 float mid = 0, side = 0;
394 int longblocks = (B0 == 1);
397 N_B0 = N_B = N / blocks;
398 split = dualstereo = (Y != NULL);
401 /* special case for one sample */
404 for (i = 0; i <= dualstereo; i++) {
406 if (s->remaining2 >= 1<<3) {
407 sign = ff_opus_rc_get_raw(rc, 1);
408 s->remaining2 -= 1 << 3;
411 x[0] = sign ? -1.0f : 1.0f;
415 lowband_out[0] = X[0];
419 if (!dualstereo && level == 0) {
420 int tf_change = s->tf_change[band];
423 recombine = tf_change;
424 /* Band recombining to increase frequency resolution */
427 (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
429 for (j = 0; j < N; j++)
430 lowband_scratch[j] = lowband[j];
431 lowband = lowband_scratch;
434 for (k = 0; k < recombine; k++) {
436 celt_haar1(lowband, N >> k, 1 << k);
437 fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
439 blocks >>= recombine;
442 /* Increasing the time resolution */
443 while ((N_B & 1) == 0 && tf_change < 0) {
445 celt_haar1(lowband, N_B, blocks);
446 fill |= fill << blocks;
455 /* Reorganize the samples in time order instead of frequency order */
456 if (B0 > 1 && lowband)
457 celt_deinterleave_hadamard(s->scratch, lowband, N_B >> recombine,
458 B0 << recombine, longblocks);
461 /* If we need 1.5 more bit than we can produce, split the band in two. */
462 cache = ff_celt_cache_bits +
463 ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
464 if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
470 fill = (fill & 1) | (fill << 1);
471 blocks = (blocks + 1) >> 1;
477 int mbits, sbits, delta;
484 /* Decide on the resolution to give to the split parameter theta */
485 pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
486 offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
488 qn = (dualstereo && band >= s->intensitystereo) ? 1 :
489 celt_compute_qn(N, b, offset, pulse_cap, dualstereo);
490 tell = opus_rc_tell_frac(rc);
492 /* Entropy coding of the angle. We use a uniform pdf for the
493 time split, a step for stereo, and a triangular one for the rest. */
494 if (dualstereo && N > 2)
495 itheta = ff_opus_rc_dec_uint_step(rc, qn/2);
496 else if (dualstereo || B0 > 1)
497 itheta = ff_opus_rc_dec_uint(rc, qn+1);
499 itheta = ff_opus_rc_dec_uint_tri(rc, qn);
500 itheta = itheta * 16384 / qn;
501 /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.
502 Let's do that at higher complexity */
503 } else if (dualstereo) {
504 inv = (b > 2 << 3 && s->remaining2 > 2 << 3) ? ff_opus_rc_dec_log(rc, 2) : 0;
507 qalloc = opus_rc_tell_frac(rc) - tell;
514 fill = av_mod_uintp2(fill, blocks);
516 } else if (itheta == 16384) {
519 fill &= ((1 << blocks) - 1) << blocks;
522 imid = celt_cos(itheta);
523 iside = celt_cos(16384-itheta);
524 /* This is the mid vs side allocation that minimizes squared error
526 delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
529 mid = imid / 32768.0f;
530 side = iside / 32768.0f;
532 /* This is a special case for N=2 that only works for stereo and takes
533 advantage of the fact that mid and side are orthogonal to encode
534 the side with just one bit. */
535 if (N == 2 && dualstereo) {
541 /* Only need one bit for the side */
542 sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
545 s->remaining2 -= qalloc+sbits;
550 sign = ff_opus_rc_get_raw(rc, 1);
552 /* We use orig_fill here because we want to fold the side, but if
553 itheta==16384, we'll have cleared the low bits of fill. */
554 cm = ff_celt_decode_band(s, rc, band, x2, NULL, N, mbits, blocks,
555 lowband, duration, lowband_out, level, gain,
556 lowband_scratch, orig_fill);
557 /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
558 and there's no need to worry about mixing with the other channel. */
559 y2[0] = -sign * x2[1];
560 y2[1] = sign * x2[0];
572 /* "Normal" split code */
573 float *next_lowband2 = NULL;
574 float *next_lowband_out1 = NULL;
578 /* Give more bits to low-energy MDCTs than they would
579 * otherwise deserve */
580 if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {
582 /* Rough approximation for pre-echo masking */
583 delta -= delta >> (4 - duration);
585 /* Corresponds to a forward-masking slope of
586 * 1.5 dB per 10 ms */
587 delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
589 mbits = av_clip((b - delta) / 2, 0, b);
591 s->remaining2 -= qalloc;
593 if (lowband && !dualstereo)
594 next_lowband2 = lowband + N; /* >32-bit split case */
596 /* Only stereo needs to pass on lowband_out.
597 * Otherwise, it's handled at the end */
599 next_lowband_out1 = lowband_out;
601 next_level = level + 1;
603 rebalance = s->remaining2;
604 if (mbits >= sbits) {
605 /* In stereo mode, we do not apply a scaling to the mid
606 * because we need the normalized mid for folding later */
607 cm = ff_celt_decode_band(s, rc, band, X, NULL, N, mbits, blocks,
608 lowband, duration, next_lowband_out1,
609 next_level, dualstereo ? 1.0f : (gain * mid),
610 lowband_scratch, fill);
612 rebalance = mbits - (rebalance - s->remaining2);
613 if (rebalance > 3 << 3 && itheta != 0)
614 sbits += rebalance - (3 << 3);
616 /* For a stereo split, the high bits of fill are always zero,
617 * so no folding will be done to the side. */
618 cm |= ff_celt_decode_band(s, rc, band, Y, NULL, N, sbits, blocks,
619 next_lowband2, duration, NULL,
620 next_level, gain * side, NULL,
621 fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
623 /* For a stereo split, the high bits of fill are always zero,
624 * so no folding will be done to the side. */
625 cm = ff_celt_decode_band(s, rc, band, Y, NULL, N, sbits, blocks,
626 next_lowband2, duration, NULL,
627 next_level, gain * side, NULL,
628 fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
630 rebalance = sbits - (rebalance - s->remaining2);
631 if (rebalance > 3 << 3 && itheta != 16384)
632 mbits += rebalance - (3 << 3);
634 /* In stereo mode, we do not apply a scaling to the mid because
635 * we need the normalized mid for folding later */
636 cm |= ff_celt_decode_band(s, rc, band, X, NULL, N, mbits, blocks,
637 lowband, duration, next_lowband_out1,
638 next_level, dualstereo ? 1.0f : (gain * mid),
639 lowband_scratch, fill);
643 /* This is the basic no-split case */
644 uint32_t q = celt_bits2pulses(cache, b);
645 uint32_t curr_bits = celt_pulses2bits(cache, q);
646 s->remaining2 -= curr_bits;
648 /* Ensures we can never bust the budget */
649 while (s->remaining2 < 0 && q > 0) {
650 s->remaining2 += curr_bits;
651 curr_bits = celt_pulses2bits(cache, --q);
652 s->remaining2 -= curr_bits;
656 /* Finally do the actual quantization */
657 cm = celt_alg_unquant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
658 s->spread, blocks, gain);
660 /* If there's no pulse, fill the band anyway */
662 uint32_t cm_mask = (1 << blocks) - 1;
665 for (j = 0; j < N; j++)
670 for (j = 0; j < N; j++)
671 X[j] = (((int32_t)celt_rng(s)) >> 20);
674 /* Folded spectrum */
675 for (j = 0; j < N; j++) {
676 /* About 48 dB below the "normal" folding level */
677 X[j] = lowband[j] + (((celt_rng(s)) & 0x8000) ? 1.0f / 256 : -1.0f / 256);
681 celt_renormalize_vector(X, N, gain);
686 /* This code is used by the decoder and by the resynthesis-enabled encoder */
690 celt_stereo_merge(X, Y, mid, N);
692 for (j = 0; j < N; j++)
695 } else if (level == 0) {
698 /* Undo the sample reorganization going from time order to frequency order */
700 celt_interleave_hadamard(s->scratch, X, N_B>>recombine,
701 B0<<recombine, longblocks);
703 /* Undo time-freq changes that we did earlier */
706 for (k = 0; k < time_divide; k++) {
710 celt_haar1(X, N_B, blocks);
713 for (k = 0; k < recombine; k++) {
714 cm = ff_celt_bit_deinterleave[cm];
715 celt_haar1(X, N0>>k, 1<<k);
717 blocks <<= recombine;
719 /* Scale output for later folding */
723 for (j = 0; j < N0; j++)
724 lowband_out[j] = n * X[j];
726 cm = av_mod_uintp2(cm, blocks);