GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/opus_pvq.c Lines: 398 497 80.1 %
Date: 2021-01-21 21:11:50 Branches: 262 346 75.7 %

Line Branch Exec Source
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
1037770
static inline int16_t celt_cos(int16_t x)
33
{
34
1037770
    x = (MUL16(x, x) + 4096) >> 13;
35
1037770
    x = (32767-x) + ROUND_MUL16(x, (-7651 + ROUND_MUL16(x, (8277 + ROUND_MUL16(-626, x)))));
36
1037770
    return x + 1;
37
}
38
39
518885
static inline int celt_log2tan(int isin, int icos)
40
{
41
    int lc, ls;
42
518885
    lc = opus_ilog(icos);
43
518885
    ls = opus_ilog(isin);
44
518885
    icos <<= 15 - lc;
45
518885
    isin <<= 15 - ls;
46
518885
    return (ls << 11) - (lc << 11) +
47
1037770
           ROUND_MUL16(isin, ROUND_MUL16(isin, -2597) + 7932) -
48
518885
           ROUND_MUL16(icos, ROUND_MUL16(icos, -2597) + 7932);
49
}
50
51
1006497
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
1006497
    int i, low = 0, high;
55
56
1006497
    high = cache[0];
57
1006497
    bits--;
58
59
7045479
    for (i = 0; i < 6; i++) {
60
6038982
        int center = (low + high + 1) >> 1;
61
6038982
        if (cache[center] >= bits)
62
3419805
            high = center;
63
        else
64
2619177
            low = center;
65
    }
66
67

1006497
    return (bits - (low == 0 ? -1 : cache[low]) <= cache[high] - bits) ? low : high;
68
}
69
70
1018229
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
1018229
   return (pulses == 0) ? 0 : cache[pulses] + 1;
74
}
75
76
867942
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
8206304
    for (i = 0; i < N; i++)
81
7338362
        X[i] = g * iy[i];
82
867942
}
83
84
374943
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
374943
    Xptr = X;
91
5428487
    for (i = 0; i < len - stride; i++) {
92
5053544
        float x1     = Xptr[0];
93
5053544
        float x2     = Xptr[stride];
94
5053544
        Xptr[stride] = c * x2 + s * x1;
95
5053544
        *Xptr++      = c * x1 - s * x2;
96
    }
97
98
374943
    Xptr = &X[len - 2 * stride - 1];
99
4586497
    for (i = len - 2 * stride - 1; i >= 0; i--) {
100
4211554
        float x1     = Xptr[0];
101
4211554
        float x2     = Xptr[stride];
102
4211554
        Xptr[stride] = c * x2 + s * x1;
103
4211554
        *Xptr--      = c * x1 - s * x2;
104
    }
105
374943
}
106
107
867942
static inline void celt_exp_rotation(float *X, uint32_t len,
108
                                     uint32_t stride, uint32_t K,
109
                                     enum CeltSpread spread, const int encode)
110
{
111
867942
    uint32_t stride2 = 0;
112
    float c, s;
113
    float gain, theta;
114
    int i;
115
116

867942
    if (2*K >= len || spread == CELT_SPREAD_NONE)
117
704445
        return;
118
119
163497
    gain = (float)len / (len + (20 - 5*spread) * K);
120
163497
    theta = M_PI * gain * gain / 4;
121
122
163497
    c = cosf(theta);
123
163497
    s = sinf(theta);
124
125
163497
    if (len >= stride << 3) {
126
138987
        stride2 = 1;
127
        /* This is just a simple (equivalent) way of computing sqrt(len/stride) with rounding.
128
        It's basically incrementing long as (stride2+0.5)^2 < len/stride. */
129
590425
        while ((stride2 * stride2 + stride2) * stride + (stride >> 2) < len)
130
451438
            stride2++;
131
    }
132
133
163497
    len /= stride;
134
384644
    for (i = 0; i < stride; i++) {
135
221147
        if (encode) {
136
            celt_exp_rotation_impl(X + i * len, len, 1, c, -s);
137
            if (stride2)
138
                celt_exp_rotation_impl(X + i * len, len, stride2, s, -c);
139
        } else {
140
221147
            if (stride2)
141
153796
                celt_exp_rotation_impl(X + i * len, len, stride2, s, c);
142
221147
            celt_exp_rotation_impl(X + i * len, len, 1, c, s);
143
        }
144
    }
145
}
146
147
867942
static inline uint32_t celt_extract_collapse_mask(const int *iy, uint32_t N, uint32_t B)
148
{
149
867942
    int i, j, N0 = N / B;
150
867942
    uint32_t collapse_mask = 0;
151
152
867942
    if (B <= 1)
153
741536
        return 1;
154
155
533430
    for (i = 0; i < B; i++)
156
1520152
        for (j = 0; j < N0; j++)
157
1113128
            collapse_mask |= (!!iy[i*N0+j]) << i;
158
126406
    return collapse_mask;
159
}
160
161
186191
static inline void celt_stereo_merge(float *X, float *Y, float mid, int N)
162
{
163
    int i;
164
186191
    float xp = 0, side = 0;
165
    float E[2];
166
    float mid2;
167
    float gain[2];
168
169
    /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
170
4471947
    for (i = 0; i < N; i++) {
171
4285756
        xp   += X[i] * Y[i];
172
4285756
        side += Y[i] * Y[i];
173
    }
174
175
    /* Compensating for the mid normalization */
176
186191
    xp *= mid;
177
186191
    mid2 = mid;
178
186191
    E[0] = mid2 * mid2 + side - 2 * xp;
179
186191
    E[1] = mid2 * mid2 + side + 2 * xp;
180

186191
    if (E[0] < 6e-4f || E[1] < 6e-4f) {
181
1154
        for (i = 0; i < N; i++)
182
998
            Y[i] = X[i];
183
156
        return;
184
    }
185
186
186035
    gain[0] = 1.0f / sqrtf(E[0]);
187
186035
    gain[1] = 1.0f / sqrtf(E[1]);
188
189
4470793
    for (i = 0; i < N; i++) {
190
        float value[2];
191
        /* Apply mid scaling (side is already scaled) */
192
4284758
        value[0] = mid * X[i];
193
4284758
        value[1] = Y[i];
194
4284758
        X[i] = gain[0] * (value[0] - value[1]);
195
4284758
        Y[i] = gain[1] * (value[0] + value[1]);
196
    }
197
}
198
199
140127
static void celt_interleave_hadamard(float *tmp, float *X, int N0,
200
                                     int stride, int hadamard)
201
{
202
140127
    int i, j, N = N0*stride;
203
140127
    const uint8_t *order = &ff_celt_hadamard_order[hadamard ? stride - 2 : 30];
204
205
884745
    for (i = 0; i < stride; i++)
206
4394906
        for (j = 0; j < N0; j++)
207
3650288
            tmp[j*stride+i] = X[order[i]*N0+j];
208
209
140127
    memcpy(X, tmp, N*sizeof(float));
210
140127
}
211
212
90824
static void celt_deinterleave_hadamard(float *tmp, float *X, int N0,
213
                                       int stride, int hadamard)
214
{
215
90824
    int i, j, N = N0*stride;
216
90824
    const uint8_t *order = &ff_celt_hadamard_order[hadamard ? stride - 2 : 30];
217
218
556080
    for (i = 0; i < stride; i++)
219
2742746
        for (j = 0; j < N0; j++)
220
2277490
            tmp[order[i]*N0+j] = X[j*stride+i];
221
222
90824
    memcpy(X, tmp, N*sizeof(float));
223
90824
}
224
225
356919
static void celt_haar1(float *X, int N0, int stride)
226
{
227
    int i, j;
228
356919
    N0 >>= 1;
229
1032538
    for (i = 0; i < stride; i++) {
230
5805723
        for (j = 0; j < N0; j++) {
231
5130104
            float x0 = X[stride * (2 * j + 0) + i];
232
5130104
            float x1 = X[stride * (2 * j + 1) + i];
233
5130104
            X[stride * (2 * j + 0) + i] = (x0 + x1) * M_SQRT1_2;
234
5130104
            X[stride * (2 * j + 1) + i] = (x0 - x1) * M_SQRT1_2;
235
        }
236
    }
237
356919
}
238
239
575131
static inline int celt_compute_qn(int N, int b, int offset, int pulse_cap,
240
                                  int stereo)
241
{
242
    int qn, qb;
243
575131
    int N2 = 2 * N - 1;
244

575131
    if (stereo && N == 2)
245
48661
        N2--;
246
247
    /* The upper limit ensures that in a stereo split with itheta==16384, we'll
248
     * always have enough bits left over to code at least one pulse in the
249
     * side; otherwise it would collapse, since it doesn't get folded. */
250
575131
    qb = FFMIN3(b - pulse_cap - (4 << 3), (b + N2 * offset) / N2, 8 << 3);
251
575131
    qn = (qb < (1 << 3 >> 1)) ? 1 : ((ff_celt_qn_exp2[qb & 0x7] >> (14 - (qb >> 3))) + 1) >> 1 << 1;
252
575131
    return qn;
253
}
254
255
/* Convert the quantized vector to an index */
256
static inline uint32_t celt_icwrsi(uint32_t N, uint32_t K, const int *y)
257
{
258
    int i, idx = 0, sum = 0;
259
    for (i = N - 1; i >= 0; i--) {
260
        const uint32_t i_s = CELT_PVQ_U(N - i, sum + FFABS(y[i]) + 1);
261
        idx += CELT_PVQ_U(N - i, sum) + (y[i] < 0)*i_s;
262
        sum += FFABS(y[i]);
263
    }
264
    return idx;
265
}
266
267
// this code was adapted from libopus
268
867942
static inline uint64_t celt_cwrsi(uint32_t N, uint32_t K, uint32_t i, int *y)
269
{
270
867942
    uint64_t norm = 0;
271
    uint32_t q, p;
272
    int s, val;
273
    int k0;
274
275
6470420
    while (N > 2) {
276
        /*Lots of pulses case:*/
277
5602478
        if (K >= N) {
278
1666017
            const uint32_t *row = ff_celt_pvq_u_row[N];
279
280
            /* Are the pulses in this dimension negative? */
281
1666017
            p  = row[K + 1];
282
1666017
            s  = -(i >= p);
283
1666017
            i -= p & s;
284
285
            /*Count how many pulses were placed in this dimension.*/
286
1666017
            k0 = K;
287
1666017
            q = row[N];
288
1666017
            if (q > i) {
289
268919
                K = N;
290
                do {
291
387231
                    p = ff_celt_pvq_u_row[--K][N];
292
387231
                } while (p > i);
293
            } else
294
8742497
                for (p = row[K]; p > i; p = row[K])
295
7345399
                    K--;
296
297
1666017
            i    -= p;
298
1666017
            val   = (k0 - K + s) ^ s;
299
1666017
            norm += val * val;
300
1666017
            *y++  = val;
301
        } else { /*Lots of dimensions case:*/
302
            /*Are there any pulses in this dimension at all?*/
303
3936461
            p = ff_celt_pvq_u_row[K    ][N];
304
3936461
            q = ff_celt_pvq_u_row[K + 1][N];
305
306

3936461
            if (p <= i && i < q) {
307
2833646
                i -= p;
308
2833646
                *y++ = 0;
309
            } else {
310
                /*Are the pulses in this dimension negative?*/
311
1102815
                s  = -(i >= q);
312
1102815
                i -= q & s;
313
314
                /*Count how many pulses were placed in this dimension.*/
315
1102815
                k0 = K;
316
1284281
                do p = ff_celt_pvq_u_row[--K][N];
317
1284281
                while (p > i);
318
319
1102815
                i    -= p;
320
1102815
                val   = (k0 - K + s) ^ s;
321
1102815
                norm += val * val;
322
1102815
                *y++  = val;
323
            }
324
        }
325
5602478
        N--;
326
    }
327
328
    /* N == 2 */
329
867942
    p  = 2 * K + 1;
330
867942
    s  = -(i >= p);
331
867942
    i -= p & s;
332
867942
    k0 = K;
333
867942
    K  = (i + 1) / 2;
334
335
867942
    if (K)
336
611968
        i -= 2 * K - 1;
337
338
867942
    val   = (k0 - K + s) ^ s;
339
867942
    norm += val * val;
340
867942
    *y++  = val;
341
342
    /* N==1 */
343
867942
    s     = -i;
344
867942
    val   = (K + s) ^ s;
345
867942
    norm += val * val;
346
867942
    *y    = val;
347
348
867942
    return norm;
349
}
350
351
static inline void celt_encode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
352
{
353
    ff_opus_rc_enc_uint(rc, celt_icwrsi(N, K, y), CELT_PVQ_V(N, K));
354
}
355
356
867942
static inline float celt_decode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
357
{
358

867942
    const uint32_t idx = ff_opus_rc_dec_uint(rc, CELT_PVQ_V(N, K));
359
867942
    return celt_cwrsi(N, K, idx, y);
360
}
361
362
/*
363
 * Faster than libopus's search, operates entirely in the signed domain.
364
 * Slightly worse/better depending on N, K and the input vector.
365
 */
366
static float ppp_pvq_search_c(float *X, int *y, int K, int N)
367
{
368
    int i, y_norm = 0;
369
    float res = 0.0f, xy_norm = 0.0f;
370
371
    for (i = 0; i < N; i++)
372
        res += FFABS(X[i]);
373
374
    res = K/(res + FLT_EPSILON);
375
376
    for (i = 0; i < N; i++) {
377
        y[i] = lrintf(res*X[i]);
378
        y_norm  += y[i]*y[i];
379
        xy_norm += y[i]*X[i];
380
        K -= FFABS(y[i]);
381
    }
382
383
    while (K) {
384
        int max_idx = 0, phase = FFSIGN(K);
385
        float max_num = 0.0f;
386
        float max_den = 1.0f;
387
        y_norm += 1.0f;
388
389
        for (i = 0; i < N; i++) {
390
            /* If the sum has been overshot and the best place has 0 pulses allocated
391
             * to it, attempting to decrease it further will actually increase the
392
             * sum. Prevent this by disregarding any 0 positions when decrementing. */
393
            const int ca = 1 ^ ((y[i] == 0) & (phase < 0));
394
            const int y_new = y_norm  + 2*phase*FFABS(y[i]);
395
            float xy_new = xy_norm + 1*phase*FFABS(X[i]);
396
            xy_new = xy_new * xy_new;
397
            if (ca && (max_den*xy_new) > (y_new*max_num)) {
398
                max_den = y_new;
399
                max_num = xy_new;
400
                max_idx = i;
401
            }
402
        }
403
404
        K -= phase;
405
406
        phase *= FFSIGN(X[max_idx]);
407
        xy_norm += 1*phase*X[max_idx];
408
        y_norm  += 2*phase*y[max_idx];
409
        y[max_idx] += phase;
410
    }
411
412
    return (float)y_norm;
413
}
414
415
static uint32_t celt_alg_quant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
416
                               enum CeltSpread spread, uint32_t blocks, float gain,
417
                               CeltPVQ *pvq)
418
{
419
    int *y = pvq->qcoeff;
420
421
    celt_exp_rotation(X, N, blocks, K, spread, 1);
422
    gain /= sqrtf(pvq->pvq_search(X, y, K, N));
423
    celt_encode_pulses(rc, y,  N, K);
424
    celt_normalize_residual(y, X, N, gain);
425
    celt_exp_rotation(X, N, blocks, K, spread, 0);
426
    return celt_extract_collapse_mask(y, N, blocks);
427
}
428
429
/** Decode pulse vector and combine the result with the pitch vector to produce
430
    the final normalised signal in the current band. */
431
867942
static uint32_t celt_alg_unquant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
432
                                 enum CeltSpread spread, uint32_t blocks, float gain,
433
                                 CeltPVQ *pvq)
434
{
435
867942
    int *y = pvq->qcoeff;
436
437
867942
    gain /= sqrtf(celt_decode_pulses(rc, y, N, K));
438
867942
    celt_normalize_residual(y, X, N, gain);
439
867942
    celt_exp_rotation(X, N, blocks, K, spread, 0);
440
867942
    return celt_extract_collapse_mask(y, N, blocks);
441
}
442
443
static int celt_calc_theta(const float *X, const float *Y, int coupling, int N)
444
{
445
    int i;
446
    float e[2] = { 0.0f, 0.0f };
447
    if (coupling) { /* Coupling case */
448
        for (i = 0; i < N; i++) {
449
            e[0] += (X[i] + Y[i])*(X[i] + Y[i]);
450
            e[1] += (X[i] - Y[i])*(X[i] - Y[i]);
451
        }
452
    } else {
453
        for (i = 0; i < N; i++) {
454
            e[0] += X[i]*X[i];
455
            e[1] += Y[i]*Y[i];
456
        }
457
    }
458
    return lrintf(32768.0f*atan2f(sqrtf(e[1]), sqrtf(e[0]))/M_PI);
459
}
460
461
static void celt_stereo_is_decouple(float *X, float *Y, float e_l, float e_r, int N)
462
{
463
    int i;
464
    const float energy_n = 1.0f/(sqrtf(e_l*e_l + e_r*e_r) + FLT_EPSILON);
465
    e_l *= energy_n;
466
    e_r *= energy_n;
467
    for (i = 0; i < N; i++)
468
        X[i] = e_l*X[i] + e_r*Y[i];
469
}
470
471
static void celt_stereo_ms_decouple(float *X, float *Y, int N)
472
{
473
    int i;
474
    for (i = 0; i < N; i++) {
475
        const float Xret = X[i];
476
        X[i] = (X[i] + Y[i])*M_SQRT1_2;
477
        Y[i] = (Y[i] - Xret)*M_SQRT1_2;
478
    }
479
}
480
481
1742927
static av_always_inline uint32_t quant_band_template(CeltPVQ *pvq, CeltFrame *f,
482
                                                     OpusRangeCoder *rc,
483
                                                     const int band, float *X,
484
                                                     float *Y, int N, int b,
485
                                                     uint32_t blocks, float *lowband,
486
                                                     int duration, float *lowband_out,
487
                                                     int level, float gain,
488
                                                     float *lowband_scratch,
489
                                                     int fill, int quant)
490
{
491
    int i;
492
    const uint8_t *cache;
493
1742927
    int stereo = !!Y, split = stereo;
494
1742927
    int imid = 0, iside = 0;
495
1742927
    uint32_t N0 = N;
496
1742927
    int N_B = N / blocks;
497
1742927
    int N_B0 = N_B;
498
1742927
    int B0 = blocks;
499
1742927
    int time_divide = 0;
500
1742927
    int recombine = 0;
501
1742927
    int inv = 0;
502
1742927
    float mid = 0, side = 0;
503
1742927
    int longblocks = (B0 == 1);
504
1742927
    uint32_t cm = 0;
505
506
1742927
    if (N == 1) {
507
109648
        float *x = X;
508
285672
        for (i = 0; i <= stereo; i++) {
509
176024
            int sign = 0;
510
176024
            if (f->remaining2 >= 1 << 3) {
511
169213
                if (quant) {
512
                    sign = x[0] < 0;
513
                    ff_opus_rc_put_raw(rc, sign, 1);
514
                } else {
515
169213
                    sign = ff_opus_rc_get_raw(rc, 1);
516
                }
517
169213
                f->remaining2 -= 1 << 3;
518
            }
519
176024
            x[0] = 1.0f - 2.0f*sign;
520
176024
            x = Y;
521
        }
522
109648
        if (lowband_out)
523
109648
            lowband_out[0] = X[0];
524
109648
        return 1;
525
    }
526
527

1633279
    if (!stereo && level == 0) {
528
620101
        int tf_change = f->tf_change[band];
529
        int k;
530
620101
        if (tf_change > 0)
531
40217
            recombine = tf_change;
532
        /* Band recombining to increase frequency resolution */
533
534

620101
        if (lowband &&
535

345387
            (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
536
2782289
            for (i = 0; i < N; i++)
537
2674010
                lowband_scratch[i] = lowband[i];
538
108279
            lowband = lowband_scratch;
539
        }
540
541
687901
        for (k = 0; k < recombine; k++) {
542

67800
            if (quant || lowband)
543
42647
                celt_haar1(quant ? X : lowband, N >> k, 1 << k);
544
67800
            fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
545
        }
546
620101
        blocks >>= recombine;
547
620101
        N_B <<= recombine;
548
549
        /* Increasing the time resolution */
550

769739
        while ((N_B & 1) == 0 && tf_change < 0) {
551

149638
            if (quant || lowband)
552
96834
                celt_haar1(quant ? X : lowband, N_B, blocks);
553
149638
            fill |= fill << blocks;
554
149638
            blocks <<= 1;
555
149638
            N_B >>= 1;
556
149638
            time_divide++;
557
149638
            tf_change++;
558
        }
559
620101
        B0 = blocks;
560
620101
        N_B0 = N_B;
561
562
        /* Reorganize the samples in time order instead of frequency order */
563

620101
        if (B0 > 1 && (quant || lowband))
564
90824
            celt_deinterleave_hadamard(pvq->hadamard_tmp, quant ? X : lowband,
565
                                       N_B >> recombine, B0 << recombine,
566
                                       longblocks);
567
    }
568
569
    /* If we need 1.5 more bit than we can produce, split the band in two. */
570
1633279
    cache = ff_celt_cache_bits +
571
1633279
            ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
572


1633279
    if (!stereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
573
386396
        N >>= 1;
574
386396
        Y = X + N;
575
386396
        split = 1;
576
386396
        duration -= 1;
577
386396
        if (blocks == 1)
578
245705
            fill = (fill & 1) | (fill << 1);
579
386396
        blocks = (blocks + 1) >> 1;
580
    }
581
582
1633279
    if (split) {
583
        int qn;
584
626782
        int itheta = quant ? celt_calc_theta(X, Y, stereo, N) : 0;
585
        int mbits, sbits, delta;
586
        int qalloc;
587
        int pulse_cap;
588
        int offset;
589
        int orig_fill;
590
        int tell;
591
592
        /* Decide on the resolution to give to the split parameter theta */
593
626782
        pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
594

626782
        offset = (pulse_cap >> 1) - (stereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
595
                                                          CELT_QTHETA_OFFSET);
596

626782
        qn = (stereo && band >= f->intensity_stereo) ? 1 :
597
575131
             celt_compute_qn(N, b, offset, pulse_cap, stereo);
598
626782
        tell = opus_rc_tell_frac(rc);
599
626782
        if (qn != 1) {
600
573416
            if (quant)
601
                itheta = (itheta*qn + 8192) >> 14;
602
            /* Entropy coding of the angle. We use a uniform pdf for the
603
             * time split, a step for stereo, and a triangular one for the rest. */
604
573416
            if (quant) {
605
                if (stereo && N > 2)
606
                    ff_opus_rc_enc_uint_step(rc, itheta, qn / 2);
607
                else if (stereo || B0 > 1)
608
                    ff_opus_rc_enc_uint(rc, itheta, qn + 1);
609
                else
610
                    ff_opus_rc_enc_uint_tri(rc, itheta, qn);
611
                itheta = itheta * 16384 / qn;
612
                if (stereo) {
613
                    if (itheta == 0)
614
                        celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band],
615
                                                f->block[1].lin_energy[band], N);
616
                    else
617
                        celt_stereo_ms_decouple(X, Y, N);
618
                }
619
            } else {
620

573416
                if (stereo && N > 2)
621
138861
                    itheta = ff_opus_rc_dec_uint_step(rc, qn / 2);
622

434555
                else if (stereo || B0 > 1)
623
188850
                    itheta = ff_opus_rc_dec_uint(rc, qn+1);
624
                else
625
245705
                    itheta = ff_opus_rc_dec_uint_tri(rc, qn);
626
573416
                itheta = itheta * 16384 / qn;
627
            }
628
53366
        } else if (stereo) {
629
53366
            if (quant) {
630
                inv = f->apply_phase_inv ? itheta > 8192 : 0;
631
                 if (inv) {
632
                    for (i = 0; i < N; i++)
633
                       Y[i] *= -1;
634
                 }
635
                 celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band],
636
                                         f->block[1].lin_energy[band], N);
637
638
                if (b > 2 << 3 && f->remaining2 > 2 << 3) {
639
                    ff_opus_rc_enc_log(rc, inv, 2);
640
                } else {
641
                    inv = 0;
642
                }
643
            } else {
644

53366
                inv = (b > 2 << 3 && f->remaining2 > 2 << 3) ? ff_opus_rc_dec_log(rc, 2) : 0;
645
53366
                inv = f->apply_phase_inv ? inv : 0;
646
            }
647
53366
            itheta = 0;
648
        }
649
626782
        qalloc = opus_rc_tell_frac(rc) - tell;
650
626782
        b -= qalloc;
651
652
626782
        orig_fill = fill;
653
626782
        if (itheta == 0) {
654
105651
            imid = 32767;
655
105651
            iside = 0;
656
105651
            fill = av_mod_uintp2(fill, blocks);
657
105651
            delta = -16384;
658
521131
        } else if (itheta == 16384) {
659
2246
            imid = 0;
660
2246
            iside = 32767;
661
2246
            fill &= ((1 << blocks) - 1) << blocks;
662
2246
            delta = 16384;
663
        } else {
664
518885
            imid = celt_cos(itheta);
665
518885
            iside = celt_cos(16384-itheta);
666
            /* This is the mid vs side allocation that minimizes squared error
667
            in that band. */
668
518885
            delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
669
        }
670
671
626782
        mid  = imid  / 32768.0f;
672
626782
        side = iside / 32768.0f;
673
674
        /* This is a special case for N=2 that only works for stereo and takes
675
        advantage of the fact that mid and side are orthogonal to encode
676
        the side with just one bit. */
677

626782
        if (N == 2 && stereo) {
678
            int c;
679
54195
            int sign = 0;
680
            float tmp;
681
            float *x2, *y2;
682
54195
            mbits = b;
683
            /* Only need one bit for the side */
684

54195
            sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
685
54195
            mbits -= sbits;
686
54195
            c = (itheta > 8192);
687
54195
            f->remaining2 -= qalloc+sbits;
688
689
54195
            x2 = c ? Y : X;
690
54195
            y2 = c ? X : Y;
691
54195
            if (sbits) {
692
28840
                if (quant) {
693
                    sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
694
                    ff_opus_rc_put_raw(rc, sign, 1);
695
                } else {
696
28840
                    sign = ff_opus_rc_get_raw(rc, 1);
697
                }
698
            }
699
54195
            sign = 1 - 2 * sign;
700
            /* We use orig_fill here because we want to fold the side, but if
701
            itheta==16384, we'll have cleared the low bits of fill. */
702
54195
            cm = pvq->quant_band(pvq, f, rc, band, x2, NULL, N, mbits, blocks, lowband, duration,
703
                                 lowband_out, level, gain, lowband_scratch, orig_fill);
704
            /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
705
            and there's no need to worry about mixing with the other channel. */
706
54195
            y2[0] = -sign * x2[1];
707
54195
            y2[1] =  sign * x2[0];
708
54195
            X[0] *= mid;
709
54195
            X[1] *= mid;
710
54195
            Y[0] *= side;
711
54195
            Y[1] *= side;
712
54195
            tmp = X[0];
713
54195
            X[0] = tmp - Y[0];
714
54195
            Y[0] = tmp + Y[0];
715
54195
            tmp = X[1];
716
54195
            X[1] = tmp - Y[1];
717
54195
            Y[1] = tmp + Y[1];
718
        } else {
719
            /* "Normal" split code */
720
572587
            float *next_lowband2     = NULL;
721
572587
            float *next_lowband_out1 = NULL;
722
572587
            int next_level = 0;
723
            int rebalance;
724
            uint32_t cmt;
725
726
            /* Give more bits to low-energy MDCTs than they would
727
             * otherwise deserve */
728

572587
            if (B0 > 1 && !stereo && (itheta & 0x3fff)) {
729
139845
                if (itheta > 8192)
730
                    /* Rough approximation for pre-echo masking */
731
61043
                    delta -= delta >> (4 - duration);
732
                else
733
                    /* Corresponds to a forward-masking slope of
734
                     * 1.5 dB per 10 ms */
735
78802
                    delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
736
            }
737
572587
            mbits = av_clip((b - delta) / 2, 0, b);
738
572587
            sbits = b - mbits;
739
572587
            f->remaining2 -= qalloc;
740
741

572587
            if (lowband && !stereo)
742
292101
                next_lowband2 = lowband + N; /* >32-bit split case */
743
744
            /* Only stereo needs to pass on lowband_out.
745
             * Otherwise, it's handled at the end */
746
572587
            if (stereo)
747
186191
                next_lowband_out1 = lowband_out;
748
            else
749
386396
                next_level = level + 1;
750
751
572587
            rebalance = f->remaining2;
752
572587
            if (mbits >= sbits) {
753
                /* In stereo mode, we do not apply a scaling to the mid
754
                 * because we need the normalized mid for folding later */
755
351486
                cm = pvq->quant_band(pvq, f, rc, band, X, NULL, N, mbits, blocks,
756
                                     lowband, duration, next_lowband_out1, next_level,
757
                                     stereo ? 1.0f : (gain * mid), lowband_scratch, fill);
758
351486
                rebalance = mbits - (rebalance - f->remaining2);
759

351486
                if (rebalance > 3 << 3 && itheta != 0)
760
86536
                    sbits += rebalance - (3 << 3);
761
762
                /* For a stereo split, the high bits of fill are always zero,
763
                 * so no folding will be done to the side. */
764
351486
                cmt = pvq->quant_band(pvq, f, rc, band, Y, NULL, N, sbits, blocks,
765
                                      next_lowband2, duration, NULL, next_level,
766
                                      gain * side, NULL, fill >> blocks);
767
351486
                cm |= cmt << ((B0 >> 1) & (stereo - 1));
768
            } else {
769
                /* For a stereo split, the high bits of fill are always zero,
770
                 * so no folding will be done to the side. */
771
221101
                cm = pvq->quant_band(pvq, f, rc, band, Y, NULL, N, sbits, blocks,
772
                                     next_lowband2, duration, NULL, next_level,
773
                                     gain * side, NULL, fill >> blocks);
774
221101
                cm <<= ((B0 >> 1) & (stereo - 1));
775
221101
                rebalance = sbits - (rebalance - f->remaining2);
776

221101
                if (rebalance > 3 << 3 && itheta != 16384)
777
80951
                    mbits += rebalance - (3 << 3);
778
779
                /* In stereo mode, we do not apply a scaling to the mid because
780
                 * we need the normalized mid for folding later */
781
221101
                cm |= pvq->quant_band(pvq, f, rc, band, X, NULL, N, mbits, blocks,
782
                                      lowband, duration, next_lowband_out1, next_level,
783
                                      stereo ? 1.0f : (gain * mid), lowband_scratch, fill);
784
            }
785
        }
786
    } else {
787
        /* This is the basic no-split case */
788
1006497
        uint32_t q         = celt_bits2pulses(cache, b);
789
1006497
        uint32_t curr_bits = celt_pulses2bits(cache, q);
790
1006497
        f->remaining2 -= curr_bits;
791
792
        /* Ensures we can never bust the budget */
793

1018229
        while (f->remaining2 < 0 && q > 0) {
794
11732
            f->remaining2 += curr_bits;
795
11732
            curr_bits      = celt_pulses2bits(cache, --q);
796
11732
            f->remaining2 -= curr_bits;
797
        }
798
799
1006497
        if (q != 0) {
800
            /* Finally do the actual (de)quantization */
801
867942
            if (quant) {
802
                cm = celt_alg_quant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
803
                                    f->spread, blocks, gain, pvq);
804
            } else {
805
867942
                cm = celt_alg_unquant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
806
                                      f->spread, blocks, gain, pvq);
807
            }
808
        } else {
809
            /* If there's no pulse, fill the band anyway */
810
138555
            uint32_t cm_mask = (1 << blocks) - 1;
811
138555
            fill &= cm_mask;
812
138555
            if (fill) {
813
54172
                if (!lowband) {
814
                    /* Noise */
815
221642
                    for (i = 0; i < N; i++)
816
212448
                        X[i] = (((int32_t)celt_rng(f)) >> 20);
817
9194
                    cm = cm_mask;
818
                } else {
819
                    /* Folded spectrum */
820
1817164
                    for (i = 0; i < N; i++) {
821
                        /* About 48 dB below the "normal" folding level */
822
1772186
                        X[i] = lowband[i] + (((celt_rng(f)) & 0x8000) ? 1.0f / 256 : -1.0f / 256);
823
                    }
824
44978
                    cm = fill;
825
                }
826
54172
                celt_renormalize_vector(X, N, gain);
827
            } else {
828
84383
                memset(X, 0, N*sizeof(float));
829
            }
830
        }
831
    }
832
833
    /* This code is used by the decoder and by the resynthesis-enabled encoder */
834
1633279
    if (stereo) {
835
240386
        if (N > 2)
836
186191
            celt_stereo_merge(X, Y, mid, N);
837
240386
        if (inv) {
838
398220
            for (i = 0; i < N; i++)
839
391242
                Y[i] *= -1;
840
        }
841
1392893
    } else if (level == 0) {
842
        int k;
843
844
        /* Undo the sample reorganization going from time order to frequency order */
845
620101
        if (B0 > 1)
846
140127
            celt_interleave_hadamard(pvq->hadamard_tmp, X, N_B >> recombine,
847
                                     B0 << recombine, longblocks);
848
849
        /* Undo time-freq changes that we did earlier */
850
620101
        N_B = N_B0;
851
620101
        blocks = B0;
852
769739
        for (k = 0; k < time_divide; k++) {
853
149638
            blocks >>= 1;
854
149638
            N_B <<= 1;
855
149638
            cm |= cm >> blocks;
856
149638
            celt_haar1(X, N_B, blocks);
857
        }
858
859
687901
        for (k = 0; k < recombine; k++) {
860
67800
            cm = ff_celt_bit_deinterleave[cm];
861
67800
            celt_haar1(X, N0>>k, 1<<k);
862
        }
863
620101
        blocks <<= recombine;
864
865
        /* Scale output for later folding */
866
620101
        if (lowband_out) {
867
433910
            float n = sqrtf(N0);
868
8189280
            for (i = 0; i < N0; i++)
869
7755370
                lowband_out[i] = n * X[i];
870
        }
871
620101
        cm = av_mod_uintp2(cm, blocks);
872
    }
873
874
1633279
    return cm;
875
}
876
877
1742927
static QUANT_FN(pvq_decode_band)
878
{
879
#if CONFIG_OPUS_DECODER
880
1742927
    return quant_band_template(pvq, f, rc, band, X, Y, N, b, blocks, lowband, duration,
881
                               lowband_out, level, gain, lowband_scratch, fill, 0);
882
#else
883
    return 0;
884
#endif
885
}
886
887
static QUANT_FN(pvq_encode_band)
888
{
889
#if CONFIG_OPUS_ENCODER
890
    return quant_band_template(pvq, f, rc, band, X, Y, N, b, blocks, lowband, duration,
891
                               lowband_out, level, gain, lowband_scratch, fill, 1);
892
#else
893
    return 0;
894
#endif
895
}
896
897
41
int av_cold ff_celt_pvq_init(CeltPVQ **pvq, int encode)
898
{
899
41
    CeltPVQ *s = av_malloc(sizeof(CeltPVQ));
900
41
    if (!s)
901
        return AVERROR(ENOMEM);
902
903
41
    s->pvq_search = ppp_pvq_search_c;
904
41
    s->quant_band = encode ? pvq_encode_band : pvq_decode_band;
905
906
    if (CONFIG_OPUS_ENCODER && ARCH_X86)
907
41
        ff_celt_pvq_init_x86(s);
908
909
41
    *pvq = s;
910
911
41
    return 0;
912
}
913
914
41
void av_cold ff_celt_pvq_uninit(CeltPVQ **pvq)
915
{
916
41
    av_freep(pvq);
917
41
}