Coverage Report

Created: 2026-07-25 07:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opus/celt/celt_decoder.c
Line
Count
Source
1
/* Copyright (c) 2007-2008 CSIRO
2
   Copyright (c) 2007-2010 Xiph.Org Foundation
3
   Copyright (c) 2008 Gregory Maxwell
4
   Written by Jean-Marc Valin and Gregory Maxwell */
5
/*
6
   Redistribution and use in source and binary forms, with or without
7
   modification, are permitted provided that the following conditions
8
   are met:
9
10
   - Redistributions of source code must retain the above copyright
11
   notice, this list of conditions and the following disclaimer.
12
13
   - Redistributions in binary form must reproduce the above copyright
14
   notice, this list of conditions and the following disclaimer in the
15
   documentation and/or other materials provided with the distribution.
16
17
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21
   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
*/
29
30
#ifdef HAVE_CONFIG_H
31
#include "config.h"
32
#endif
33
34
#define CELT_DECODER_C
35
36
#include "cpu_support.h"
37
#include "os_support.h"
38
#include "mdct.h"
39
#include <math.h>
40
#include "celt.h"
41
#include "pitch.h"
42
#include "bands.h"
43
#include "modes.h"
44
#include "entcode.h"
45
#include "quant_bands.h"
46
#include "rate.h"
47
#include "stack_alloc.h"
48
#include "mathops.h"
49
#include "float_cast.h"
50
#include <stdarg.h>
51
#include "celt_lpc.h"
52
#include "vq.h"
53
54
#ifdef ENABLE_DEEP_PLC
55
#include "lpcnet.h"
56
#include "lpcnet_private.h"
57
#endif
58
59
/* The maximum pitch lag to allow in the pitch-based PLC. It's possible to save
60
   CPU time in the PLC pitch search by making this smaller than MAX_PERIOD. The
61
   current value corresponds to a pitch of 66.67 Hz. */
62
77.2k
#define PLC_PITCH_LAG_MAX (720)
63
/* The minimum pitch lag to allow in the pitch-based PLC. This corresponds to a
64
   pitch of 480 Hz. */
65
19.3k
#define PLC_PITCH_LAG_MIN (100)
66
67
1.41M
#define FRAME_NONE         0
68
85.3k
#define FRAME_NORMAL       1
69
198k
#define FRAME_PLC_NOISE    2
70
332k
#define FRAME_PLC_PERIODIC 3
71
151k
#define FRAME_PLC_NEURAL   4
72
151k
#define FRAME_DRED         5
73
74
/**********************************************************************/
75
/*                                                                    */
76
/*                             DECODER                                */
77
/*                                                                    */
78
/**********************************************************************/
79
38.6k
#define DECODE_BUFFER_SIZE DEC_PITCH_BUF_SIZE
80
81
#define PLC_UPDATE_FRAMES 4
82
#define PLC_UPDATE_SAMPLES (PLC_UPDATE_FRAMES*FRAME_SIZE)
83
84
/** Decoder state
85
 @brief Decoder state
86
 */
87
struct OpusCustomDecoder {
88
   const OpusCustomMode *mode;
89
   int overlap;
90
   int channels;
91
   int stream_channels;
92
93
   int downsample;
94
   int start, end;
95
   int signalling;
96
   int disable_inv;
97
   int complexity;
98
   int arch;
99
#ifdef ENABLE_QEXT
100
   int qext_scale;
101
#endif
102
103
   /* Everything beyond this point gets cleared on a reset */
104
#define DECODER_RESET_START rng
105
106
   opus_uint32 rng;
107
   int error;
108
   int last_pitch_index;
109
   int loss_duration;
110
   int plc_duration;
111
   int last_frame_type;
112
   int skip_plc;
113
   int postfilter_period;
114
   int postfilter_period_old;
115
   opus_val16 postfilter_gain;
116
   opus_val16 postfilter_gain_old;
117
   int postfilter_tapset;
118
   int postfilter_tapset_old;
119
   int prefilter_and_fold;
120
121
   celt_sig preemph_memD[2];
122
123
#ifdef ENABLE_DEEP_PLC
124
   opus_int16 plc_pcm[PLC_UPDATE_SAMPLES];
125
   int plc_fill;
126
   float plc_preemphasis_mem;
127
#endif
128
129
#ifdef ENABLE_QEXT
130
   celt_glog qext_oldBandE[2*NB_QEXT_BANDS];
131
#endif
132
133
   celt_sig _decode_mem[1]; /* Size = channels*(DECODE_BUFFER_SIZE+mode->overlap) */
134
   /* celt_glog oldEBands[], Size = 2*mode->nbEBands */
135
   /* celt_glog oldLogE[], Size = 2*mode->nbEBands */
136
   /* celt_glog oldLogE2[], Size = 2*mode->nbEBands */
137
   /* celt_glog backgroundLogE[], Size = 2*mode->nbEBands */
138
   /* opus_val16 lpc[],  Size = channels*CELT_LPC_ORDER */
139
};
140
141
#if defined(ENABLE_HARDENING) || defined(ENABLE_ASSERTIONS)
142
/* Make basic checks on the CELT state to ensure we don't end
143
   up writing all over memory. */
144
void validate_celt_decoder(CELTDecoder *st)
145
203k
{
146
203k
#if !defined(CUSTOM_MODES) && !defined(ENABLE_OPUS_CUSTOM_API) && !defined(ENABLE_QEXT)
147
203k
   celt_assert(st->mode == opus_custom_mode_create(48000, 960, NULL));
148
203k
   celt_assert(st->overlap == 120);
149
203k
   celt_assert(st->end <= 21);
150
#else
151
/* From Section 4.3 in the spec: "The normal CELT layer uses 21 of those bands,
152
   though Opus Custom (see Section 6.2) may use a different number of bands"
153
154
   Check if it's within the maximum number of Bark frequency bands instead */
155
   celt_assert(st->end <= 25);
156
#endif
157
203k
   celt_assert(st->channels == 1 || st->channels == 2);
158
203k
   celt_assert(st->stream_channels == 1 || st->stream_channels == 2);
159
203k
   celt_assert(st->downsample > 0);
160
203k
   celt_assert(st->start == 0 || st->start == 17);
161
203k
   celt_assert(st->start < st->end);
162
203k
#ifdef OPUS_ARCHMASK
163
203k
   celt_assert(st->arch >= 0);
164
203k
   celt_assert(st->arch <= OPUS_ARCHMASK);
165
203k
#endif
166
203k
#ifndef ENABLE_QEXT
167
203k
   celt_assert(st->last_pitch_index <= PLC_PITCH_LAG_MAX);
168
203k
   celt_assert(st->last_pitch_index >= PLC_PITCH_LAG_MIN || st->last_pitch_index == 0);
169
203k
#endif
170
203k
   celt_assert(st->postfilter_period < MAX_PERIOD);
171
203k
   celt_assert(st->postfilter_period >= COMBFILTER_MINPERIOD || st->postfilter_period == 0);
172
203k
   celt_assert(st->postfilter_period_old < MAX_PERIOD);
173
203k
   celt_assert(st->postfilter_period_old >= COMBFILTER_MINPERIOD || st->postfilter_period_old == 0);
174
203k
   celt_assert(st->postfilter_tapset <= 2);
175
203k
   celt_assert(st->postfilter_tapset >= 0);
176
203k
   celt_assert(st->postfilter_tapset_old <= 2);
177
203k
   celt_assert(st->postfilter_tapset_old >= 0);
178
203k
}
179
#endif
180
181
int celt_decoder_get_size(int channels)
182
1.28M
{
183
#ifdef ENABLE_QEXT
184
   const CELTMode *mode = opus_custom_mode_create(96000, 960, NULL);
185
#else
186
1.28M
   const CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
187
1.28M
#endif
188
1.28M
   return opus_custom_decoder_get_size(mode, channels);
189
1.28M
}
190
191
OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_get_size(const CELTMode *mode, int channels)
192
2.75M
{
193
2.75M
   int size;
194
#ifdef ENABLE_QEXT
195
   int qext_scale;
196
   if (mode->Fs == 96000 && (mode->shortMdctSize==240 || mode->shortMdctSize==180)) {
197
      qext_scale = 2;
198
   } else qext_scale = 1;
199
#endif
200
2.75M
   size = sizeof(struct CELTDecoder)
201
2.75M
            + (channels*(QEXT_SCALE(DECODE_BUFFER_SIZE)+mode->overlap)-1)*sizeof(celt_sig)
202
2.75M
            + 4*2*mode->nbEBands*sizeof(celt_glog)
203
2.75M
            + channels*CELT_LPC_ORDER*sizeof(opus_val16);
204
2.75M
   return size;
205
2.75M
}
206
207
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
208
CELTDecoder *opus_custom_decoder_create(const CELTMode *mode, int channels, int *error)
209
{
210
   int ret;
211
   CELTDecoder *st = (CELTDecoder *)opus_alloc(opus_custom_decoder_get_size(mode, channels));
212
   ret = opus_custom_decoder_init(st, mode, channels);
213
   if (ret != OPUS_OK)
214
   {
215
      opus_custom_decoder_destroy(st);
216
      st = NULL;
217
   }
218
   if (error)
219
      *error = ret;
220
   return st;
221
}
222
#endif /* CUSTOM_MODES */
223
224
int celt_decoder_init(CELTDecoder *st, opus_int32 sampling_rate, int channels)
225
60.4k
{
226
60.4k
   int ret;
227
#ifdef ENABLE_QEXT
228
   if (sampling_rate == 96000) {
229
      return opus_custom_decoder_init(st, opus_custom_mode_create(96000, 960, NULL), channels);
230
   }
231
#endif
232
60.4k
   ret = opus_custom_decoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
233
60.4k
   if (ret != OPUS_OK)
234
0
      return ret;
235
60.4k
   st->downsample = resampling_factor(sampling_rate);
236
60.4k
   if (st->downsample==0)
237
0
      return OPUS_BAD_ARG;
238
60.4k
   else
239
60.4k
      return OPUS_OK;
240
60.4k
}
241
242
OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_init(CELTDecoder *st, const CELTMode *mode, int channels)
243
60.4k
{
244
60.4k
   if (channels < 0 || channels > 2)
245
0
      return OPUS_BAD_ARG;
246
247
60.4k
   if (st==NULL)
248
0
      return OPUS_ALLOC_FAIL;
249
250
60.4k
   OPUS_CLEAR((char*)st, opus_custom_decoder_get_size(mode, channels));
251
252
60.4k
   st->mode = mode;
253
60.4k
   st->overlap = mode->overlap;
254
60.4k
   st->stream_channels = st->channels = channels;
255
256
60.4k
   st->downsample = 1;
257
60.4k
   st->start = 0;
258
60.4k
   st->end = st->mode->effEBands;
259
60.4k
   st->signalling = 1;
260
60.4k
#ifndef DISABLE_UPDATE_DRAFT
261
60.4k
   st->disable_inv = channels == 1;
262
#else
263
   st->disable_inv = 0;
264
#endif
265
60.4k
   st->arch = opus_select_arch();
266
267
#ifdef ENABLE_QEXT
268
   if (st->mode->Fs == 96000 && (mode->shortMdctSize==240 || mode->shortMdctSize==180)) st->qext_scale = 2;
269
   else st->qext_scale = 1;
270
#endif
271
272
60.4k
   opus_custom_decoder_ctl(st, OPUS_RESET_STATE);
273
274
60.4k
   return OPUS_OK;
275
60.4k
}
276
277
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
278
void opus_custom_decoder_destroy(CELTDecoder *st)
279
{
280
   opus_free(st);
281
}
282
#endif /* CUSTOM_MODES */
283
284
#if !defined(CUSTOM_MODES) && !defined(ENABLE_OPUS_CUSTOM_API) && !defined(ENABLE_QEXT)
285
/* Special case for stereo with no downsampling and no accumulation. This is
286
   quite common and we can make it faster by processing both channels in the
287
   same loop, reducing overhead due to the dependency loop in the IIR filter. */
288
static void deemphasis_stereo_simple(celt_sig *in[], opus_res *pcm, int N, const opus_val16 coef0,
289
      celt_sig *mem)
290
133k
{
291
133k
   celt_sig * OPUS_RESTRICT x0;
292
133k
   celt_sig * OPUS_RESTRICT x1;
293
133k
   celt_sig m0, m1;
294
133k
   int j;
295
133k
   x0=in[0];
296
133k
   x1=in[1];
297
133k
   m0 = mem[0];
298
133k
   m1 = mem[1];
299
55.0M
   for (j=0;j<N;j++)
300
54.8M
   {
301
54.8M
      celt_sig tmp0, tmp1;
302
      /* Add VERY_SMALL to x[] first to reduce dependency chain. */
303
54.8M
      tmp0 = SATURATE(x0[j] + VERY_SMALL + m0, SIG_SAT);
304
54.8M
      tmp1 = SATURATE(x1[j] + VERY_SMALL + m1, SIG_SAT);
305
54.8M
      m0 = MULT16_32_Q15(coef0, tmp0);
306
54.8M
      m1 = MULT16_32_Q15(coef0, tmp1);
307
54.8M
      pcm[2*j  ] = SIG2RES(tmp0);
308
54.8M
      pcm[2*j+1] = SIG2RES(tmp1);
309
54.8M
   }
310
133k
   mem[0] = m0;
311
133k
   mem[1] = m1;
312
133k
}
313
#endif
314
315
#ifndef RESYNTH
316
static
317
#endif
318
void deemphasis(celt_sig *in[], opus_res *pcm, int N, int C, int downsample, const opus_val16 *coef,
319
      celt_sig *mem, int accum)
320
203k
{
321
203k
   int c;
322
203k
   int Nd;
323
203k
   int apply_downsampling=0;
324
203k
   opus_val16 coef0;
325
203k
   VARDECL(celt_sig, scratch);
326
203k
   SAVE_STACK;
327
203k
#if !defined(CUSTOM_MODES) && !defined(ENABLE_OPUS_CUSTOM_API) && !defined(ENABLE_QEXT)
328
   /* Short version for common case. */
329
203k
   if (downsample == 1 && C == 2 && !accum)
330
133k
   {
331
133k
      deemphasis_stereo_simple(in, pcm, N, coef[0], mem);
332
133k
      return;
333
133k
   }
334
70.2k
#endif
335
70.2k
   ALLOC(scratch, N, celt_sig);
336
70.2k
   coef0 = coef[0];
337
70.2k
   Nd = N/downsample;
338
118k
   c=0; do {
339
118k
      int j;
340
118k
      celt_sig * OPUS_RESTRICT x;
341
118k
      opus_res  * OPUS_RESTRICT y;
342
118k
      celt_sig m = mem[c];
343
118k
      x =in[c];
344
118k
      y = pcm+c;
345
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API) || defined(ENABLE_QEXT)
346
      if (coef[1] != 0)
347
      {
348
         opus_val16 coef1 = coef[1];
349
         opus_val16 coef3 = coef[3];
350
         for (j=0;j<N;j++)
351
         {
352
            celt_sig tmp = SATURATE(x[j] + m + VERY_SMALL, SIG_SAT);
353
            m = MULT16_32_Q15(coef0, tmp)
354
                          - MULT16_32_Q15(coef1, x[j]);
355
            tmp = SHL32(MULT16_32_Q15(coef3, tmp), 2);
356
            scratch[j] = tmp;
357
         }
358
         apply_downsampling=1;
359
      } else
360
#endif
361
118k
      if (downsample>1)
362
0
      {
363
         /* Shortcut for the standard (non-custom modes) case */
364
0
         for (j=0;j<N;j++)
365
0
         {
366
0
            celt_sig tmp = SATURATE(x[j] + VERY_SMALL + m, SIG_SAT);
367
0
            m = MULT16_32_Q15(coef0, tmp);
368
0
            scratch[j] = tmp;
369
0
         }
370
0
         apply_downsampling=1;
371
118k
      } else {
372
         /* Shortcut for the standard (non-custom modes) case */
373
118k
         if (accum)
374
99.6k
         {
375
66.0M
            for (j=0;j<N;j++)
376
65.9M
            {
377
65.9M
               celt_sig tmp = SATURATE(x[j] + m + VERY_SMALL, SIG_SAT);
378
65.9M
               m = MULT16_32_Q15(coef0, tmp);
379
65.9M
               y[j*C] = ADD_RES(y[j*C], SIG2RES(tmp));
380
65.9M
            }
381
99.6k
         } else
382
18.4k
         {
383
7.99M
            for (j=0;j<N;j++)
384
7.97M
            {
385
7.97M
               celt_sig tmp = SATURATE(x[j] + VERY_SMALL + m, SIG_SAT);
386
7.97M
               m = MULT16_32_Q15(coef0, tmp);
387
7.97M
               y[j*C] = SIG2RES(tmp);
388
7.97M
            }
389
18.4k
         }
390
118k
      }
391
118k
      mem[c] = m;
392
393
118k
      if (apply_downsampling)
394
0
      {
395
         /* Perform down-sampling */
396
0
         if (accum)
397
0
         {
398
0
            for (j=0;j<Nd;j++)
399
0
               y[j*C] = ADD_RES(y[j*C], SIG2RES(scratch[j*downsample]));
400
0
         } else
401
0
         {
402
0
            for (j=0;j<Nd;j++)
403
0
               y[j*C] = SIG2RES(scratch[j*downsample]);
404
0
         }
405
0
      }
406
118k
   } while (++c<C);
407
70.2k
   RESTORE_STACK;
408
70.2k
}
409
410
#ifndef RESYNTH
411
static
412
#endif
413
void celt_synthesis(const CELTMode *mode, celt_norm *X, celt_sig * out_syn[],
414
                    celt_glog *oldBandE, int start, int effEnd, int C, int CC,
415
                    int isTransient, int LM, int downsample,
416
                    int silence, int arch ARG_QEXT(const CELTMode *qext_mode) ARG_QEXT(const celt_glog *qext_bandLogE) ARG_QEXT(int qext_end))
417
165k
{
418
165k
   int c, i;
419
165k
   int M;
420
165k
   int b;
421
165k
   int B;
422
165k
   int N, NB;
423
165k
   int shift;
424
165k
   int nbEBands;
425
165k
   int overlap;
426
165k
   VARDECL(celt_sig, freq);
427
165k
   SAVE_STACK;
428
429
165k
   overlap = mode->overlap;
430
165k
   nbEBands = mode->nbEBands;
431
165k
   N = mode->shortMdctSize<<LM;
432
165k
   ALLOC(freq, N, celt_sig); /**< Interleaved signal MDCTs */
433
165k
   M = 1<<LM;
434
#ifdef ENABLE_QEXT
435
   if (mode->Fs != 96000) qext_end=2;
436
#endif
437
438
165k
   if (isTransient)
439
6.33k
   {
440
6.33k
      B = M;
441
6.33k
      NB = mode->shortMdctSize;
442
6.33k
      shift = mode->maxLM;
443
159k
   } else {
444
159k
      B = 1;
445
159k
      NB = mode->shortMdctSize<<LM;
446
159k
      shift = mode->maxLM-LM;
447
159k
   }
448
449
165k
   if (CC==2&&C==1)
450
51.3k
   {
451
      /* Copying a mono streams to two channels */
452
51.3k
      celt_sig *freq2;
453
51.3k
      denormalise_bands(mode, X, freq, oldBandE, start, effEnd, M,
454
51.3k
            downsample, silence);
455
#ifdef ENABLE_QEXT
456
      if (qext_mode)
457
         denormalise_bands(qext_mode, X, freq, qext_bandLogE, 0, qext_end, M,
458
                        downsample, silence);
459
#endif
460
      /* Store a temporary copy in the output buffer because the IMDCT destroys its input. */
461
51.3k
      freq2 = out_syn[1]+overlap/2;
462
51.3k
      OPUS_COPY(freq2, freq, N);
463
116k
      for (b=0;b<B;b++)
464
64.9k
         clt_mdct_backward(&mode->mdct, &freq2[b], out_syn[0]+NB*b, mode->window, overlap, shift, B, arch);
465
116k
      for (b=0;b<B;b++)
466
64.9k
         clt_mdct_backward(&mode->mdct, &freq[b], out_syn[1]+NB*b, mode->window, overlap, shift, B, arch);
467
114k
   } else if (CC==1&&C==2)
468
1.85k
   {
469
      /* Downmixing a stereo stream to mono */
470
1.85k
      celt_sig *freq2;
471
1.85k
      freq2 = out_syn[0]+overlap/2;
472
1.85k
      denormalise_bands(mode, X, freq, oldBandE, start, effEnd, M,
473
1.85k
            downsample, silence);
474
      /* Use the output buffer as temp array before downmixing. */
475
1.85k
      denormalise_bands(mode, X+N, freq2, oldBandE+nbEBands, start, effEnd, M,
476
1.85k
            downsample, silence);
477
#ifdef ENABLE_QEXT
478
      if (qext_mode)
479
      {
480
         denormalise_bands(qext_mode, X, freq, qext_bandLogE, 0, qext_end, M,
481
                        downsample, silence);
482
         denormalise_bands(qext_mode, X+N, freq2, qext_bandLogE+NB_QEXT_BANDS, 0, qext_end, M,
483
                        downsample, silence);
484
      }
485
#endif
486
692k
      for (i=0;i<N;i++)
487
690k
         freq[i] = ADD32(HALF32(freq[i]), HALF32(freq2[i]));
488
4.10k
      for (b=0;b<B;b++)
489
2.24k
         clt_mdct_backward(&mode->mdct, &freq[b], out_syn[0]+NB*b, mode->window, overlap, shift, B, arch);
490
112k
   } else {
491
      /* Normal case (mono or stereo) */
492
210k
      c=0; do {
493
210k
         denormalise_bands(mode, X+c*N, freq, oldBandE+c*nbEBands, start, effEnd, M,
494
210k
               downsample, silence);
495
#ifdef ENABLE_QEXT
496
         if (qext_mode)
497
            denormalise_bands(qext_mode, X+c*N, freq, qext_bandLogE+c*NB_QEXT_BANDS, 0, qext_end, M,
498
                           downsample, silence);
499
#endif
500
429k
         for (b=0;b<B;b++)
501
219k
            clt_mdct_backward(&mode->mdct, &freq[b], out_syn[c]+NB*b, mode->window, overlap, shift, B, arch);
502
210k
      } while (++c<CC);
503
112k
   }
504
   /* Saturate IMDCT output so that we can't overflow in the pitch postfilter
505
      or in the */
506
315k
   c=0; do {
507
155M
      for (i=0;i<N;i++)
508
155M
         out_syn[c][i] = SATURATE(out_syn[c][i], SIG_SAT);
509
315k
   } while (++c<CC);
510
165k
   RESTORE_STACK;
511
165k
}
512
513
static void tf_decode(int start, int end, int isTransient, int *tf_res, int LM, ec_dec *dec)
514
85.3k
{
515
85.3k
   int i, curr, tf_select;
516
85.3k
   int tf_select_rsv;
517
85.3k
   int tf_changed;
518
85.3k
   int logp;
519
85.3k
   opus_uint32 budget;
520
85.3k
   opus_uint32 tell;
521
522
85.3k
   budget = dec->storage*8;
523
85.3k
   tell = ec_tell(dec);
524
85.3k
   logp = isTransient ? 2 : 4;
525
85.3k
   tf_select_rsv = LM>0 && tell+logp+1<=budget;
526
85.3k
   budget -= tf_select_rsv;
527
85.3k
   tf_changed = curr = 0;
528
1.10M
   for (i=start;i<end;i++)
529
1.01M
   {
530
1.01M
      if (tell+logp<=budget)
531
643k
      {
532
643k
         curr ^= ec_dec_bit_logp(dec, logp);
533
643k
         tell = ec_tell(dec);
534
643k
         tf_changed |= curr;
535
643k
      }
536
1.01M
      tf_res[i] = curr;
537
1.01M
      logp = isTransient ? 4 : 5;
538
1.01M
   }
539
85.3k
   tf_select = 0;
540
85.3k
   if (tf_select_rsv &&
541
40.5k
     tf_select_table[LM][4*isTransient+0+tf_changed] !=
542
40.5k
     tf_select_table[LM][4*isTransient+2+tf_changed])
543
14.4k
   {
544
14.4k
      tf_select = ec_dec_bit_logp(dec, 1);
545
14.4k
   }
546
1.10M
   for (i=start;i<end;i++)
547
1.01M
   {
548
1.01M
      tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
549
1.01M
   }
550
85.3k
}
551
552
static int celt_plc_pitch_search(CELTDecoder *st, celt_sig *decode_mem[2], int C, int arch)
553
19.3k
{
554
19.3k
   int pitch_index;
555
#ifdef ENABLE_QEXT
556
   int qext_scale;
557
#endif
558
19.3k
   VARDECL( opus_val16, lp_pitch_buf );
559
19.3k
   SAVE_STACK;
560
#ifdef ENABLE_QEXT
561
   qext_scale = st->qext_scale;
562
#else
563
19.3k
   (void)st;
564
19.3k
#endif
565
19.3k
   ALLOC( lp_pitch_buf, DECODE_BUFFER_SIZE>>1, opus_val16 );
566
19.3k
   pitch_downsample(decode_mem, lp_pitch_buf,
567
19.3k
         DECODE_BUFFER_SIZE>>1, C, QEXT_SCALE(2), arch);
568
19.3k
   pitch_search(lp_pitch_buf+(PLC_PITCH_LAG_MAX>>1), lp_pitch_buf,
569
19.3k
         DECODE_BUFFER_SIZE-PLC_PITCH_LAG_MAX,
570
19.3k
         PLC_PITCH_LAG_MAX-PLC_PITCH_LAG_MIN, &pitch_index, arch);
571
19.3k
   pitch_index = PLC_PITCH_LAG_MAX-pitch_index;
572
19.3k
   RESTORE_STACK;
573
19.3k
   return QEXT_SCALE(pitch_index);
574
19.3k
}
575
576
static void prefilter_and_fold(CELTDecoder * OPUS_RESTRICT st, int N)
577
15.7k
{
578
15.7k
   int c;
579
15.7k
   int CC;
580
15.7k
   int i;
581
15.7k
   int overlap;
582
15.7k
   celt_sig *decode_mem[2];
583
15.7k
   const OpusCustomMode *mode;
584
15.7k
   int decode_buffer_size;
585
#ifdef ENABLE_QEXT
586
   int qext_scale;
587
#endif
588
15.7k
   VARDECL(opus_val32, etmp);
589
15.7k
   SAVE_STACK
590
#ifdef ENABLE_QEXT
591
   qext_scale = st->qext_scale;
592
#endif
593
15.7k
   decode_buffer_size = QEXT_SCALE(DECODE_BUFFER_SIZE);
594
15.7k
   mode = st->mode;
595
15.7k
   overlap = st->overlap;
596
15.7k
   CC = st->channels;
597
15.7k
   ALLOC(etmp, overlap, opus_val32);
598
28.9k
   c=0; do {
599
28.9k
      decode_mem[c] = st->_decode_mem + c*(decode_buffer_size+overlap);
600
28.9k
   } while (++c<CC);
601
602
28.9k
   c=0; do {
603
      /* Apply the pre-filter to the MDCT overlap for the next frame because
604
         the post-filter will be re-applied in the decoder after the MDCT
605
         overlap. */
606
28.9k
      comb_filter(etmp, decode_mem[c]+decode_buffer_size-N,
607
28.9k
         st->postfilter_period_old, st->postfilter_period, overlap,
608
28.9k
         -st->postfilter_gain_old, -st->postfilter_gain,
609
28.9k
         st->postfilter_tapset_old, st->postfilter_tapset, NULL, 0, st->arch);
610
611
      /* Simulate TDAC on the concealed audio so that it blends with the
612
         MDCT of the next frame. */
613
1.76M
      for (i=0;i<overlap/2;i++)
614
1.73M
      {
615
1.73M
         decode_mem[c][decode_buffer_size-N+i] =
616
1.73M
            MULT16_32_Q15(COEF2VAL16(mode->window[i]), etmp[overlap-1-i])
617
1.73M
            + MULT16_32_Q15 (COEF2VAL16(mode->window[overlap-i-1]), etmp[i]);
618
1.73M
      }
619
28.9k
   } while (++c<CC);
620
15.7k
   RESTORE_STACK;
621
15.7k
}
622
623
#ifdef ENABLE_DEEP_PLC
624
625
#define SINC_ORDER 48
626
/* h=cos(pi/2*abs(sin([-24:24]/48*pi*23./24)).^2);
627
   b=sinc([-24:24]/3*1.02).*h;
628
   b=b/sum(b); */
629
static const float sinc_filter[SINC_ORDER+1] = {
630
    4.2931e-05f, -0.000190293f, -0.000816132f, -0.000637162f, 0.00141662f, 0.00354764f, 0.00184368f, -0.00428274f,
631
    -0.00856105f, -0.0034003f, 0.00930201f, 0.0159616f, 0.00489785f, -0.0169649f, -0.0259484f, -0.00596856f,
632
    0.0286551f, 0.0405872f, 0.00649994f, -0.0509284f, -0.0716655f, -0.00665212f,  0.134336f,  0.278927f,
633
    0.339995f,  0.278927f,  0.134336f, -0.00665212f, -0.0716655f, -0.0509284f, 0.00649994f, 0.0405872f,
634
    0.0286551f, -0.00596856f, -0.0259484f, -0.0169649f, 0.00489785f, 0.0159616f, 0.00930201f, -0.0034003f,
635
    -0.00856105f, -0.00428274f, 0.00184368f, 0.00354764f, 0.00141662f, -0.000637162f, -0.000816132f, -0.000190293f,
636
    4.2931e-05f
637
};
638
639
void update_plc_state(LPCNetPLCState *lpcnet, celt_sig *decode_mem[2], float *plc_preemphasis_mem, int CC)
640
{
641
   int i;
642
   int tmp_read_post, tmp_fec_skip;
643
   int offset;
644
   VARDECL(celt_sig, buf48k);
645
   VARDECL(opus_int16, buf16k);
646
   SAVE_STACK;
647
   ALLOC(buf48k, DECODE_BUFFER_SIZE, celt_sig);
648
   ALLOC(buf16k, PLC_UPDATE_SAMPLES, opus_int16);
649
   if (CC == 1) OPUS_COPY(buf48k, decode_mem[0], DECODE_BUFFER_SIZE);
650
   else {
651
      for (i=0;i<DECODE_BUFFER_SIZE;i++) {
652
         buf48k[i] = .5*(decode_mem[0][i] + decode_mem[1][i]);
653
      }
654
   }
655
   /* Down-sample the last 40 ms. */
656
   for (i=1;i<DECODE_BUFFER_SIZE;i++) buf48k[i] += PREEMPHASIS*buf48k[i-1];
657
   *plc_preemphasis_mem = buf48k[DECODE_BUFFER_SIZE-1];
658
   offset = DECODE_BUFFER_SIZE-SINC_ORDER-1 - 3*(PLC_UPDATE_SAMPLES-1);
659
   celt_assert(3*(PLC_UPDATE_SAMPLES-1) + SINC_ORDER + offset == DECODE_BUFFER_SIZE-1);
660
   for (i=0;i<PLC_UPDATE_SAMPLES;i++) {
661
      int j;
662
      float sum = 0;
663
      for (j=0;j<SINC_ORDER+1;j++) {
664
         sum += buf48k[3*i + j + offset]*sinc_filter[j];
665
      }
666
      buf16k[i] = float2int(MIN32(32767.f, MAX32(-32767.f, sum)));
667
   }
668
   tmp_read_post = lpcnet->fec_read_pos;
669
   tmp_fec_skip = lpcnet->fec_skip;
670
   for (i=0;i<PLC_UPDATE_FRAMES;i++) {
671
      lpcnet_plc_update(lpcnet, &buf16k[FRAME_SIZE*i]);
672
   }
673
   lpcnet->fec_read_pos = tmp_read_post;
674
   lpcnet->fec_skip = tmp_fec_skip;
675
   RESTORE_STACK;
676
}
677
#endif
678
679
static void celt_decode_lost(CELTDecoder * OPUS_RESTRICT st, int N, int LM
680
#ifdef ENABLE_DEEP_PLC
681
      ,LPCNetPLCState *lpcnet
682
#endif
683
      )
684
118k
{
685
118k
   int c;
686
118k
   int i;
687
118k
   const int C = st->channels;
688
118k
   celt_sig *decode_mem[2];
689
118k
   celt_sig *out_syn[2];
690
118k
   opus_val16 *lpc;
691
118k
   celt_glog *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
692
118k
   const OpusCustomMode *mode;
693
118k
   int nbEBands;
694
118k
   int overlap;
695
118k
   int start;
696
118k
   int loss_duration;
697
118k
   int curr_frame_type;
698
118k
   const opus_int16 *eBands;
699
118k
   int decode_buffer_size;
700
118k
   int max_period;
701
#ifdef ENABLE_QEXT
702
   int qext_scale;
703
#endif
704
118k
   SAVE_STACK;
705
#ifdef ENABLE_QEXT
706
   qext_scale = st->qext_scale;
707
#endif
708
118k
   decode_buffer_size = QEXT_SCALE(DECODE_BUFFER_SIZE);
709
118k
   max_period = QEXT_SCALE(MAX_PERIOD);
710
118k
   mode = st->mode;
711
118k
   nbEBands = mode->nbEBands;
712
118k
   overlap = mode->overlap;
713
118k
   eBands = mode->eBands;
714
715
222k
   c=0; do {
716
222k
      decode_mem[c] = st->_decode_mem + c*(decode_buffer_size+overlap);
717
222k
      out_syn[c] = decode_mem[c]+decode_buffer_size-N;
718
222k
   } while (++c<C);
719
118k
   oldBandE = (celt_glog*)(st->_decode_mem+(decode_buffer_size+overlap)*C);
720
118k
   oldLogE = oldBandE + 2*nbEBands;
721
118k
   oldLogE2 = oldLogE + 2*nbEBands;
722
118k
   backgroundLogE = oldLogE2 + 2*nbEBands;
723
118k
   lpc = (opus_val16*)(backgroundLogE + 2*nbEBands);
724
725
118k
   loss_duration = st->loss_duration;
726
118k
   start = st->start;
727
118k
   curr_frame_type = FRAME_PLC_PERIODIC;
728
118k
   if (st->plc_duration >= 40 || start != 0 || st->skip_plc)
729
80.3k
      curr_frame_type = FRAME_PLC_NOISE;
730
#ifdef ENABLE_DEEP_PLC
731
   if (start == 0 && lpcnet != NULL && st->mode->Fs != 96000 && lpcnet->loaded)
732
   {
733
      if (st->complexity >= 5 && st->plc_duration < 80 && !st->skip_plc)
734
         curr_frame_type = FRAME_PLC_NEURAL;
735
#ifdef ENABLE_DRED
736
      if (lpcnet->fec_fill_pos > lpcnet->fec_read_pos)
737
         curr_frame_type = FRAME_DRED;
738
#endif
739
   }
740
#endif
741
742
118k
   if (curr_frame_type == FRAME_PLC_NOISE)
743
80.3k
   {
744
      /* Noise-based PLC/CNG */
745
80.3k
      VARDECL(celt_norm, X);
746
80.3k
      opus_uint32 seed;
747
80.3k
      int end;
748
80.3k
      int effEnd;
749
80.3k
      celt_glog decay;
750
80.3k
      end = st->end;
751
80.3k
      effEnd = IMAX(start, IMIN(end, mode->effEBands));
752
753
80.3k
      ALLOC(X, C*N, celt_norm);   /**< Interleaved normalised MDCTs */
754
153k
      c=0; do {
755
153k
         OPUS_MOVE(decode_mem[c], decode_mem[c]+N,
756
153k
               decode_buffer_size-N+overlap);
757
153k
      } while (++c<C);
758
759
80.3k
      if (st->prefilter_and_fold) {
760
666
         prefilter_and_fold(st, N);
761
666
      }
762
763
      /* Energy decay */
764
80.3k
      decay = loss_duration==0 ? GCONST(1.5f) : GCONST(.5f);
765
80.3k
      c=0; do
766
153k
      {
767
2.38M
         for (i=start;i<end;i++)
768
2.23M
            oldBandE[c*nbEBands+i] = MAXG(backgroundLogE[c*nbEBands+i], oldBandE[c*nbEBands+i] - decay);
769
153k
      } while (++c<C);
770
80.3k
      seed = st->rng;
771
233k
      for (c=0;c<C;c++)
772
153k
      {
773
2.38M
         for (i=start;i<effEnd;i++)
774
2.23M
         {
775
2.23M
            int j;
776
2.23M
            int boffs;
777
2.23M
            int blen;
778
2.23M
            boffs = N*c+(eBands[i]<<LM);
779
2.23M
            blen = (eBands[i+1]-eBands[i])<<LM;
780
49.6M
            for (j=0;j<blen;j++)
781
47.4M
            {
782
47.4M
               seed = celt_lcg_rand(seed);
783
47.4M
               X[boffs+j] = SHL32((celt_norm)((opus_int32)seed>>20), NORM_SHIFT-14);
784
47.4M
            }
785
2.23M
            renormalise_vector(X+boffs, blen, Q31ONE, st->arch);
786
2.23M
         }
787
153k
      }
788
80.3k
      st->rng = seed;
789
790
80.3k
      celt_synthesis(mode, X, out_syn, oldBandE, start, effEnd, C, C, 0, LM, st->downsample, 0, st->arch ARG_QEXT(NULL) ARG_QEXT(NULL) ARG_QEXT(0));
791
792
      /* Run the postfilter with the last parameters. */
793
153k
      c=0; do {
794
153k
         st->postfilter_period=IMAX(st->postfilter_period, COMBFILTER_MINPERIOD);
795
153k
         st->postfilter_period_old=IMAX(st->postfilter_period_old, COMBFILTER_MINPERIOD);
796
153k
         comb_filter(out_syn[c], out_syn[c], st->postfilter_period_old, st->postfilter_period, mode->shortMdctSize,
797
153k
               st->postfilter_gain_old, st->postfilter_gain, st->postfilter_tapset_old, st->postfilter_tapset,
798
153k
               mode->window, overlap, st->arch);
799
153k
         if (LM!=0)
800
143k
            comb_filter(out_syn[c]+mode->shortMdctSize, out_syn[c]+mode->shortMdctSize, st->postfilter_period, st->postfilter_period, N-mode->shortMdctSize,
801
143k
                  st->postfilter_gain, st->postfilter_gain, st->postfilter_tapset, st->postfilter_tapset,
802
143k
                  mode->window, overlap, st->arch);
803
804
153k
      } while (++c<C);
805
80.3k
      st->postfilter_period_old = st->postfilter_period;
806
80.3k
      st->postfilter_gain_old = st->postfilter_gain;
807
80.3k
      st->postfilter_tapset_old = st->postfilter_tapset;
808
809
80.3k
      st->prefilter_and_fold = 0;
810
      /* Skip regular PLC until we get two consecutive packets. */
811
80.3k
      st->skip_plc = 1;
812
80.3k
   } else {
813
37.7k
      int exc_length;
814
      /* Pitch-based PLC */
815
37.7k
      const celt_coef *window;
816
37.7k
      opus_val16 *exc;
817
37.7k
      opus_val16 fade = Q15ONE;
818
37.7k
      int pitch_index;
819
37.7k
      int curr_neural;
820
37.7k
      int last_neural;
821
37.7k
      VARDECL(opus_val16, _exc);
822
37.7k
      VARDECL(opus_val16, fir_tmp);
823
824
37.7k
      curr_neural = curr_frame_type == FRAME_PLC_NEURAL || curr_frame_type == FRAME_DRED;
825
37.7k
      last_neural = st->last_frame_type == FRAME_PLC_NEURAL || st->last_frame_type == FRAME_DRED;
826
37.7k
      if (st->last_frame_type != FRAME_PLC_PERIODIC && !(last_neural && curr_neural))
827
19.3k
      {
828
19.3k
         st->last_pitch_index = pitch_index = celt_plc_pitch_search(st, decode_mem, C, st->arch);
829
19.3k
      } else {
830
18.4k
         pitch_index = st->last_pitch_index;
831
18.4k
         fade = QCONST16(.8f,15);
832
18.4k
      }
833
#ifdef ENABLE_DEEP_PLC
834
      if (curr_neural && !last_neural) update_plc_state(lpcnet, decode_mem, &st->plc_preemphasis_mem, C);
835
#endif
836
837
      /* We want the excitation for 2 pitch periods in order to look for a
838
         decaying signal, but we can't get more than MAX_PERIOD. */
839
37.7k
      exc_length = IMIN(2*pitch_index, max_period);
840
841
37.7k
      ALLOC(_exc, max_period+CELT_LPC_ORDER, opus_val16);
842
37.7k
      ALLOC(fir_tmp, exc_length, opus_val16);
843
37.7k
      exc = _exc+CELT_LPC_ORDER;
844
37.7k
      window = mode->window;
845
69.5k
      c=0; do {
846
69.5k
         opus_val16 decay;
847
69.5k
         opus_val16 attenuation;
848
69.5k
         opus_val32 S1=0;
849
69.5k
         celt_sig *buf;
850
69.5k
         int extrapolation_offset;
851
69.5k
         int extrapolation_len;
852
69.5k
         int j;
853
854
69.5k
         buf = decode_mem[c];
855
72.9M
         for (i=0;i<max_period+CELT_LPC_ORDER;i++)
856
72.8M
            exc[i-CELT_LPC_ORDER] = SROUND16(buf[decode_buffer_size-max_period-CELT_LPC_ORDER+i], SIG_SHIFT);
857
858
69.5k
         if (st->last_frame_type != FRAME_PLC_PERIODIC && !(last_neural && curr_neural))
859
35.2k
         {
860
35.2k
            opus_val32 ac[CELT_LPC_ORDER+1];
861
            /* Compute LPC coefficients for the last MAX_PERIOD samples before
862
               the first loss so we can work in the excitation-filter domain. */
863
35.2k
            _celt_autocorr(exc, ac, window, overlap,
864
35.2k
                   CELT_LPC_ORDER, max_period, st->arch);
865
            /* Add a noise floor of -40 dB. */
866
#ifdef FIXED_POINT
867
            ac[0] += SHR32(ac[0],13);
868
#else
869
35.2k
            ac[0] *= 1.0001f;
870
35.2k
#endif
871
            /* Use lag windowing to stabilize the Levinson-Durbin recursion. */
872
882k
            for (i=1;i<=CELT_LPC_ORDER;i++)
873
847k
            {
874
               /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
875
#ifdef FIXED_POINT
876
               ac[i] -= MULT16_32_Q15(2*i*i, ac[i]);
877
#else
878
847k
               ac[i] -= ac[i]*(0.008f*0.008f)*i*i;
879
847k
#endif
880
847k
            }
881
35.2k
            _celt_lpc(lpc+c*CELT_LPC_ORDER, ac, CELT_LPC_ORDER);
882
#ifdef FIXED_POINT
883
         /* For fixed-point, apply bandwidth expansion until we can guarantee that
884
            no overflow can happen in the IIR filter. This means:
885
            32768*sum(abs(filter)) < 2^31 */
886
         while (1) {
887
            opus_val16 tmp=Q15ONE;
888
            opus_val32 sum=QCONST16(1., SIG_SHIFT);
889
            for (i=0;i<CELT_LPC_ORDER;i++)
890
               sum += ABS16(lpc[c*CELT_LPC_ORDER+i]);
891
            if (sum < 65535) break;
892
            for (i=0;i<CELT_LPC_ORDER;i++)
893
            {
894
               tmp = MULT16_16_Q15(QCONST16(.99f,15), tmp);
895
               lpc[c*CELT_LPC_ORDER+i] = MULT16_16_Q15(lpc[c*CELT_LPC_ORDER+i], tmp);
896
            }
897
         }
898
#endif
899
35.2k
         }
900
         /* Initialize the LPC history with the samples just before the start
901
            of the region for which we're computing the excitation. */
902
69.5k
         {
903
            /* Compute the excitation for exc_length samples before the loss. We need the copy
904
               because celt_fir() cannot filter in-place. */
905
69.5k
            celt_fir(exc+max_period-exc_length, lpc+c*CELT_LPC_ORDER,
906
69.5k
                  fir_tmp, exc_length, CELT_LPC_ORDER, st->arch);
907
69.5k
            OPUS_COPY(exc+max_period-exc_length, fir_tmp, exc_length);
908
69.5k
         }
909
910
         /* Check if the waveform is decaying, and if so how fast.
911
            We do this to avoid adding energy when concealing in a segment
912
            with decaying energy. */
913
69.5k
         {
914
69.5k
            opus_val32 E1=1, E2=1;
915
69.5k
            int decay_length;
916
#ifdef FIXED_POINT
917
            int shift = IMAX(0,2*celt_zlog2(celt_maxabs16(&exc[max_period-exc_length], exc_length))-20);
918
#ifdef ENABLE_QEXT
919
            if (st->qext_scale==2) shift++;
920
#endif
921
#endif
922
69.5k
            decay_length = exc_length>>1;
923
18.6M
            for (i=0;i<decay_length;i++)
924
18.6M
            {
925
18.6M
               opus_val16 e;
926
18.6M
               e = exc[max_period-decay_length+i];
927
18.6M
               E1 += SHR32(MULT16_16(e, e), shift);
928
18.6M
               e = exc[max_period-2*decay_length+i];
929
18.6M
               E2 += SHR32(MULT16_16(e, e), shift);
930
18.6M
            }
931
69.5k
            E1 = MIN32(E1, E2);
932
69.5k
            decay = celt_sqrt(frac_div32(SHR32(E1, 1), E2));
933
69.5k
         }
934
935
         /* Move the decoder memory one frame to the left to give us room to
936
            add the data for the new frame. We ignore the overlap that extends
937
            past the end of the buffer, because we aren't going to use it. */
938
69.5k
         OPUS_MOVE(buf, buf+N, decode_buffer_size-N);
939
940
         /* Extrapolate from the end of the excitation with a period of
941
            "pitch_index", scaling down each period by an additional factor of
942
            "decay". */
943
69.5k
         extrapolation_offset = max_period-pitch_index;
944
         /* We need to extrapolate enough samples to cover a complete MDCT
945
            window (including overlap/2 samples on both sides). */
946
69.5k
         extrapolation_len = N+overlap;
947
         /* We also apply fading if this is not the first loss. */
948
69.5k
         attenuation = MULT16_16_Q15(fade, decay);
949
36.6M
         for (i=j=0;i<extrapolation_len;i++,j++)
950
36.5M
         {
951
36.5M
            opus_val16 tmp;
952
36.5M
            if (j >= pitch_index) {
953
146k
               j -= pitch_index;
954
146k
               attenuation = MULT16_16_Q15(attenuation, decay);
955
146k
            }
956
36.5M
            buf[decode_buffer_size-N+i] =
957
36.5M
                  SHL32(EXTEND32(MULT16_16_Q15(attenuation,
958
36.5M
                        exc[extrapolation_offset+j])), SIG_SHIFT);
959
            /* Compute the energy of the previously decoded signal whose
960
               excitation we're copying. */
961
36.5M
            tmp = SROUND16(
962
36.5M
                  buf[decode_buffer_size-max_period-N+extrapolation_offset+j],
963
36.5M
                  SIG_SHIFT);
964
36.5M
            S1 += SHR32(MULT16_16(tmp, tmp), 11);
965
36.5M
         }
966
69.5k
         {
967
69.5k
            opus_val16 lpc_mem[CELT_LPC_ORDER];
968
            /* Copy the last decoded samples (prior to the overlap region) to
969
               synthesis filter memory so we can have a continuous signal. */
970
1.73M
            for (i=0;i<CELT_LPC_ORDER;i++)
971
1.66M
               lpc_mem[i] = SROUND16(buf[decode_buffer_size-N-1-i], SIG_SHIFT);
972
            /* Apply the synthesis filter to convert the excitation back into
973
               the signal domain. */
974
69.5k
            celt_iir(buf+decode_buffer_size-N, lpc+c*CELT_LPC_ORDER,
975
69.5k
                  buf+decode_buffer_size-N, extrapolation_len, CELT_LPC_ORDER,
976
69.5k
                  lpc_mem, st->arch);
977
#ifdef FIXED_POINT
978
            for (i=0; i < extrapolation_len; i++)
979
               buf[decode_buffer_size-N+i] = SATURATE(buf[decode_buffer_size-N+i], SIG_SAT);
980
#endif
981
69.5k
         }
982
983
         /* Check if the synthesis energy is higher than expected, which can
984
            happen with the signal changes during our window. If so,
985
            attenuate. */
986
69.5k
         {
987
69.5k
            opus_val32 S2=0;
988
36.6M
            for (i=0;i<extrapolation_len;i++)
989
36.5M
            {
990
36.5M
               opus_val16 tmp = SROUND16(buf[decode_buffer_size-N+i], SIG_SHIFT);
991
36.5M
               S2 += SHR32(MULT16_16(tmp, tmp), 11);
992
36.5M
            }
993
            /* This checks for an "explosion" in the synthesis. */
994
#ifdef FIXED_POINT
995
            if (!(S1 > SHR32(S2,2)))
996
#else
997
            /* The float test is written this way to catch NaNs in the output
998
               of the IIR filter at the same time. */
999
69.5k
            if (!(S1 > 0.2f*S2))
1000
8.06k
#endif
1001
8.06k
            {
1002
2.83M
               for (i=0;i<extrapolation_len;i++)
1003
2.82M
                  buf[decode_buffer_size-N+i] = 0;
1004
61.4k
            } else if (S1 < S2)
1005
11.8k
            {
1006
11.8k
               opus_val16 ratio = celt_sqrt(frac_div32(SHR32(S1,1)+1,S2+1));
1007
1.43M
               for (i=0;i<overlap;i++)
1008
1.42M
               {
1009
1.42M
                  opus_val16 tmp_g = Q15ONE
1010
1.42M
                        - MULT16_16_Q15(COEF2VAL16(window[i]), Q15ONE-ratio);
1011
1.42M
                  buf[decode_buffer_size-N+i] =
1012
1.42M
                        MULT16_32_Q15(tmp_g, buf[decode_buffer_size-N+i]);
1013
1.42M
               }
1014
5.48M
               for (i=overlap;i<extrapolation_len;i++)
1015
5.47M
               {
1016
5.47M
                  buf[decode_buffer_size-N+i] =
1017
5.47M
                        MULT16_32_Q15(ratio, buf[decode_buffer_size-N+i]);
1018
5.47M
               }
1019
11.8k
            }
1020
69.5k
         }
1021
1022
69.5k
      } while (++c<C);
1023
1024
#ifdef ENABLE_DEEP_PLC
1025
      if (curr_neural) {
1026
         float overlap_mem;
1027
         int samples_needed16k;
1028
         celt_sig *buf;
1029
         VARDECL(float, buf_copy);
1030
         buf = decode_mem[0];
1031
         ALLOC(buf_copy, C*overlap, float);
1032
         c=0; do {
1033
            OPUS_COPY(buf_copy+c*overlap, &decode_mem[c][decode_buffer_size-N], overlap);
1034
         } while (++c<C);
1035
1036
         /* Need enough samples from the PLC to cover the frame size, resampling delay,
1037
            and the overlap at the end. */
1038
         samples_needed16k = (N+SINC_ORDER+overlap)/3;
1039
         if (!last_neural) {
1040
            st->plc_fill = 0;
1041
         }
1042
         while (st->plc_fill < samples_needed16k) {
1043
            lpcnet_plc_conceal(lpcnet, &st->plc_pcm[st->plc_fill]);
1044
            st->plc_fill += FRAME_SIZE;
1045
         }
1046
         /* Resample to 48 kHz. */
1047
         for (i=0;i<(N+overlap)/3;i++) {
1048
            int j;
1049
            float sum;
1050
            for (sum=0, j=0;j<17;j++) sum += 3*st->plc_pcm[i+j]*sinc_filter[3*j];
1051
            buf[decode_buffer_size-N+3*i] = sum;
1052
            for (sum=0, j=0;j<16;j++) sum += 3*st->plc_pcm[i+j+1]*sinc_filter[3*j+2];
1053
            buf[decode_buffer_size-N+3*i+1] = sum;
1054
            for (sum=0, j=0;j<16;j++) sum += 3*st->plc_pcm[i+j+1]*sinc_filter[3*j+1];
1055
            buf[decode_buffer_size-N+3*i+2] = sum;
1056
         }
1057
         OPUS_MOVE(st->plc_pcm, &st->plc_pcm[N/3], st->plc_fill-N/3);
1058
         st->plc_fill -= N/3;
1059
         for (i=0;i<N;i++) {
1060
            float tmp = buf[decode_buffer_size-N+i];
1061
            buf[decode_buffer_size-N+i] -= PREEMPHASIS*st->plc_preemphasis_mem;
1062
            st->plc_preemphasis_mem = tmp;
1063
         }
1064
         overlap_mem = st->plc_preemphasis_mem;
1065
         for (i=0;i<overlap;i++) {
1066
            float tmp = buf[decode_buffer_size+i];
1067
            buf[decode_buffer_size+i] -= PREEMPHASIS*overlap_mem;
1068
            overlap_mem = tmp;
1069
         }
1070
         /* For now, we just do mono PLC. */
1071
         if (C==2) OPUS_COPY(decode_mem[1], decode_mem[0], decode_buffer_size+overlap);
1072
         c=0; do {
1073
            /* Cross-fade with 48-kHz non-neural PLC for the first 2.5 ms to avoid a discontinuity. */
1074
            if (!last_neural) {
1075
               for (i=0;i<overlap;i++) decode_mem[c][decode_buffer_size-N+i] = (1-window[i])*buf_copy[c*overlap+i] + (window[i])*decode_mem[c][decode_buffer_size-N+i];
1076
            }
1077
         } while (++c<C);
1078
      }
1079
#endif
1080
37.7k
      st->prefilter_and_fold = 1;
1081
37.7k
   }
1082
1083
   /* Saturate to something large to avoid wrap-around. */
1084
118k
   st->loss_duration = IMIN(10000, loss_duration+(1<<LM));
1085
118k
   st->plc_duration = IMIN(10000, st->plc_duration+(1<<LM));
1086
#ifdef ENABLE_DRED
1087
   if (curr_frame_type == FRAME_DRED) {
1088
      st->plc_duration = 0;
1089
      st->skip_plc = 0;
1090
   }
1091
#endif
1092
118k
   st->last_frame_type = curr_frame_type;
1093
118k
   RESTORE_STACK;
1094
118k
}
1095
1096
#ifdef ENABLE_QEXT
1097
static void decode_qext_stereo_params(ec_dec *ec, int qext_end, int *qext_intensity, int *qext_dual_stereo) {
1098
   *qext_intensity = ec_dec_uint(ec, qext_end+1);
1099
   if (*qext_intensity != 0) *qext_dual_stereo = ec_dec_bit_logp(ec, 1);
1100
   else *qext_dual_stereo = 0;
1101
}
1102
#endif
1103
1104
int celt_decode_with_ec_dred(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data,
1105
      int len, opus_res * OPUS_RESTRICT pcm, int frame_size, ec_dec *dec, int accum
1106
#ifdef ENABLE_DEEP_PLC
1107
      ,LPCNetPLCState *lpcnet
1108
#endif
1109
      ARG_QEXT(const unsigned char *qext_payload) ARG_QEXT(int qext_payload_len)
1110
      )
1111
203k
{
1112
203k
   int c, i, N;
1113
203k
   int spread_decision;
1114
203k
   opus_int32 bits;
1115
203k
   ec_dec _dec;
1116
203k
   VARDECL(celt_norm, X);
1117
203k
   VARDECL(int, fine_quant);
1118
203k
   VARDECL(int, pulses);
1119
203k
   VARDECL(int, cap);
1120
203k
   VARDECL(int, offsets);
1121
203k
   VARDECL(int, fine_priority);
1122
203k
   VARDECL(int, tf_res);
1123
203k
   VARDECL(unsigned char, collapse_masks);
1124
203k
   celt_sig *decode_mem[2];
1125
203k
   celt_sig *out_syn[2];
1126
203k
   celt_glog *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
1127
1128
203k
   int shortBlocks;
1129
203k
   int isTransient;
1130
203k
   int intra_ener;
1131
203k
   const int CC = st->channels;
1132
203k
   int LM, M;
1133
203k
   int start;
1134
203k
   int end;
1135
203k
   int effEnd;
1136
203k
   int codedBands;
1137
203k
   int alloc_trim;
1138
203k
   int postfilter_pitch;
1139
203k
   opus_val16 postfilter_gain;
1140
203k
   int intensity=0;
1141
203k
   int dual_stereo=0;
1142
203k
   opus_int32 total_bits;
1143
203k
   opus_int32 balance;
1144
203k
   opus_int32 tell;
1145
203k
   int dynalloc_logp;
1146
203k
   int postfilter_tapset;
1147
203k
   int anti_collapse_rsv;
1148
203k
   int anti_collapse_on=0;
1149
203k
   int silence;
1150
203k
   int C = st->stream_channels;
1151
203k
   const OpusCustomMode *mode;
1152
203k
   int nbEBands;
1153
203k
   int overlap;
1154
203k
   const opus_int16 *eBands;
1155
203k
   celt_glog max_background_increase;
1156
203k
   int decode_buffer_size;
1157
#ifdef ENABLE_QEXT
1158
   opus_int32 qext_bits;
1159
   ec_dec ext_dec;
1160
   int qext_bytes=0;
1161
   int qext_end=0;
1162
   int qext_intensity=0;
1163
   int qext_dual_stereo=0;
1164
   VARDECL(int, extra_quant);
1165
   VARDECL(int, extra_pulses);
1166
   const CELTMode *qext_mode = NULL;
1167
   CELTMode qext_mode_struct;
1168
   int qext_scale;
1169
#else
1170
203k
# define qext_bytes 0
1171
203k
#endif
1172
203k
   ALLOC_STACK;
1173
#ifdef ENABLE_QEXT
1174
   qext_scale = st->qext_scale;
1175
#endif
1176
203k
   decode_buffer_size = QEXT_SCALE(DECODE_BUFFER_SIZE);
1177
1178
203k
   VALIDATE_CELT_DECODER(st);
1179
203k
   mode = st->mode;
1180
203k
   nbEBands = mode->nbEBands;
1181
203k
   overlap = mode->overlap;
1182
203k
   eBands = mode->eBands;
1183
203k
   start = st->start;
1184
203k
   end = st->end;
1185
203k
   frame_size *= st->downsample;
1186
1187
203k
   oldBandE = (celt_glog*)(st->_decode_mem+(decode_buffer_size+overlap)*CC);
1188
203k
   oldLogE = oldBandE + 2*nbEBands;
1189
203k
   oldLogE2 = oldLogE + 2*nbEBands;
1190
203k
   backgroundLogE = oldLogE2 + 2*nbEBands;
1191
1192
#ifdef ENABLE_QEXT
1193
   if (qext_payload) {
1194
      ec_dec_init(&ext_dec, (unsigned char*)qext_payload, qext_payload_len);
1195
      qext_bytes = qext_payload_len;
1196
   } else {
1197
      ec_dec_init(&ext_dec, NULL, 0);
1198
   }
1199
#endif
1200
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
1201
   if (st->signalling && data!=NULL)
1202
   {
1203
      int data0=data[0];
1204
      /* Convert "standard mode" to Opus header */
1205
# ifndef ENABLE_QEXT
1206
      if (mode->Fs==48000 && mode->shortMdctSize==120)
1207
# endif
1208
      {
1209
         data0 = fromOpus(data0);
1210
         if (data0<0)
1211
            return OPUS_INVALID_PACKET;
1212
      }
1213
      st->end = end = IMAX(1, mode->effEBands-2*(data0>>5));
1214
      LM = (data0>>3)&0x3;
1215
      C = 1 + ((data0>>2)&0x1);
1216
      if ((data[0] & 0x03) == 0x03) {
1217
         data++;
1218
         len--;
1219
         if (len<=0)
1220
            return OPUS_INVALID_PACKET;
1221
         if (data[0] & 0x40) {
1222
            int p;
1223
            int padding=0;
1224
            data++;
1225
            len--;
1226
            do {
1227
               int tmp;
1228
               if (len<=0)
1229
                  return OPUS_INVALID_PACKET;
1230
               p = *data++;
1231
               len--;
1232
               tmp = p==255 ? 254: p;
1233
               len -= tmp;
1234
               padding += tmp;
1235
            } while (p==255);
1236
            padding--;
1237
            if (len <= 0 || padding<0) return OPUS_INVALID_PACKET;
1238
#ifdef ENABLE_QEXT
1239
            qext_bytes = padding;
1240
            if (data[len] != QEXT_EXTENSION_ID<<1)
1241
               qext_bytes=0;
1242
            ec_dec_init(&ext_dec, (unsigned char*)data+len+1, qext_bytes);
1243
#endif
1244
         }
1245
      } else
1246
      {
1247
         data++;
1248
         len--;
1249
      }
1250
      if (LM>mode->maxLM)
1251
         return OPUS_INVALID_PACKET;
1252
      if (frame_size < mode->shortMdctSize<<LM)
1253
         return OPUS_BUFFER_TOO_SMALL;
1254
      else
1255
         frame_size = mode->shortMdctSize<<LM;
1256
   } else {
1257
#else
1258
203k
   {
1259
203k
#endif
1260
560k
      for (LM=0;LM<=mode->maxLM;LM++)
1261
560k
         if (mode->shortMdctSize<<LM==frame_size)
1262
203k
            break;
1263
203k
      if (LM>mode->maxLM)
1264
0
         return OPUS_BAD_ARG;
1265
203k
   }
1266
203k
   M=1<<LM;
1267
1268
203k
   if (len<0 || len>1275 || pcm==NULL)
1269
0
      return OPUS_BAD_ARG;
1270
1271
203k
   N = M*mode->shortMdctSize;
1272
384k
   c=0; do {
1273
384k
      decode_mem[c] = st->_decode_mem + c*(decode_buffer_size+overlap);
1274
384k
      out_syn[c] = decode_mem[c]+decode_buffer_size-N;
1275
384k
   } while (++c<CC);
1276
1277
203k
   effEnd = end;
1278
203k
   if (effEnd > mode->effEBands)
1279
0
      effEnd = mode->effEBands;
1280
1281
203k
   if (data == NULL || len<=1)
1282
118k
   {
1283
118k
      celt_decode_lost(st, N, LM
1284
#ifdef ENABLE_DEEP_PLC
1285
      , lpcnet
1286
#endif
1287
118k
                      );
1288
118k
      deemphasis(out_syn, pcm, N, CC, st->downsample, mode->preemph, st->preemph_memD, accum);
1289
118k
      RESTORE_STACK;
1290
118k
      return frame_size/st->downsample;
1291
118k
   }
1292
#ifdef ENABLE_DEEP_PLC
1293
   else {
1294
      /* FIXME: This is a bit of a hack just to make sure opus_decode_native() knows we're no longer in PLC. */
1295
      if (lpcnet) lpcnet->blend = 0;
1296
   }
1297
#endif
1298
1299
   /* Check if there are at least two packets received consecutively before
1300
    * turning on the pitch-based PLC */
1301
85.3k
   if (st->loss_duration == 0) st->skip_plc = 0;
1302
1303
85.3k
   if (dec == NULL)
1304
14.9k
   {
1305
14.9k
      ec_dec_init(&_dec,(unsigned char*)data,len);
1306
14.9k
      dec = &_dec;
1307
14.9k
   }
1308
1309
85.3k
   if (C==1)
1310
58.2k
   {
1311
1.28M
      for (i=0;i<nbEBands;i++)
1312
1.22M
         oldBandE[i]=MAXG(oldBandE[i],oldBandE[nbEBands+i]);
1313
58.2k
   }
1314
1315
85.3k
   total_bits = len*8;
1316
85.3k
   tell = ec_tell(dec);
1317
1318
85.3k
   if (tell >= total_bits)
1319
20.1k
      silence = 1;
1320
65.2k
   else if (tell==1)
1321
59.8k
      silence = ec_dec_bit_logp(dec, 15);
1322
5.42k
   else
1323
5.42k
      silence = 0;
1324
85.3k
   if (silence)
1325
23.2k
   {
1326
      /* Pretend we've read all the remaining bits */
1327
23.2k
      tell = len*8;
1328
23.2k
      dec->nbits_total+=tell-ec_tell(dec);
1329
23.2k
   }
1330
1331
85.3k
   postfilter_gain = 0;
1332
85.3k
   postfilter_pitch = 0;
1333
85.3k
   postfilter_tapset = 0;
1334
85.3k
   if (start==0 && tell+16 <= total_bits)
1335
49.0k
   {
1336
49.0k
      if(ec_dec_bit_logp(dec, 1))
1337
13.1k
      {
1338
13.1k
         int qg, octave;
1339
13.1k
         octave = ec_dec_uint(dec, 6);
1340
13.1k
         postfilter_pitch = (16<<octave)+ec_dec_bits(dec, 4+octave)-1;
1341
13.1k
         qg = ec_dec_bits(dec, 3);
1342
13.1k
         if (ec_tell(dec)+2<=total_bits)
1343
13.1k
            postfilter_tapset = ec_dec_icdf(dec, tapset_icdf, 2);
1344
13.1k
         postfilter_gain = QCONST16(.09375f,15)*(qg+1);
1345
13.1k
      }
1346
49.0k
      tell = ec_tell(dec);
1347
49.0k
   }
1348
1349
85.3k
   if (LM > 0 && tell+3 <= total_bits)
1350
49.4k
   {
1351
49.4k
      isTransient = ec_dec_bit_logp(dec, 3);
1352
49.4k
      tell = ec_tell(dec);
1353
49.4k
   }
1354
35.9k
   else
1355
35.9k
      isTransient = 0;
1356
1357
85.3k
   if (isTransient)
1358
6.33k
      shortBlocks = M;
1359
79.0k
   else
1360
79.0k
      shortBlocks = 0;
1361
1362
   /* Decode the global flags (first symbols in the stream) */
1363
85.3k
   intra_ener = tell+3<=total_bits ? ec_dec_bit_logp(dec, 3) : 0;
1364
   /* If recovering from packet loss, make sure we make the energy prediction safe to reduce the
1365
      risk of getting loud artifacts. */
1366
85.3k
   if (!intra_ener && st->loss_duration != 0) {
1367
20.9k
      c=0; do
1368
41.9k
      {
1369
41.9k
         celt_glog safety = 0;
1370
41.9k
         int missing = IMIN(10, st->loss_duration>>LM);
1371
41.9k
         if (LM==0) safety = GCONST(1.5f);
1372
37.9k
         else if (LM==1) safety = GCONST(.5f);
1373
523k
         for (i=start;i<end;i++)
1374
482k
         {
1375
482k
            if (oldBandE[c*nbEBands+i] < MAXG(oldLogE[c*nbEBands+i], oldLogE2[c*nbEBands+i])) {
1376
               /* If energy is going down already, continue the trend. */
1377
160k
               opus_val32 slope;
1378
160k
               opus_val32 E0, E1, E2;
1379
160k
               E0 = oldBandE[c*nbEBands+i];
1380
160k
               E1 = oldLogE[c*nbEBands+i];
1381
160k
               E2 = oldLogE2[c*nbEBands+i];
1382
160k
               slope = MAX32(E1 - E0, HALF32(E2 - E0));
1383
160k
               slope = MING(slope, GCONST(2.f));
1384
160k
               E0 -= MAX32(0, (1+missing)*slope);
1385
160k
               oldBandE[c*nbEBands+i] = MAX32(-GCONST(20.f), E0);
1386
321k
            } else {
1387
               /* Otherwise take the min of the last frames. */
1388
321k
               oldBandE[c*nbEBands+i] = MING(MING(oldBandE[c*nbEBands+i], oldLogE[c*nbEBands+i]), oldLogE2[c*nbEBands+i]);
1389
321k
            }
1390
            /* Shorter frames have more natural fluctuations -- play it safe. */
1391
482k
            oldBandE[c*nbEBands+i] -= safety;
1392
482k
         }
1393
41.9k
      } while (++c<2);
1394
20.9k
   }
1395
   /* Get band energies */
1396
85.3k
   unquant_coarse_energy(mode, start, end, oldBandE,
1397
85.3k
         intra_ener, dec, C, LM);
1398
1399
85.3k
   ALLOC(tf_res, nbEBands, int);
1400
85.3k
   tf_decode(start, end, isTransient, tf_res, LM, dec);
1401
1402
85.3k
   tell = ec_tell(dec);
1403
85.3k
   spread_decision = SPREAD_NORMAL;
1404
85.3k
   if (tell+4 <= total_bits)
1405
46.1k
      spread_decision = ec_dec_icdf(dec, spread_icdf, 5);
1406
1407
85.3k
   ALLOC(cap, nbEBands, int);
1408
1409
85.3k
   init_caps(mode,cap,LM,C);
1410
1411
85.3k
   ALLOC(offsets, nbEBands, int);
1412
1413
85.3k
   dynalloc_logp = 6;
1414
85.3k
   total_bits<<=BITRES;
1415
85.3k
   tell = ec_tell_frac(dec);
1416
1.10M
   for (i=start;i<end;i++)
1417
1.01M
   {
1418
1.01M
      int width, quanta;
1419
1.01M
      int dynalloc_loop_logp;
1420
1.01M
      int boost;
1421
1.01M
      width = C*(eBands[i+1]-eBands[i])<<LM;
1422
      /* quanta is 6 bits, but no more than 1 bit/sample
1423
         and no less than 1/8 bit/sample */
1424
1.01M
      quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
1425
1.01M
      dynalloc_loop_logp = dynalloc_logp;
1426
1.01M
      boost = 0;
1427
1.04M
      while (tell+(dynalloc_loop_logp<<BITRES) < total_bits && boost < cap[i])
1428
643k
      {
1429
643k
         int flag;
1430
643k
         flag = ec_dec_bit_logp(dec, dynalloc_loop_logp);
1431
643k
         tell = ec_tell_frac(dec);
1432
643k
         if (!flag)
1433
618k
            break;
1434
25.0k
         boost += quanta;
1435
25.0k
         total_bits -= quanta;
1436
25.0k
         dynalloc_loop_logp = 1;
1437
25.0k
      }
1438
1.01M
      offsets[i] = boost;
1439
      /* Making dynalloc more likely */
1440
1.01M
      if (boost>0)
1441
10.9k
         dynalloc_logp = IMAX(2, dynalloc_logp-1);
1442
1.01M
   }
1443
1444
85.3k
   ALLOC(fine_quant, nbEBands, int);
1445
85.3k
   alloc_trim = tell+(6<<BITRES) <= total_bits ?
1446
43.4k
         ec_dec_icdf(dec, trim_icdf, 7) : 5;
1447
1448
85.3k
   bits = (((opus_int32)len*8)<<BITRES) - (opus_int32)ec_tell_frac(dec) - 1;
1449
85.3k
   anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
1450
85.3k
   bits -= anti_collapse_rsv;
1451
1452
85.3k
   ALLOC(pulses, nbEBands, int);
1453
85.3k
   ALLOC(fine_priority, nbEBands, int);
1454
1455
85.3k
   codedBands = clt_compute_allocation(mode, start, end, offsets, cap,
1456
85.3k
         alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
1457
85.3k
         fine_quant, fine_priority, C, LM, dec, 0, 0, 0);
1458
1459
85.3k
   unquant_fine_energy(mode, start, end, oldBandE, NULL, fine_quant, dec, C);
1460
1461
85.3k
   ALLOC(X, C*N, celt_norm);   /**< Interleaved normalised MDCTs */
1462
1463
#ifdef ENABLE_QEXT
1464
   if (qext_bytes && end == nbEBands &&
1465
         ((mode->Fs == 48000 && (mode->shortMdctSize==120 || mode->shortMdctSize==90))
1466
       || (mode->Fs == 96000 && (mode->shortMdctSize==240 || mode->shortMdctSize==180)))) {
1467
      int qext_intra_ener;
1468
      compute_qext_mode(&qext_mode_struct, mode);
1469
      qext_mode = &qext_mode_struct;
1470
      qext_end = ec_dec_bit_logp(&ext_dec, 1) ? NB_QEXT_BANDS : 2;
1471
      if (C==2) decode_qext_stereo_params(&ext_dec, qext_end, &qext_intensity, &qext_dual_stereo);
1472
      qext_intra_ener = ec_tell(&ext_dec)+3<=qext_bytes*8 ? ec_dec_bit_logp(&ext_dec, 3) : 0;
1473
      unquant_coarse_energy(qext_mode, 0, qext_end, st->qext_oldBandE,
1474
            qext_intra_ener, &ext_dec, C, LM);
1475
   }
1476
   ALLOC(extra_quant, nbEBands+NB_QEXT_BANDS, int);
1477
   ALLOC(extra_pulses, nbEBands+NB_QEXT_BANDS, int);
1478
   qext_bits = ((opus_int32)qext_bytes*8<<BITRES) - (opus_int32)ec_tell_frac(&ext_dec) - 1;
1479
   clt_compute_extra_allocation(mode, qext_mode, start, end, qext_end, NULL, NULL,
1480
         qext_bits, extra_pulses, extra_quant, C, LM, &ext_dec, 0, 0, 0);
1481
   if (qext_bytes > 0) {
1482
      unquant_fine_energy(mode, start, end, oldBandE, fine_quant, extra_quant, &ext_dec, C);
1483
   }
1484
#endif
1485
1486
162k
   c=0; do {
1487
162k
      OPUS_MOVE(decode_mem[c], decode_mem[c]+N, decode_buffer_size-N+overlap);
1488
162k
   } while (++c<CC);
1489
1490
   /* Decode fixed codebook */
1491
85.3k
   ALLOC(collapse_masks, C*nbEBands, unsigned char);
1492
1493
85.3k
   quant_all_bands(0, mode, start, end, X, C==2 ? X+N : NULL, collapse_masks,
1494
85.3k
         NULL, pulses, shortBlocks, spread_decision, dual_stereo, intensity, tf_res,
1495
85.3k
         len*(8<<BITRES)-anti_collapse_rsv, balance, dec, LM, codedBands, &st->rng, 0,
1496
85.3k
         st->arch, st->disable_inv
1497
85.3k
         ARG_QEXT(&ext_dec) ARG_QEXT(extra_pulses)
1498
85.3k
         ARG_QEXT(qext_bytes*(8<<BITRES)) ARG_QEXT(cap));
1499
1500
#ifdef ENABLE_QEXT
1501
   if (qext_mode) {
1502
      VARDECL(int, zeros);
1503
      VARDECL(unsigned char, qext_collapse_masks);
1504
      ec_dec dummy_dec;
1505
      int ext_balance;
1506
      ALLOC(zeros, nbEBands, int);
1507
      ALLOC(qext_collapse_masks, C*NB_QEXT_BANDS, unsigned char);
1508
      ec_dec_init(&dummy_dec, NULL, 0);
1509
      OPUS_CLEAR(zeros, end);
1510
      ext_balance = qext_bytes*(8<<BITRES) - ec_tell_frac(&ext_dec);
1511
      for (i=0;i<qext_end;i++) ext_balance -= extra_pulses[nbEBands+i] + C*(extra_quant[nbEBands+i]<<BITRES);
1512
      unquant_fine_energy(qext_mode, 0, qext_end, st->qext_oldBandE, NULL, &extra_quant[nbEBands], &ext_dec, C);
1513
      quant_all_bands(0, qext_mode, 0, qext_end, X, C==2 ? X+N : NULL, qext_collapse_masks,
1514
            NULL, &extra_pulses[nbEBands], shortBlocks, spread_decision, qext_dual_stereo, qext_intensity, zeros,
1515
            qext_bytes*(8<<BITRES), ext_balance, &ext_dec, LM, qext_end, &st->rng, 0,
1516
            st->arch, st->disable_inv, &dummy_dec, zeros, 0, NULL);
1517
   }
1518
#endif
1519
1520
85.3k
   if (anti_collapse_rsv > 0)
1521
3.95k
   {
1522
3.95k
      anti_collapse_on = ec_dec_bits(dec, 1);
1523
3.95k
   }
1524
85.3k
   unquant_energy_finalise(mode, start, end, (qext_bytes > 0) ? NULL : oldBandE,
1525
85.3k
         fine_quant, fine_priority, len*8-ec_tell(dec), dec, C);
1526
85.3k
   if (anti_collapse_on)
1527
2.13k
      anti_collapse(mode, X, collapse_masks, LM, C, N,
1528
2.13k
            start, end, oldBandE, oldLogE, oldLogE2, pulses, st->rng, 0, st->arch);
1529
1530
85.3k
   if (silence)
1531
23.2k
   {
1532
706k
      for (i=0;i<C*nbEBands;i++)
1533
682k
         oldBandE[i] = -GCONST(28.f);
1534
23.2k
   }
1535
85.3k
   if (st->prefilter_and_fold) {
1536
15.1k
      prefilter_and_fold(st, N);
1537
15.1k
   }
1538
85.3k
   celt_synthesis(mode, X, out_syn, oldBandE, start, effEnd,
1539
85.3k
                  C, CC, isTransient, LM, st->downsample, silence, st->arch ARG_QEXT(qext_mode) ARG_QEXT(st->qext_oldBandE) ARG_QEXT(qext_end));
1540
1541
162k
   c=0; do {
1542
162k
      st->postfilter_period=IMAX(st->postfilter_period, COMBFILTER_MINPERIOD);
1543
162k
      st->postfilter_period_old=IMAX(st->postfilter_period_old, COMBFILTER_MINPERIOD);
1544
162k
      comb_filter(out_syn[c], out_syn[c], st->postfilter_period_old, st->postfilter_period, mode->shortMdctSize,
1545
162k
            st->postfilter_gain_old, st->postfilter_gain, st->postfilter_tapset_old, st->postfilter_tapset,
1546
162k
            mode->window, overlap, st->arch);
1547
162k
      if (LM!=0)
1548
135k
         comb_filter(out_syn[c]+mode->shortMdctSize, out_syn[c]+mode->shortMdctSize, st->postfilter_period, postfilter_pitch, N-mode->shortMdctSize,
1549
135k
               st->postfilter_gain, postfilter_gain, st->postfilter_tapset, postfilter_tapset,
1550
135k
               mode->window, overlap, st->arch);
1551
1552
162k
   } while (++c<CC);
1553
85.3k
   st->postfilter_period_old = st->postfilter_period;
1554
85.3k
   st->postfilter_gain_old = st->postfilter_gain;
1555
85.3k
   st->postfilter_tapset_old = st->postfilter_tapset;
1556
85.3k
   st->postfilter_period = postfilter_pitch;
1557
85.3k
   st->postfilter_gain = postfilter_gain;
1558
85.3k
   st->postfilter_tapset = postfilter_tapset;
1559
85.3k
   if (LM!=0)
1560
70.7k
   {
1561
70.7k
      st->postfilter_period_old = st->postfilter_period;
1562
70.7k
      st->postfilter_gain_old = st->postfilter_gain;
1563
70.7k
      st->postfilter_tapset_old = st->postfilter_tapset;
1564
70.7k
   }
1565
1566
85.3k
   if (C==1)
1567
58.2k
      OPUS_COPY(&oldBandE[nbEBands], oldBandE, nbEBands);
1568
1569
85.3k
   if (!isTransient)
1570
79.0k
   {
1571
79.0k
      OPUS_COPY(oldLogE2, oldLogE, 2*nbEBands);
1572
79.0k
      OPUS_COPY(oldLogE, oldBandE, 2*nbEBands);
1573
79.0k
   } else {
1574
272k
      for (i=0;i<2*nbEBands;i++)
1575
265k
         oldLogE[i] = MING(oldLogE[i], oldBandE[i]);
1576
6.33k
   }
1577
   /* In normal circumstances, we only allow the noise floor to increase by
1578
      up to 2.4 dB/second, but when we're in DTX we give the weight of
1579
      all missing packets to the update packet. */
1580
85.3k
   max_background_increase = IMIN(160, st->loss_duration+M)*GCONST(0.001f);
1581
3.67M
   for (i=0;i<2*nbEBands;i++)
1582
3.58M
      backgroundLogE[i] = MING(backgroundLogE[i] + max_background_increase, oldBandE[i]);
1583
   /* In case start or end were to change */
1584
85.3k
   c=0; do
1585
170k
   {
1586
1.04M
      for (i=0;i<start;i++)
1587
869k
      {
1588
869k
         oldBandE[c*nbEBands+i]=0;
1589
869k
         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-GCONST(28.f);
1590
869k
      }
1591
852k
      for (i=end;i<nbEBands;i++)
1592
681k
      {
1593
681k
         oldBandE[c*nbEBands+i]=0;
1594
681k
         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-GCONST(28.f);
1595
681k
      }
1596
170k
   } while (++c<2);
1597
85.3k
   st->rng = dec->rng;
1598
#ifdef ENABLE_QEXT
1599
   if (qext_bytes) st->rng = st->rng ^ ext_dec.rng;
1600
#endif
1601
1602
85.3k
   deemphasis(out_syn, pcm, N, CC, st->downsample, mode->preemph, st->preemph_memD, accum);
1603
85.3k
   st->loss_duration = 0;
1604
85.3k
   st->plc_duration = 0;
1605
85.3k
   st->last_frame_type = FRAME_NORMAL;
1606
85.3k
   st->prefilter_and_fold = 0;
1607
85.3k
   RESTORE_STACK;
1608
85.3k
   if (ec_tell(dec) > 8*len)
1609
0
      return OPUS_INTERNAL_ERROR;
1610
#ifdef ENABLE_QEXT
1611
   if (qext_bytes != 0 && ec_tell(&ext_dec) > 8*qext_bytes)
1612
      return OPUS_INTERNAL_ERROR;
1613
#endif
1614
85.3k
   if(ec_get_error(dec))
1615
551
      st->error = 1;
1616
85.3k
   return frame_size/st->downsample;
1617
85.3k
}
1618
1619
int celt_decode_with_ec(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data,
1620
      int len, opus_res * OPUS_RESTRICT pcm, int frame_size, ec_dec *dec, int accum)
1621
14.9k
{
1622
14.9k
   return celt_decode_with_ec_dred(st, data, len, pcm, frame_size, dec, accum
1623
#ifdef ENABLE_DEEP_PLC
1624
       , NULL
1625
#endif
1626
14.9k
       ARG_QEXT(NULL) ARG_QEXT(0)
1627
14.9k
       );
1628
14.9k
}
1629
1630
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
1631
1632
#if defined(FIXED_POINT) && !defined(ENABLE_RES24)
1633
int opus_custom_decode(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int16 * OPUS_RESTRICT pcm, int frame_size)
1634
{
1635
   return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL, 0);
1636
}
1637
#else
1638
int opus_custom_decode(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int16 * OPUS_RESTRICT pcm, int frame_size)
1639
{
1640
   int j, ret, C, N;
1641
   VARDECL(opus_res, out);
1642
   ALLOC_STACK;
1643
1644
   if (pcm==NULL)
1645
      return OPUS_BAD_ARG;
1646
1647
   C = st->channels;
1648
   N = frame_size;
1649
1650
   ALLOC(out, C*N, opus_res);
1651
   ret = celt_decode_with_ec(st, data, len, out, frame_size, NULL, 0);
1652
   if (ret>0)
1653
      for (j=0;j<C*ret;j++)
1654
         pcm[j]=RES2INT16(out[j]);
1655
1656
   RESTORE_STACK;
1657
   return ret;
1658
}
1659
#endif
1660
1661
#if defined(FIXED_POINT) && defined(ENABLE_RES24)
1662
int opus_custom_decode24(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int32 * OPUS_RESTRICT pcm, int frame_size)
1663
{
1664
   return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL, 0);
1665
}
1666
#else
1667
int opus_custom_decode24(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int32 * OPUS_RESTRICT pcm, int frame_size)
1668
{
1669
   int j, ret, C, N;
1670
   VARDECL(opus_res, out);
1671
   ALLOC_STACK;
1672
1673
   if (pcm==NULL)
1674
      return OPUS_BAD_ARG;
1675
1676
   C = st->channels;
1677
   N = frame_size;
1678
1679
   ALLOC(out, C*N, opus_res);
1680
   ret = celt_decode_with_ec(st, data, len, out, frame_size, NULL, 0);
1681
   if (ret>0)
1682
      for (j=0;j<C*ret;j++)
1683
         pcm[j]=RES2INT24(out[j]);
1684
1685
   RESTORE_STACK;
1686
   return ret;
1687
}
1688
#endif
1689
1690
1691
#ifndef DISABLE_FLOAT_API
1692
1693
# if !defined(FIXED_POINT)
1694
int opus_custom_decode_float(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, float * OPUS_RESTRICT pcm, int frame_size)
1695
{
1696
   return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL, 0);
1697
}
1698
# else
1699
int opus_custom_decode_float(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, float * OPUS_RESTRICT pcm, int frame_size)
1700
{
1701
   int j, ret, C, N;
1702
   VARDECL(opus_res, out);
1703
   ALLOC_STACK;
1704
1705
   if (pcm==NULL)
1706
      return OPUS_BAD_ARG;
1707
1708
   C = st->channels;
1709
   N = frame_size;
1710
1711
   ALLOC(out, C*N, opus_res);
1712
   ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL, 0);
1713
   if (ret>0)
1714
      for (j=0;j<C*ret;j++)
1715
         pcm[j]=RES2FLOAT(out[j]);
1716
1717
   RESTORE_STACK;
1718
   return ret;
1719
}
1720
# endif
1721
1722
#endif
1723
1724
#endif /* CUSTOM_MODES */
1725
1726
int opus_custom_decoder_ctl(CELTDecoder * OPUS_RESTRICT st, int request, ...)
1727
2.80M
{
1728
2.80M
   va_list ap;
1729
1730
2.80M
   va_start(ap, request);
1731
2.80M
   switch (request)
1732
2.80M
   {
1733
0
      case OPUS_SET_COMPLEXITY_REQUEST:
1734
0
      {
1735
0
          opus_int32 value = va_arg(ap, opus_int32);
1736
0
          if(value<0 || value>10)
1737
0
          {
1738
0
             goto bad_arg;
1739
0
          }
1740
0
          st->complexity = value;
1741
0
      }
1742
0
      break;
1743
0
      case OPUS_GET_COMPLEXITY_REQUEST:
1744
0
      {
1745
0
          opus_int32 *value = va_arg(ap, opus_int32*);
1746
0
          if (!value)
1747
0
          {
1748
0
             goto bad_arg;
1749
0
          }
1750
0
          *value = st->complexity;
1751
0
      }
1752
0
      break;
1753
326k
      case CELT_SET_START_BAND_REQUEST:
1754
326k
      {
1755
326k
         opus_int32 value = va_arg(ap, opus_int32);
1756
326k
         if (value<0 || value>=st->mode->nbEBands)
1757
0
            goto bad_arg;
1758
326k
         st->start = value;
1759
326k
      }
1760
0
      break;
1761
120k
      case CELT_SET_END_BAND_REQUEST:
1762
120k
      {
1763
120k
         opus_int32 value = va_arg(ap, opus_int32);
1764
120k
         if (value<1 || value>st->mode->nbEBands)
1765
0
            goto bad_arg;
1766
120k
         st->end = value;
1767
120k
      }
1768
0
      break;
1769
311k
      case CELT_SET_CHANNELS_REQUEST:
1770
311k
      {
1771
311k
         opus_int32 value = va_arg(ap, opus_int32);
1772
311k
         if (value<1 || value>2)
1773
0
            goto bad_arg;
1774
311k
         st->stream_channels = value;
1775
311k
      }
1776
0
      break;
1777
0
      case CELT_GET_AND_CLEAR_ERROR_REQUEST:
1778
0
      {
1779
0
         opus_int32 *value = va_arg(ap, opus_int32*);
1780
0
         if (value==NULL)
1781
0
            goto bad_arg;
1782
0
         *value=st->error;
1783
0
         st->error = 0;
1784
0
      }
1785
0
      break;
1786
0
      case OPUS_GET_LOOKAHEAD_REQUEST:
1787
0
      {
1788
0
         opus_int32 *value = va_arg(ap, opus_int32*);
1789
0
         if (value==NULL)
1790
0
            goto bad_arg;
1791
0
         *value = st->overlap/st->downsample;
1792
0
      }
1793
0
      break;
1794
1.41M
      case OPUS_RESET_STATE:
1795
1.41M
      {
1796
1.41M
         int i;
1797
1.41M
         celt_glog *oldBandE, *oldLogE, *oldLogE2;
1798
1.41M
         int decode_buffer_size;
1799
#ifdef ENABLE_QEXT
1800
         int qext_scale = st->qext_scale;
1801
#endif
1802
1.41M
         decode_buffer_size = QEXT_SCALE(DECODE_BUFFER_SIZE);
1803
1.41M
         oldBandE = (celt_glog*)(st->_decode_mem+(decode_buffer_size+st->overlap)*st->channels);
1804
1.41M
         oldLogE = oldBandE + 2*st->mode->nbEBands;
1805
1.41M
         oldLogE2 = oldLogE + 2*st->mode->nbEBands;
1806
1.41M
         OPUS_CLEAR((char*)&st->DECODER_RESET_START,
1807
1.41M
               opus_custom_decoder_get_size(st->mode, st->channels)-
1808
1.41M
               ((char*)&st->DECODER_RESET_START - (char*)st));
1809
60.6M
         for (i=0;i<2*st->mode->nbEBands;i++)
1810
59.2M
            oldLogE[i]=oldLogE2[i]=-GCONST(28.f);
1811
1.41M
         st->skip_plc = 1;
1812
1.41M
         st->last_frame_type = FRAME_NONE;
1813
1.41M
      }
1814
1.41M
      break;
1815
0
      case OPUS_GET_PITCH_REQUEST:
1816
0
      {
1817
0
         opus_int32 *value = va_arg(ap, opus_int32*);
1818
0
         if (value==NULL)
1819
0
            goto bad_arg;
1820
0
         *value = st->postfilter_period;
1821
0
      }
1822
0
      break;
1823
311k
      case CELT_GET_MODE_REQUEST:
1824
311k
      {
1825
311k
         const CELTMode ** value = va_arg(ap, const CELTMode**);
1826
311k
         if (value==0)
1827
0
            goto bad_arg;
1828
311k
         *value=st->mode;
1829
311k
      }
1830
0
      break;
1831
60.4k
      case CELT_SET_SIGNALLING_REQUEST:
1832
60.4k
      {
1833
60.4k
         opus_int32 value = va_arg(ap, opus_int32);
1834
60.4k
         st->signalling = value;
1835
60.4k
      }
1836
60.4k
      break;
1837
202k
      case OPUS_GET_FINAL_RANGE_REQUEST:
1838
202k
      {
1839
202k
         opus_uint32 * value = va_arg(ap, opus_uint32 *);
1840
202k
         if (value==0)
1841
0
            goto bad_arg;
1842
202k
         *value=st->rng;
1843
202k
      }
1844
0
      break;
1845
60.4k
      case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST:
1846
60.4k
      {
1847
60.4k
          opus_int32 value = va_arg(ap, opus_int32);
1848
60.4k
          if(value<0 || value>1)
1849
0
          {
1850
0
             goto bad_arg;
1851
0
          }
1852
60.4k
          st->disable_inv = value;
1853
60.4k
      }
1854
0
      break;
1855
0
      case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST:
1856
0
      {
1857
0
          opus_int32 *value = va_arg(ap, opus_int32*);
1858
0
          if (!value)
1859
0
          {
1860
0
             goto bad_arg;
1861
0
          }
1862
0
          *value = st->disable_inv;
1863
0
      }
1864
0
      break;
1865
0
      default:
1866
0
         goto bad_request;
1867
2.80M
   }
1868
2.80M
   va_end(ap);
1869
2.80M
   return OPUS_OK;
1870
0
bad_arg:
1871
0
   va_end(ap);
1872
0
   return OPUS_BAD_ARG;
1873
0
bad_request:
1874
0
      va_end(ap);
1875
0
  return OPUS_UNIMPLEMENTED;
1876
2.80M
}