Coverage Report

Created: 2025-11-16 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opus/celt/celt_encoder.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_ENCODER_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
55
#ifndef M_PI
56
#define M_PI 3.141592653
57
#endif
58
59
60
/** Encoder state
61
 @brief Encoder state
62
 */
63
struct OpusCustomEncoder {
64
   const OpusCustomMode *mode;     /**< Mode used by the encoder */
65
   int channels;
66
   int stream_channels;
67
68
   int force_intra;
69
   int clip;
70
   int disable_pf;
71
   int complexity;
72
   int upsample;
73
   int start, end;
74
75
   opus_int32 bitrate;
76
   int vbr;
77
   int signalling;
78
   int constrained_vbr;      /* If zero, VBR can do whatever it likes with the rate */
79
   int loss_rate;
80
   int lsb_depth;
81
   int lfe;
82
   int disable_inv;
83
   int arch;
84
#ifdef ENABLE_QEXT
85
   int enable_qext;
86
   int qext_scale;
87
#endif
88
89
   /* Everything beyond this point gets cleared on a reset */
90
#define ENCODER_RESET_START rng
91
92
   opus_uint32 rng;
93
   int spread_decision;
94
   opus_val32 delayedIntra;
95
   int tonal_average;
96
   int lastCodedBands;
97
   int hf_average;
98
   int tapset_decision;
99
100
   int prefilter_period;
101
   opus_val16 prefilter_gain;
102
   int prefilter_tapset;
103
#ifdef RESYNTH
104
   int prefilter_period_old;
105
   opus_val16 prefilter_gain_old;
106
   int prefilter_tapset_old;
107
#endif
108
   int consec_transient;
109
   AnalysisInfo analysis;
110
   SILKInfo silk_info;
111
112
   opus_val32 preemph_memE[2];
113
   opus_val32 preemph_memD[2];
114
115
   /* VBR-related parameters */
116
   opus_int32 vbr_reservoir;
117
   opus_int32 vbr_drift;
118
   opus_int32 vbr_offset;
119
   opus_int32 vbr_count;
120
   opus_val32 overlap_max;
121
   opus_val16 stereo_saving;
122
   int intensity;
123
   celt_glog *energy_mask;
124
   celt_glog spec_avg;
125
126
#ifdef RESYNTH
127
#ifdef ENABLE_QEXT
128
   /* +MAX_PERIOD/2 to make space for overlap */
129
   celt_sig syn_mem[2][2*DEC_PITCH_BUF_SIZE+MAX_PERIOD];
130
#else
131
   /* +MAX_PERIOD/2 to make space for overlap */
132
   celt_sig syn_mem[2][DEC_PITCH_BUF_SIZE+MAX_PERIOD/2];
133
#endif
134
#endif
135
136
   celt_sig in_mem[1]; /* Size = channels*mode->overlap */
137
   /* celt_sig prefilter_mem[],  Size = channels*COMBFILTER_MAXPERIOD */
138
   /* celt_glog oldBandE[],     Size = channels*mode->nbEBands */
139
   /* celt_glog oldLogE[],      Size = channels*mode->nbEBands */
140
   /* celt_glog oldLogE2[],     Size = channels*mode->nbEBands */
141
   /* celt_glog energyError[],  Size = channels*mode->nbEBands */
142
};
143
144
int celt_encoder_get_size(int channels)
145
0
{
146
#ifdef ENABLE_QEXT
147
   CELTMode *mode = opus_custom_mode_create(96000, 1920, NULL);
148
#else
149
0
   CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
150
0
#endif
151
0
   return opus_custom_encoder_get_size(mode, channels);
152
0
}
153
154
OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_get_size(const CELTMode *mode, int channels)
155
0
{
156
0
   int extra=0;
157
0
   int size;
158
#ifdef ENABLE_QEXT
159
   int qext_scale;
160
   extra = channels*NB_QEXT_BANDS*sizeof(celt_glog);
161
   if (mode->Fs == 96000 && (mode->shortMdctSize==240 || mode->shortMdctSize==180)) {
162
      qext_scale = 2;
163
   } else qext_scale = 1;
164
#endif
165
0
   size = sizeof(struct CELTEncoder)
166
0
         + (channels*mode->overlap-1)*sizeof(celt_sig)    /* celt_sig in_mem[channels*mode->overlap]; */
167
0
         + channels*QEXT_SCALE(COMBFILTER_MAXPERIOD)*sizeof(celt_sig) /* celt_sig prefilter_mem[channels*COMBFILTER_MAXPERIOD]; */
168
0
         + 4*channels*mode->nbEBands*sizeof(celt_glog)    /* celt_glog oldBandE[channels*mode->nbEBands]; */
169
                                                          /* celt_glog oldLogE[channels*mode->nbEBands]; */
170
                                                          /* celt_glog oldLogE2[channels*mode->nbEBands]; */
171
                                                          /* celt_glog energyError[channels*mode->nbEBands]; */
172
0
         + extra;
173
0
   return size;
174
0
}
175
176
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
177
CELTEncoder *opus_custom_encoder_create(const CELTMode *mode, int channels, int *error)
178
{
179
   int ret;
180
   CELTEncoder *st = (CELTEncoder *)opus_alloc(opus_custom_encoder_get_size(mode, channels));
181
   /* init will handle the NULL case */
182
   ret = opus_custom_encoder_init(st, mode, channels);
183
   if (ret != OPUS_OK)
184
   {
185
      opus_custom_encoder_destroy(st);
186
      st = NULL;
187
   }
188
   if (error)
189
      *error = ret;
190
   return st;
191
}
192
#endif /* CUSTOM_MODES */
193
194
static int opus_custom_encoder_init_arch(CELTEncoder *st, const CELTMode *mode,
195
                                         int channels, int arch)
196
0
{
197
0
   if (channels < 0 || channels > 2)
198
0
      return OPUS_BAD_ARG;
199
200
0
   if (st==NULL || mode==NULL)
201
0
      return OPUS_ALLOC_FAIL;
202
203
0
   OPUS_CLEAR((char*)st, opus_custom_encoder_get_size(mode, channels));
204
205
0
   st->mode = mode;
206
0
   st->stream_channels = st->channels = channels;
207
208
0
   st->upsample = 1;
209
0
   st->start = 0;
210
0
   st->end = st->mode->effEBands;
211
0
   st->signalling = 1;
212
0
   st->arch = arch;
213
214
0
   st->constrained_vbr = 1;
215
0
   st->clip = 1;
216
217
0
   st->bitrate = OPUS_BITRATE_MAX;
218
0
   st->vbr = 0;
219
0
   st->force_intra  = 0;
220
0
   st->complexity = 5;
221
0
   st->lsb_depth=24;
222
223
#ifdef ENABLE_QEXT
224
   if (st->mode->Fs == 96000 && (mode->shortMdctSize==240 || mode->shortMdctSize==180)) st->qext_scale = 2;
225
   else st->qext_scale = 1;
226
#endif
227
228
0
   opus_custom_encoder_ctl(st, OPUS_RESET_STATE);
229
230
0
   return OPUS_OK;
231
0
}
232
233
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
234
int opus_custom_encoder_init(CELTEncoder *st, const CELTMode *mode, int channels)
235
{
236
   return opus_custom_encoder_init_arch(st, mode, channels, opus_select_arch());
237
}
238
#endif
239
240
int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels,
241
                      int arch)
242
0
{
243
0
   int ret;
244
#ifdef ENABLE_QEXT
245
   if (sampling_rate==96000) {
246
      st->upsample = 1;
247
      return opus_custom_encoder_init_arch(st,
248
              opus_custom_mode_create(96000, 1920, NULL), channels, arch);
249
   }
250
#endif
251
0
   ret = opus_custom_encoder_init_arch(st,
252
0
           opus_custom_mode_create(48000, 960, NULL), channels, arch);
253
0
   if (ret != OPUS_OK)
254
0
      return ret;
255
0
   st->upsample = resampling_factor(sampling_rate);
256
0
   return OPUS_OK;
257
0
}
258
259
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
260
void opus_custom_encoder_destroy(CELTEncoder *st)
261
{
262
   opus_free(st);
263
}
264
#endif /* CUSTOM_MODES */
265
266
267
static int transient_analysis(const opus_val32 * OPUS_RESTRICT in, int len, int C,
268
                              opus_val16 *tf_estimate, int *tf_chan, int allow_weak_transients,
269
                              int *weak_transient, opus_val16 tone_freq, opus_val32 toneishness)
270
0
{
271
0
   int i;
272
0
   VARDECL(opus_val16, tmp);
273
0
   opus_val32 mem0,mem1;
274
0
   int is_transient = 0;
275
0
   opus_int32 mask_metric = 0;
276
0
   int c;
277
0
   opus_val16 tf_max;
278
0
   int len2;
279
   /* Forward masking: 6.7 dB/ms. */
280
#ifdef FIXED_POINT
281
   int forward_shift = 4;
282
#else
283
0
   opus_val16 forward_decay = QCONST16(.0625f,15);
284
0
#endif
285
   /* Table of 6*64/x, trained on real data to minimize the average error */
286
0
   static const unsigned char inv_table[128] = {
287
0
         255,255,156,110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25,
288
0
          23, 22, 21, 20, 19, 18, 17, 16, 16, 15, 15, 14, 13, 13, 12, 12,
289
0
          12, 12, 11, 11, 11, 10, 10, 10,  9,  9,  9,  9,  9,  9,  8,  8,
290
0
           8,  8,  8,  7,  7,  7,  7,  7,  7,  6,  6,  6,  6,  6,  6,  6,
291
0
           6,  6,  6,  6,  6,  6,  6,  6,  6,  5,  5,  5,  5,  5,  5,  5,
292
0
           5,  5,  5,  5,  5,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,
293
0
           4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  3,  3,
294
0
           3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  2,
295
0
   };
296
0
   SAVE_STACK;
297
#ifdef FIXED_POINT
298
   int in_shift = IMAX(0, celt_ilog2(1+celt_maxabs32(in, C*len))-14);
299
#endif
300
0
   ALLOC(tmp, len, opus_val16);
301
302
0
   *weak_transient = 0;
303
   /* For lower bitrates, let's be more conservative and have a forward masking
304
      decay of 3.3 dB/ms. This avoids having to code transients at very low
305
      bitrate (mostly for hybrid), which can result in unstable energy and/or
306
      partial collapse. */
307
0
   if (allow_weak_transients)
308
0
   {
309
#ifdef FIXED_POINT
310
      forward_shift = 5;
311
#else
312
0
      forward_decay = QCONST16(.03125f,15);
313
0
#endif
314
0
   }
315
0
   len2=len/2;
316
0
   for (c=0;c<C;c++)
317
0
   {
318
0
      opus_val32 mean;
319
0
      opus_int32 unmask=0;
320
0
      opus_val32 norm;
321
0
      opus_val16 maxE;
322
0
      mem0=0;
323
0
      mem1=0;
324
      /* High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) */
325
0
      for (i=0;i<len;i++)
326
0
      {
327
0
#ifndef FIXED_POINT
328
0
         float mem00;
329
0
#endif
330
0
         opus_val32 x,y;
331
0
         x = SHR32(in[i+c*len],in_shift);
332
0
         y = ADD32(mem0, x);
333
#ifdef FIXED_POINT
334
         mem0 = mem1 + y - SHL32(x,1);
335
         mem1 = x - SHR32(y,1);
336
#else
337
         /* Original code:
338
         mem0 = mem1 + y - 2*x;
339
         mem1 = x - .5f*y;
340
         Modified code to shorten dependency chains: */
341
0
         mem00=mem0;
342
0
         mem0 = mem0 - x + .5f*mem1;
343
0
         mem1 =  x - mem00;
344
0
#endif
345
0
         tmp[i] = SROUND16(y, 2);
346
         /*printf("%f ", tmp[i]);*/
347
0
      }
348
      /*printf("\n");*/
349
      /* First few samples are bad because we don't propagate the memory */
350
0
      OPUS_CLEAR(tmp, 12);
351
352
#ifdef FIXED_POINT
353
      /* Normalize tmp to max range */
354
      {
355
         int shift=0;
356
         shift = 14-celt_ilog2(MAX16(1, celt_maxabs16(tmp, len)));
357
         if (shift!=0)
358
         {
359
            for (i=0;i<len;i++)
360
               tmp[i] = SHL16(tmp[i], shift);
361
         }
362
      }
363
#endif
364
365
0
      mean=0;
366
0
      mem0=0;
367
      /* Grouping by two to reduce complexity */
368
      /* Forward pass to compute the post-echo threshold*/
369
0
      for (i=0;i<len2;i++)
370
0
      {
371
0
         opus_val32 x2 = PSHR32(MULT16_16(tmp[2*i],tmp[2*i]) + MULT16_16(tmp[2*i+1],tmp[2*i+1]),4);
372
0
         mean += PSHR32(x2, 12);
373
#ifdef FIXED_POINT
374
         /* FIXME: Use PSHR16() instead */
375
         mem0 = mem0 + PSHR32(x2-mem0,forward_shift);
376
         tmp[i] = PSHR32(mem0, 12);
377
#else
378
0
         mem0 = x2 + (1.f-forward_decay)*mem0;
379
0
         tmp[i] = forward_decay*mem0;
380
0
#endif
381
0
      }
382
383
0
      mem0=0;
384
0
      maxE=0;
385
      /* Backward pass to compute the pre-echo threshold */
386
0
      for (i=len2-1;i>=0;i--)
387
0
      {
388
         /* Backward masking: 13.9 dB/ms. */
389
#ifdef FIXED_POINT
390
         /* FIXME: Use PSHR16() instead */
391
         mem0 = mem0 + PSHR32(SHL32(tmp[i],4)-mem0,3);
392
         tmp[i] = PSHR32(mem0, 4);
393
         maxE = MAX16(maxE, tmp[i]);
394
#else
395
0
         mem0 = tmp[i] + 0.875f*mem0;
396
0
         tmp[i] = 0.125f*mem0;
397
0
         maxE = MAX16(maxE, 0.125f*mem0);
398
0
#endif
399
0
      }
400
      /*for (i=0;i<len2;i++)printf("%f ", tmp[i]/mean);printf("\n");*/
401
402
      /* Compute the ratio of the "frame energy" over the harmonic mean of the energy.
403
         This essentially corresponds to a bitrate-normalized temporal noise-to-mask
404
         ratio */
405
406
      /* As a compromise with the old transient detector, frame energy is the
407
         geometric mean of the energy and half the max */
408
#ifdef FIXED_POINT
409
      /* Costs two sqrt() to avoid overflows */
410
      mean = MULT16_16(celt_sqrt(mean), celt_sqrt(MULT16_16(maxE,len2>>1)));
411
#else
412
0
      mean = celt_sqrt(mean * maxE*.5*len2);
413
0
#endif
414
      /* Inverse of the mean energy in Q15+6 */
415
0
      norm = SHL32(EXTEND32(len2),6+14)/ADD32(EPSILON,SHR32(mean,1));
416
      /* Compute harmonic mean discarding the unreliable boundaries
417
         The data is smooth, so we only take 1/4th of the samples */
418
0
      unmask=0;
419
      /* We should never see NaNs here. If we find any, then something really bad happened and we better abort
420
         before it does any damage later on. If these asserts are disabled (no hardening), then the table
421
         lookup a few lines below (id = ...) is likely to crash dur to an out-of-bounds read. DO NOT FIX
422
         that crash on NaN since it could result in a worse issue later on. */
423
0
      celt_assert(!celt_isnan(tmp[0]));
424
0
      celt_assert(!celt_isnan(norm));
425
0
      for (i=12;i<len2-5;i+=4)
426
0
      {
427
0
         int id;
428
#ifdef FIXED_POINT
429
         id = MAX32(0,MIN32(127,MULT16_32_Q15(tmp[i]+EPSILON,norm))); /* Do not round to nearest */
430
#else
431
0
         id = (int)MAX32(0,MIN32(127,floor(64*norm*(tmp[i]+EPSILON)))); /* Do not round to nearest */
432
0
#endif
433
0
         unmask += inv_table[id];
434
0
      }
435
      /*printf("%d\n", unmask);*/
436
      /* Normalize, compensate for the 1/4th of the sample and the factor of 6 in the inverse table */
437
0
      unmask = 64*unmask*4/(6*(len2-17));
438
0
      if (unmask>mask_metric)
439
0
      {
440
0
         *tf_chan = c;
441
0
         mask_metric = unmask;
442
0
      }
443
0
   }
444
0
   is_transient = mask_metric>200;
445
   /* Prevent the transient detector from confusing the partial cycle of a
446
      very low frequency tone with a transient. */
447
0
   if (toneishness > QCONST32(.98f, 29) && tone_freq < QCONST16(0.026f, 13))
448
0
   {
449
0
      is_transient = 0;
450
0
      mask_metric = 0;
451
0
   }
452
   /* For low bitrates, define "weak transients" that need to be
453
      handled differently to avoid partial collapse. */
454
0
   if (allow_weak_transients && is_transient && mask_metric<600) {
455
0
      is_transient = 0;
456
0
      *weak_transient = 1;
457
0
   }
458
   /* Arbitrary metric for VBR boost */
459
0
   tf_max = MAX16(0,celt_sqrt(27*mask_metric)-42);
460
   /* *tf_estimate = 1 + MIN16(1, sqrt(MAX16(0, tf_max-30))/20); */
461
0
   *tf_estimate = celt_sqrt(MAX32(0, SHL32(MULT16_16(QCONST16(0.0069,14),MIN16(163,tf_max)),14)-QCONST32(0.139,28)));
462
   /*printf("%d %f\n", tf_max, mask_metric);*/
463
0
   RESTORE_STACK;
464
#ifdef FUZZING
465
   is_transient = rand()&0x1;
466
#endif
467
   /*printf("%d %f %d\n", is_transient, (float)*tf_estimate, tf_max);*/
468
0
   return is_transient;
469
0
}
470
471
/* Looks for sudden increases of energy to decide whether we need to patch
472
   the transient decision */
473
static int patch_transient_decision(celt_glog *newE, celt_glog *oldE, int nbEBands,
474
      int start, int end, int C)
475
0
{
476
0
   int i, c;
477
0
   opus_val32 mean_diff=0;
478
0
   celt_glog spread_old[26];
479
   /* Apply an aggressive (-6 dB/Bark) spreading function to the old frame to
480
      avoid false detection caused by irrelevant bands */
481
0
   if (C==1)
482
0
   {
483
0
      spread_old[start] = oldE[start];
484
0
      for (i=start+1;i<end;i++)
485
0
         spread_old[i] = MAXG(spread_old[i-1]-GCONST(1.0f), oldE[i]);
486
0
   } else {
487
0
      spread_old[start] = MAXG(oldE[start],oldE[start+nbEBands]);
488
0
      for (i=start+1;i<end;i++)
489
0
         spread_old[i] = MAXG(spread_old[i-1]-GCONST(1.0f),
490
0
                               MAXG(oldE[i],oldE[i+nbEBands]));
491
0
   }
492
0
   for (i=end-2;i>=start;i--)
493
0
      spread_old[i] = MAXG(spread_old[i], spread_old[i+1]-GCONST(1.0f));
494
   /* Compute mean increase */
495
0
   c=0; do {
496
0
      for (i=IMAX(2,start);i<end-1;i++)
497
0
      {
498
0
         opus_val16 x1, x2;
499
0
         x1 = MAXG(0, newE[i + c*nbEBands]);
500
0
         x2 = MAXG(0, spread_old[i]);
501
0
         mean_diff = ADD32(mean_diff, MAXG(0, SUB32(x1, x2)));
502
0
      }
503
0
   } while (++c<C);
504
0
   mean_diff = DIV32(mean_diff, C*(end-1-IMAX(2,start)));
505
   /*printf("%f %f %d\n", mean_diff, max_diff, count);*/
506
0
   return mean_diff > GCONST(1.f);
507
0
}
508
509
/** Apply window and compute the MDCT for all sub-frames and
510
    all channels in a frame */
511
static void compute_mdcts(const CELTMode *mode, int shortBlocks, celt_sig * OPUS_RESTRICT in,
512
                          celt_sig * OPUS_RESTRICT out, int C, int CC, int LM, int upsample,
513
                          int arch)
514
0
{
515
0
   const int overlap = mode->overlap;
516
0
   int N;
517
0
   int B;
518
0
   int shift;
519
0
   int i, b, c;
520
0
   if (shortBlocks)
521
0
   {
522
0
      B = shortBlocks;
523
0
      N = mode->shortMdctSize;
524
0
      shift = mode->maxLM;
525
0
   } else {
526
0
      B = 1;
527
0
      N = mode->shortMdctSize<<LM;
528
0
      shift = mode->maxLM-LM;
529
0
   }
530
0
   c=0; do {
531
0
      for (b=0;b<B;b++)
532
0
      {
533
         /* Interleaving the sub-frames while doing the MDCTs */
534
0
         clt_mdct_forward(&mode->mdct, in+c*(B*N+overlap)+b*N,
535
0
                          &out[b+c*N*B], mode->window, overlap, shift, B,
536
0
                          arch);
537
0
      }
538
0
   } while (++c<CC);
539
0
   if (CC==2&&C==1)
540
0
   {
541
0
      for (i=0;i<B*N;i++)
542
0
         out[i] = ADD32(HALF32(out[i]), HALF32(out[B*N+i]));
543
0
   }
544
0
   if (upsample != 1)
545
0
   {
546
0
      c=0; do
547
0
      {
548
0
         int bound = B*N/upsample;
549
0
         for (i=0;i<bound;i++)
550
0
            out[c*B*N+i] *= upsample;
551
0
         OPUS_CLEAR(&out[c*B*N+bound], B*N-bound);
552
0
      } while (++c<C);
553
0
   }
554
0
}
555
556
557
void celt_preemphasis(const opus_res * OPUS_RESTRICT pcmp, celt_sig * OPUS_RESTRICT inp,
558
                        int N, int CC, int upsample, const opus_val16 *coef, celt_sig *mem, int clip)
559
0
{
560
0
   int i;
561
0
   opus_val16 coef0;
562
0
   celt_sig m;
563
0
   int Nu;
564
565
0
   coef0 = coef[0];
566
0
   m = *mem;
567
568
   /* Fast path for the normal 48kHz case and no clipping */
569
0
   if (coef[1] == 0 && upsample == 1 && !clip)
570
0
   {
571
0
      for (i=0;i<N;i++)
572
0
      {
573
0
         celt_sig x;
574
0
         x = RES2SIG(pcmp[CC*i]);
575
         /* Apply pre-emphasis */
576
0
         inp[i] = x - m;
577
0
         m = MULT16_32_Q15(coef0, x);
578
0
      }
579
0
      *mem = m;
580
0
      return;
581
0
   }
582
583
0
   Nu = N/upsample;
584
0
   if (upsample!=1)
585
0
   {
586
0
      OPUS_CLEAR(inp, N);
587
0
   }
588
0
   for (i=0;i<Nu;i++)
589
0
      inp[i*upsample] = RES2SIG(pcmp[CC*i]);
590
591
0
#ifndef FIXED_POINT
592
0
   if (clip)
593
0
   {
594
      /* Clip input to avoid encoding non-portable files */
595
0
      for (i=0;i<Nu;i++)
596
0
         inp[i*upsample] = MAX32(-65536.f, MIN32(65536.f,inp[i*upsample]));
597
0
   }
598
#else
599
   (void)clip; /* Avoids a warning about clip being unused. */
600
#endif
601
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API) || defined(ENABLE_QEXT)
602
   if (coef[1] != 0)
603
   {
604
      opus_val16 coef1 = coef[1];
605
#if defined(FIXED_POINT) && defined(ENABLE_QEXT)
606
      /* If we need the extra precision, we use the fact that coef[3] is exact to do a Newton-Raphson
607
         iteration and get us more precision on coef[2]. */
608
      opus_val32 coef2_q30 = SHL32(coef[2], 18) + PSHR32(MULT16_16(QCONST32(1.f, 25) - MULT16_16(coef[3], coef[2]), coef[2]), 7);
609
      celt_assert(SIG_SHIFT == 12);
610
#else
611
      opus_val16 coef2 = coef[2];
612
#endif
613
      for (i=0;i<N;i++)
614
      {
615
         celt_sig x, tmp;
616
         x = inp[i];
617
         /* Apply pre-emphasis */
618
#if defined(FIXED_POINT) && defined(ENABLE_QEXT)
619
         tmp = SHL32(MULT32_32_Q31(coef2_q30, x), 1);
620
#else
621
         tmp = SHL32(MULT16_32_Q15(coef2, x), 15-SIG_SHIFT);
622
#endif
623
         inp[i] = tmp + m;
624
         m = MULT16_32_Q15(coef1, inp[i]) - MULT16_32_Q15(coef0, tmp);
625
      }
626
   } else
627
#endif
628
0
   {
629
0
      for (i=0;i<N;i++)
630
0
      {
631
0
         celt_sig x;
632
0
         x = inp[i];
633
         /* Apply pre-emphasis */
634
0
         inp[i] = x - m;
635
0
         m = MULT16_32_Q15(coef0, x);
636
0
      }
637
0
   }
638
0
   *mem = m;
639
0
}
640
641
642
643
static opus_val32 l1_metric(const celt_norm *tmp, int N, int LM, opus_val16 bias)
644
0
{
645
0
   int i;
646
0
   opus_val32 L1;
647
0
   L1 = 0;
648
0
   for (i=0;i<N;i++)
649
0
      L1 += EXTEND32(ABS16(SHR32(tmp[i], NORM_SHIFT-14)));
650
   /* When in doubt, prefer good freq resolution */
651
0
   L1 = MAC16_32_Q15(L1, LM*bias, L1);
652
0
   return L1;
653
654
0
}
655
656
static int tf_analysis(const CELTMode *m, int len, int isTransient,
657
      int *tf_res, int lambda, celt_norm *X, int N0, int LM,
658
      opus_val16 tf_estimate, int tf_chan, int *importance)
659
0
{
660
0
   int i;
661
0
   VARDECL(int, metric);
662
0
   int cost0;
663
0
   int cost1;
664
0
   VARDECL(int, path0);
665
0
   VARDECL(int, path1);
666
0
   VARDECL(celt_norm, tmp);
667
0
   VARDECL(celt_norm, tmp_1);
668
0
   int sel;
669
0
   int selcost[2];
670
0
   int tf_select=0;
671
0
   opus_val16 bias;
672
673
0
   SAVE_STACK;
674
0
   bias = MULT16_16_Q14(QCONST16(.04f,15), MAX16(-QCONST16(.25f,14), QCONST16(.5f,14)-tf_estimate));
675
   /*printf("%f ", bias);*/
676
677
0
   ALLOC(metric, len, int);
678
0
   ALLOC(tmp, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
679
0
   ALLOC(tmp_1, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
680
0
   ALLOC(path0, len, int);
681
0
   ALLOC(path1, len, int);
682
683
0
   for (i=0;i<len;i++)
684
0
   {
685
0
      int k, N;
686
0
      int narrow;
687
0
      opus_val32 L1, best_L1;
688
0
      int best_level=0;
689
0
      N = (m->eBands[i+1]-m->eBands[i])<<LM;
690
      /* band is too narrow to be split down to LM=-1 */
691
0
      narrow = (m->eBands[i+1]-m->eBands[i])==1;
692
0
      OPUS_COPY(tmp, &X[tf_chan*N0 + (m->eBands[i]<<LM)], N);
693
      /* Just add the right channel if we're in stereo */
694
      /*if (C==2)
695
         for (j=0;j<N;j++)
696
            tmp[j] = ADD16(SHR16(tmp[j], 1),SHR16(X[N0+j+(m->eBands[i]<<LM)], 1));*/
697
0
      L1 = l1_metric(tmp, N, isTransient ? LM : 0, bias);
698
0
      best_L1 = L1;
699
      /* Check the -1 case for transients */
700
0
      if (isTransient && !narrow)
701
0
      {
702
0
         OPUS_COPY(tmp_1, tmp, N);
703
0
         haar1(tmp_1, N>>LM, 1<<LM);
704
0
         L1 = l1_metric(tmp_1, N, LM+1, bias);
705
0
         if (L1<best_L1)
706
0
         {
707
0
            best_L1 = L1;
708
0
            best_level = -1;
709
0
         }
710
0
      }
711
      /*printf ("%f ", L1);*/
712
0
      for (k=0;k<LM+!(isTransient||narrow);k++)
713
0
      {
714
0
         int B;
715
716
0
         if (isTransient)
717
0
            B = (LM-k-1);
718
0
         else
719
0
            B = k+1;
720
721
0
         haar1(tmp, N>>k, 1<<k);
722
723
0
         L1 = l1_metric(tmp, N, B, bias);
724
725
0
         if (L1 < best_L1)
726
0
         {
727
0
            best_L1 = L1;
728
0
            best_level = k+1;
729
0
         }
730
0
      }
731
      /*printf ("%d ", isTransient ? LM-best_level : best_level);*/
732
      /* metric is in Q1 to be able to select the mid-point (-0.5) for narrower bands */
733
0
      if (isTransient)
734
0
         metric[i] = 2*best_level;
735
0
      else
736
0
         metric[i] = -2*best_level;
737
      /* For bands that can't be split to -1, set the metric to the half-way point to avoid
738
         biasing the decision */
739
0
      if (narrow && (metric[i]==0 || metric[i]==-2*LM))
740
0
         metric[i]-=1;
741
      /*printf("%d ", metric[i]/2 + (!isTransient)*LM);*/
742
0
   }
743
   /*printf("\n");*/
744
   /* Search for the optimal tf resolution, including tf_select */
745
0
   tf_select = 0;
746
0
   for (sel=0;sel<2;sel++)
747
0
   {
748
0
      cost0 = importance[0]*abs(metric[0]-2*tf_select_table[LM][4*isTransient+2*sel+0]);
749
0
      cost1 = importance[0]*abs(metric[0]-2*tf_select_table[LM][4*isTransient+2*sel+1]) + (isTransient ? 0 : lambda);
750
0
      for (i=1;i<len;i++)
751
0
      {
752
0
         int curr0, curr1;
753
0
         curr0 = IMIN(cost0, cost1 + lambda);
754
0
         curr1 = IMIN(cost0 + lambda, cost1);
755
0
         cost0 = curr0 + importance[i]*abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*sel+0]);
756
0
         cost1 = curr1 + importance[i]*abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*sel+1]);
757
0
      }
758
0
      cost0 = IMIN(cost0, cost1);
759
0
      selcost[sel]=cost0;
760
0
   }
761
   /* For now, we're conservative and only allow tf_select=1 for transients.
762
    * If tests confirm it's useful for non-transients, we could allow it. */
763
0
   if (selcost[1]<selcost[0] && isTransient)
764
0
      tf_select=1;
765
0
   cost0 = importance[0]*abs(metric[0]-2*tf_select_table[LM][4*isTransient+2*tf_select+0]);
766
0
   cost1 = importance[0]*abs(metric[0]-2*tf_select_table[LM][4*isTransient+2*tf_select+1]) + (isTransient ? 0 : lambda);
767
   /* Viterbi forward pass */
768
0
   for (i=1;i<len;i++)
769
0
   {
770
0
      int curr0, curr1;
771
0
      int from0, from1;
772
773
0
      from0 = cost0;
774
0
      from1 = cost1 + lambda;
775
0
      if (from0 < from1)
776
0
      {
777
0
         curr0 = from0;
778
0
         path0[i]= 0;
779
0
      } else {
780
0
         curr0 = from1;
781
0
         path0[i]= 1;
782
0
      }
783
784
0
      from0 = cost0 + lambda;
785
0
      from1 = cost1;
786
0
      if (from0 < from1)
787
0
      {
788
0
         curr1 = from0;
789
0
         path1[i]= 0;
790
0
      } else {
791
0
         curr1 = from1;
792
0
         path1[i]= 1;
793
0
      }
794
0
      cost0 = curr0 + importance[i]*abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*tf_select+0]);
795
0
      cost1 = curr1 + importance[i]*abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*tf_select+1]);
796
0
   }
797
0
   tf_res[len-1] = cost0 < cost1 ? 0 : 1;
798
   /* Viterbi backward pass to check the decisions */
799
0
   for (i=len-2;i>=0;i--)
800
0
   {
801
0
      if (tf_res[i+1] == 1)
802
0
         tf_res[i] = path1[i+1];
803
0
      else
804
0
         tf_res[i] = path0[i+1];
805
0
   }
806
   /*printf("%d %f\n", *tf_sum, tf_estimate);*/
807
0
   RESTORE_STACK;
808
#ifdef FUZZING
809
   tf_select = rand()&0x1;
810
   tf_res[0] = rand()&0x1;
811
   for (i=1;i<len;i++)
812
      tf_res[i] = tf_res[i-1] ^ ((rand()&0xF) == 0);
813
#endif
814
0
   return tf_select;
815
0
}
816
817
static void tf_encode(int start, int end, int isTransient, int *tf_res, int LM, int tf_select, ec_enc *enc)
818
0
{
819
0
   int curr, i;
820
0
   int tf_select_rsv;
821
0
   int tf_changed;
822
0
   int logp;
823
0
   opus_uint32 budget;
824
0
   opus_uint32 tell;
825
0
   budget = enc->storage*8;
826
0
   tell = ec_tell(enc);
827
0
   logp = isTransient ? 2 : 4;
828
   /* Reserve space to code the tf_select decision. */
829
0
   tf_select_rsv = LM>0 && tell+logp+1 <= budget;
830
0
   budget -= tf_select_rsv;
831
0
   curr = tf_changed = 0;
832
0
   for (i=start;i<end;i++)
833
0
   {
834
0
      if (tell+logp<=budget)
835
0
      {
836
0
         ec_enc_bit_logp(enc, tf_res[i] ^ curr, logp);
837
0
         tell = ec_tell(enc);
838
0
         curr = tf_res[i];
839
0
         tf_changed |= curr;
840
0
      }
841
0
      else
842
0
         tf_res[i] = curr;
843
0
      logp = isTransient ? 4 : 5;
844
0
   }
845
   /* Only code tf_select if it would actually make a difference. */
846
0
   if (tf_select_rsv &&
847
0
         tf_select_table[LM][4*isTransient+0+tf_changed]!=
848
0
         tf_select_table[LM][4*isTransient+2+tf_changed])
849
0
      ec_enc_bit_logp(enc, tf_select, 1);
850
0
   else
851
0
      tf_select = 0;
852
0
   for (i=start;i<end;i++)
853
0
      tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
854
   /*for(i=0;i<end;i++)printf("%d ", isTransient ? tf_res[i] : LM+tf_res[i]);printf("\n");*/
855
0
}
856
857
858
static int alloc_trim_analysis(const CELTMode *m, const celt_norm *X,
859
      const celt_glog *bandLogE, int end, int LM, int C, int N0,
860
      AnalysisInfo *analysis, opus_val16 *stereo_saving, opus_val16 tf_estimate,
861
      int intensity, celt_glog surround_trim, opus_int32 equiv_rate, int arch)
862
0
{
863
0
   int i;
864
0
   opus_val32 diff=0;
865
0
   int c;
866
0
   int trim_index;
867
0
   opus_val16 trim = QCONST16(5.f, 8);
868
0
   opus_val16 logXC, logXC2;
869
   /* At low bitrate, reducing the trim seems to help. At higher bitrates, it's less
870
      clear what's best, so we're keeping it as it was before, at least for now. */
871
0
   if (equiv_rate < 64000) {
872
0
      trim = QCONST16(4.f, 8);
873
0
   } else if (equiv_rate < 80000) {
874
0
      opus_int32 frac = (equiv_rate-64000) >> 10;
875
0
      trim = QCONST16(4.f, 8) + QCONST16(1.f/16.f, 8)*frac;
876
0
   }
877
0
   if (C==2)
878
0
   {
879
0
      opus_val16 sum = 0; /* Q10 */
880
0
      opus_val16 minXC; /* Q10 */
881
      /* Compute inter-channel correlation for low frequencies */
882
0
      for (i=0;i<8;i++)
883
0
      {
884
0
         opus_val32 partial;
885
0
         partial = celt_inner_prod_norm_shift(&X[m->eBands[i]<<LM], &X[N0+(m->eBands[i]<<LM)],
886
0
               (m->eBands[i+1]-m->eBands[i])<<LM, arch);
887
0
         sum = ADD16(sum, EXTRACT16(SHR32(partial, 18)));
888
0
      }
889
0
      sum = MULT16_16_Q15(QCONST16(1.f/8, 15), sum);
890
0
      sum = MIN16(QCONST16(1.f, 10), ABS16(sum));
891
0
      minXC = sum;
892
0
      for (i=8;i<intensity;i++)
893
0
      {
894
0
         opus_val32 partial;
895
0
         partial = celt_inner_prod_norm_shift(&X[m->eBands[i]<<LM], &X[N0+(m->eBands[i]<<LM)],
896
0
               (m->eBands[i+1]-m->eBands[i])<<LM, arch);
897
0
         minXC = MIN16(minXC, ABS16(EXTRACT16(SHR32(partial, 18))));
898
0
      }
899
0
      minXC = MIN16(QCONST16(1.f, 10), ABS16(minXC));
900
      /*printf ("%f\n", sum);*/
901
      /* mid-side savings estimations based on the LF average*/
902
0
      logXC = celt_log2(QCONST32(1.001f, 20)-MULT16_16(sum, sum));
903
      /* mid-side savings estimations based on min correlation */
904
0
      logXC2 = MAX16(HALF16(logXC), celt_log2(QCONST32(1.001f, 20)-MULT16_16(minXC, minXC)));
905
#ifdef FIXED_POINT
906
      /* Compensate for Q20 vs Q14 input and convert output to Q8 */
907
      logXC = PSHR32(logXC-QCONST16(6.f, 10),10-8);
908
      logXC2 = PSHR32(logXC2-QCONST16(6.f, 10),10-8);
909
#endif
910
911
0
      trim += MAX16(-QCONST16(4.f, 8), MULT16_16_Q15(QCONST16(.75f,15),logXC));
912
0
      *stereo_saving = MIN16(*stereo_saving + QCONST16(0.25f, 8), -HALF16(logXC2));
913
0
   }
914
915
   /* Estimate spectral tilt */
916
0
   c=0; do {
917
0
      for (i=0;i<end-1;i++)
918
0
      {
919
0
         diff += SHR32(bandLogE[i+c*m->nbEBands], 5)*(opus_int32)(2+2*i-end);
920
0
      }
921
0
   } while (++c<C);
922
0
   diff /= C*(end-1);
923
   /*printf("%f\n", diff);*/
924
0
   trim -= MAX32(-QCONST16(2.f, 8), MIN32(QCONST16(2.f, 8), SHR32(diff+QCONST32(1.f, DB_SHIFT-5),DB_SHIFT-13)/6 ));
925
0
   trim -= SHR16(surround_trim, DB_SHIFT-8);
926
0
   trim -= 2*SHR16(tf_estimate, 14-8);
927
0
#ifndef DISABLE_FLOAT_API
928
0
   if (analysis->valid)
929
0
   {
930
0
      trim -= MAX16(-QCONST16(2.f, 8), MIN16(QCONST16(2.f, 8),
931
0
            (opus_val16)(QCONST16(2.f, 8)*(analysis->tonality_slope+.05f))));
932
0
   }
933
#else
934
   (void)analysis;
935
#endif
936
937
#ifdef FIXED_POINT
938
   trim_index = PSHR32(trim, 8);
939
#else
940
0
   trim_index = (int)floor(.5f+trim);
941
0
#endif
942
0
   trim_index = IMAX(0, IMIN(10, trim_index));
943
   /*printf("%d\n", trim_index);*/
944
#ifdef FUZZING
945
   trim_index = rand()%11;
946
#endif
947
0
   return trim_index;
948
0
}
949
950
static int stereo_analysis(const CELTMode *m, const celt_norm *X,
951
      int LM, int N0)
952
0
{
953
0
   int i;
954
0
   int thetas;
955
0
   opus_val32 sumLR = EPSILON, sumMS = EPSILON;
956
957
   /* Use the L1 norm to model the entropy of the L/R signal vs the M/S signal */
958
0
   for (i=0;i<13;i++)
959
0
   {
960
0
      int j;
961
0
      for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
962
0
      {
963
0
         opus_val32 L, R, M, S;
964
         /* We cast to 32-bit first because of the -32768 case */
965
0
         L = SHR32(X[j], NORM_SHIFT-14);
966
0
         R = SHR32(X[N0+j], NORM_SHIFT-14);
967
0
         M = ADD32(L, R);
968
0
         S = SUB32(L, R);
969
0
         sumLR = ADD32(sumLR, ADD32(ABS32(L), ABS32(R)));
970
0
         sumMS = ADD32(sumMS, ADD32(ABS32(M), ABS32(S)));
971
0
      }
972
0
   }
973
0
   sumMS = MULT16_32_Q15(QCONST16(0.707107f, 15), sumMS);
974
0
   thetas = 13;
975
   /* We don't need thetas for lower bands with LM<=1 */
976
0
   if (LM<=1)
977
0
      thetas -= 8;
978
0
   return MULT16_32_Q15((m->eBands[13]<<(LM+1))+thetas, sumMS)
979
0
         > MULT16_32_Q15(m->eBands[13]<<(LM+1), sumLR);
980
0
}
981
982
0
#define MSWAP(a,b) do {celt_glog tmp = a;a=b;b=tmp;} while(0)
983
static celt_glog median_of_5(const celt_glog *x)
984
0
{
985
0
   celt_glog t0, t1, t2, t3, t4;
986
0
   t2 = x[2];
987
0
   if (x[0] > x[1])
988
0
   {
989
0
      t0 = x[1];
990
0
      t1 = x[0];
991
0
   } else {
992
0
      t0 = x[0];
993
0
      t1 = x[1];
994
0
   }
995
0
   if (x[3] > x[4])
996
0
   {
997
0
      t3 = x[4];
998
0
      t4 = x[3];
999
0
   } else {
1000
0
      t3 = x[3];
1001
0
      t4 = x[4];
1002
0
   }
1003
0
   if (t0 > t3)
1004
0
   {
1005
0
      MSWAP(t0, t3);
1006
0
      MSWAP(t1, t4);
1007
0
   }
1008
0
   if (t2 > t1)
1009
0
   {
1010
0
      if (t1 < t3)
1011
0
         return MING(t2, t3);
1012
0
      else
1013
0
         return MING(t4, t1);
1014
0
   } else {
1015
0
      if (t2 < t3)
1016
0
         return MING(t1, t3);
1017
0
      else
1018
0
         return MING(t2, t4);
1019
0
   }
1020
0
}
1021
1022
static celt_glog median_of_3(const celt_glog *x)
1023
0
{
1024
0
   celt_glog t0, t1, t2;
1025
0
   if (x[0] > x[1])
1026
0
   {
1027
0
      t0 = x[1];
1028
0
      t1 = x[0];
1029
0
   } else {
1030
0
      t0 = x[0];
1031
0
      t1 = x[1];
1032
0
   }
1033
0
   t2 = x[2];
1034
0
   if (t1 < t2)
1035
0
      return t1;
1036
0
   else if (t0 < t2)
1037
0
      return t2;
1038
0
   else
1039
0
      return t0;
1040
0
}
1041
1042
static celt_glog dynalloc_analysis(const celt_glog *bandLogE, const celt_glog *bandLogE2, const celt_glog *oldBandE,
1043
      int nbEBands, int start, int end, int C, int *offsets, int lsb_depth, const opus_int16 *logN,
1044
      int isTransient, int vbr, int constrained_vbr, const opus_int16 *eBands, int LM,
1045
      int effectiveBytes, opus_int32 *tot_boost_, int lfe, celt_glog *surround_dynalloc,
1046
      AnalysisInfo *analysis, int *importance, int *spread_weight, opus_val16 tone_freq, opus_val32 toneishness
1047
      ARG_QEXT(int qext_scale))
1048
0
{
1049
0
   int i, c;
1050
0
   opus_int32 tot_boost=0;
1051
0
   celt_glog maxDepth;
1052
0
   VARDECL(celt_glog, follower);
1053
0
   VARDECL(celt_glog, noise_floor);
1054
0
   VARDECL(celt_glog, bandLogE3);
1055
0
   SAVE_STACK;
1056
0
   ALLOC(follower, C*nbEBands, celt_glog);
1057
0
   ALLOC(noise_floor, C*nbEBands, celt_glog);
1058
0
   ALLOC(bandLogE3, nbEBands, celt_glog);
1059
0
   OPUS_CLEAR(offsets, nbEBands);
1060
   /* Dynamic allocation code */
1061
0
   maxDepth=-GCONST(31.9f);
1062
0
   for (i=0;i<end;i++)
1063
0
   {
1064
      /* Noise floor must take into account eMeans, the depth, the width of the bands
1065
         and the preemphasis filter (approx. square of bark band ID) */
1066
0
      noise_floor[i] = GCONST(0.0625f)*logN[i]
1067
0
            +GCONST(.5f)+SHL32(9-lsb_depth,DB_SHIFT)-SHL32(eMeans[i],DB_SHIFT-4)
1068
0
            +GCONST(.0062f)*(i+5)*(i+5);
1069
0
   }
1070
0
   c=0;do
1071
0
   {
1072
0
      for (i=0;i<end;i++)
1073
0
         maxDepth = MAXG(maxDepth, bandLogE[c*nbEBands+i]-noise_floor[i]);
1074
0
   } while (++c<C);
1075
0
   {
1076
      /* Compute a really simple masking model to avoid taking into account completely masked
1077
         bands when computing the spreading decision. */
1078
0
      VARDECL(celt_glog, mask);
1079
0
      VARDECL(celt_glog, sig);
1080
0
      ALLOC(mask, nbEBands, celt_glog);
1081
0
      ALLOC(sig, nbEBands, celt_glog);
1082
0
      for (i=0;i<end;i++)
1083
0
         mask[i] = bandLogE[i]-noise_floor[i];
1084
0
      if (C==2)
1085
0
      {
1086
0
         for (i=0;i<end;i++)
1087
0
            mask[i] = MAXG(mask[i], bandLogE[nbEBands+i]-noise_floor[i]);
1088
0
      }
1089
0
      OPUS_COPY(sig, mask, end);
1090
0
      for (i=1;i<end;i++)
1091
0
         mask[i] = MAXG(mask[i], mask[i-1] - GCONST(2.f));
1092
0
      for (i=end-2;i>=0;i--)
1093
0
         mask[i] = MAXG(mask[i], mask[i+1] - GCONST(3.f));
1094
0
      for (i=0;i<end;i++)
1095
0
      {
1096
         /* Compute SMR: Mask is never more than 72 dB below the peak and never below the noise floor.*/
1097
0
         celt_glog smr = sig[i]-MAXG(MAXG(0, maxDepth-GCONST(12.f)), mask[i]);
1098
         /* Clamp SMR to make sure we're not shifting by something negative or too large. */
1099
#ifdef FIXED_POINT
1100
         /* FIXME: Use PSHR16() instead */
1101
         int shift = -PSHR32(MAXG(-GCONST(5.f), MING(0, smr)), DB_SHIFT);
1102
#else
1103
0
         int shift = IMIN(5, IMAX(0, -(int)floor(.5f + smr)));
1104
0
#endif
1105
0
         spread_weight[i] = 32 >> shift;
1106
0
      }
1107
      /*for (i=0;i<end;i++)
1108
         printf("%d ", spread_weight[i]);
1109
      printf("\n");*/
1110
0
   }
1111
   /* Make sure that dynamic allocation can't make us bust the budget.
1112
      We enable the feature starting at 24 kb/s for 20-ms frames
1113
      and 96 kb/s for 2.5 ms frames.  */
1114
0
   if (effectiveBytes >= (30 + 5*LM) && !lfe)
1115
0
   {
1116
0
      int last=0;
1117
0
      c=0;do
1118
0
      {
1119
0
         celt_glog offset;
1120
0
         celt_glog tmp;
1121
0
         celt_glog *f;
1122
0
         OPUS_COPY(bandLogE3, &bandLogE2[c*nbEBands], end);
1123
0
         if (LM==0) {
1124
            /* For 2.5 ms frames, the first 8 bands have just one bin, so the
1125
               energy is highly unreliable (high variance). For that reason,
1126
               we take the max with the previous energy so that at least 2 bins
1127
               are getting used. */
1128
0
            for (i=0;i<IMIN(8,end);i++) bandLogE3[i] = MAXG(bandLogE2[c*nbEBands+i], oldBandE[c*nbEBands+i]);
1129
0
         }
1130
0
         f = &follower[c*nbEBands];
1131
0
         f[0] = bandLogE3[0];
1132
0
         for (i=1;i<end;i++)
1133
0
         {
1134
            /* The last band to be at least 3 dB higher than the previous one
1135
               is the last we'll consider. Otherwise, we run into problems on
1136
               bandlimited signals. */
1137
0
            if (bandLogE3[i] > bandLogE3[i-1]+GCONST(.5f))
1138
0
               last=i;
1139
0
            f[i] = MING(f[i-1]+GCONST(1.5f), bandLogE3[i]);
1140
0
         }
1141
0
         for (i=last-1;i>=0;i--)
1142
0
            f[i] = MING(f[i], MING(f[i+1]+GCONST(2.f), bandLogE3[i]));
1143
1144
         /* Combine with a median filter to avoid dynalloc triggering unnecessarily.
1145
            The "offset" value controls how conservative we are -- a higher offset
1146
            reduces the impact of the median filter and makes dynalloc use more bits. */
1147
0
         offset = GCONST(1.f);
1148
0
         for (i=2;i<end-2;i++)
1149
0
            f[i] = MAXG(f[i], median_of_5(&bandLogE3[i-2])-offset);
1150
0
         tmp = median_of_3(&bandLogE3[0])-offset;
1151
0
         f[0] = MAXG(f[0], tmp);
1152
0
         f[1] = MAXG(f[1], tmp);
1153
0
         tmp = median_of_3(&bandLogE3[end-3])-offset;
1154
0
         f[end-2] = MAXG(f[end-2], tmp);
1155
0
         f[end-1] = MAXG(f[end-1], tmp);
1156
1157
0
         for (i=0;i<end;i++)
1158
0
            f[i] = MAXG(f[i], noise_floor[i]);
1159
0
      } while (++c<C);
1160
0
      if (C==2)
1161
0
      {
1162
0
         for (i=start;i<end;i++)
1163
0
         {
1164
            /* Consider 24 dB "cross-talk" */
1165
0
            follower[nbEBands+i] = MAXG(follower[nbEBands+i], follower[         i]-GCONST(4.f));
1166
0
            follower[         i] = MAXG(follower[         i], follower[nbEBands+i]-GCONST(4.f));
1167
0
            follower[i] = HALF32(MAXG(0, bandLogE[i]-follower[i]) + MAXG(0, bandLogE[nbEBands+i]-follower[nbEBands+i]));
1168
0
         }
1169
0
      } else {
1170
0
         for (i=start;i<end;i++)
1171
0
         {
1172
0
            follower[i] = MAXG(0, bandLogE[i]-follower[i]);
1173
0
         }
1174
0
      }
1175
0
      for (i=start;i<end;i++)
1176
0
         follower[i] = MAXG(follower[i], surround_dynalloc[i]);
1177
0
      for (i=start;i<end;i++)
1178
0
      {
1179
#ifdef FIXED_POINT
1180
         importance[i] = PSHR32(13*celt_exp2_db(MING(follower[i], GCONST(4.f))), 16);
1181
#else
1182
0
         importance[i] = (int)floor(.5f+13*celt_exp2_db(MING(follower[i], GCONST(4.f))));
1183
0
#endif
1184
0
      }
1185
      /* For non-transient CBR/CVBR frames, halve the dynalloc contribution */
1186
0
      if ((!vbr || constrained_vbr)&&!isTransient)
1187
0
      {
1188
0
         for (i=start;i<end;i++)
1189
0
            follower[i] = HALF32(follower[i]);
1190
0
      }
1191
0
      for (i=start;i<end;i++)
1192
0
      {
1193
0
         if (i<8)
1194
0
            follower[i] *= 2;
1195
0
         if (i>=12)
1196
0
            follower[i] = HALF32(follower[i]);
1197
0
      }
1198
      /* Compensate for Opus' under-allocation on tones. */
1199
0
      if (toneishness > QCONST32(.98f, 29)) {
1200
#ifdef FIXED_POINT
1201
         int freq_bin = PSHR32(QEXT_SCALE((opus_val32)tone_freq)*QCONST16(120/M_PI, 9), 13+9);
1202
#else
1203
0
         int freq_bin = (int)floor(.5 + QEXT_SCALE(tone_freq)*120/M_PI);
1204
0
#endif
1205
0
         for (i=start;i<end;i++) {
1206
0
            if (freq_bin >= eBands[i] && freq_bin <= eBands[i+1]) follower[i] += GCONST(2.f);
1207
0
            if (freq_bin >= eBands[i]-1 && freq_bin <= eBands[i+1]+1) follower[i] += GCONST(1.f);
1208
0
            if (freq_bin >= eBands[i]-2 && freq_bin <= eBands[i+1]+2) follower[i] += GCONST(1.f);
1209
0
            if (freq_bin >= eBands[i]-3 && freq_bin <= eBands[i+1]+3) follower[i] += GCONST(.5f);
1210
0
         }
1211
0
         if (freq_bin >= eBands[end]) {
1212
0
            follower[end-1] += GCONST(2.f);
1213
0
            follower[end-2] += GCONST(1.f);
1214
0
         }
1215
0
      }
1216
#ifdef DISABLE_FLOAT_API
1217
      (void)analysis;
1218
#else
1219
0
      if (analysis->valid)
1220
0
      {
1221
0
         for (i=start;i<IMIN(LEAK_BANDS, end);i++)
1222
0
            follower[i] = follower[i] +  GCONST(1.f/64.f)*analysis->leak_boost[i];
1223
0
      }
1224
0
#endif
1225
0
      for (i=start;i<end;i++)
1226
0
      {
1227
0
         int width;
1228
0
         int boost;
1229
0
         int boost_bits;
1230
1231
0
         follower[i] = MING(follower[i], GCONST(4));
1232
1233
0
         follower[i] = SHR32(follower[i], 8);
1234
0
         width = C*(eBands[i+1]-eBands[i])<<LM;
1235
0
         if (width<6)
1236
0
         {
1237
0
            boost = (int)SHR32(follower[i],DB_SHIFT-8);
1238
0
            boost_bits = boost*width<<BITRES;
1239
0
         } else if (width > 48) {
1240
0
            boost = (int)SHR32(follower[i]*8,DB_SHIFT-8);
1241
0
            boost_bits = (boost*width<<BITRES)/8;
1242
0
         } else {
1243
0
            boost = (int)SHR32(follower[i]*width/6,DB_SHIFT-8);
1244
0
            boost_bits = boost*6<<BITRES;
1245
0
         }
1246
         /* For CBR and non-transient CVBR frames, limit dynalloc to 2/3 of the bits */
1247
0
         if ((!vbr || (constrained_vbr&&!isTransient))
1248
0
               && (tot_boost+boost_bits)>>BITRES>>3 > 2*effectiveBytes/3)
1249
0
         {
1250
0
            opus_int32 cap = ((2*effectiveBytes/3)<<BITRES<<3);
1251
0
            offsets[i] = cap-tot_boost;
1252
0
            tot_boost = cap;
1253
0
            break;
1254
0
         } else {
1255
0
            offsets[i] = boost;
1256
0
            tot_boost += boost_bits;
1257
0
         }
1258
0
      }
1259
0
   } else {
1260
0
      for (i=start;i<end;i++)
1261
0
         importance[i] = 13;
1262
0
   }
1263
0
   *tot_boost_ = tot_boost;
1264
0
   RESTORE_STACK;
1265
0
   return maxDepth;
1266
0
}
1267
1268
#ifdef FIXED_POINT
1269
void normalize_tone_input(opus_val16 *x, int len) {
1270
   opus_val32 ac0=len;
1271
   int i;
1272
   int shift;
1273
   for (i=0;i<len;i++) {
1274
      ac0 = ADD32(ac0, SHR32(MULT16_16(x[i], x[i]), 10));
1275
   }
1276
   shift = 5 - (28-celt_ilog2(ac0))/2;
1277
   if (shift > 0) {
1278
      for (i=0;i<len;i++) {
1279
         x[i] = PSHR32(x[i], shift);
1280
      }
1281
   }
1282
}
1283
int acos_approx(opus_val32 x) {
1284
   opus_val16 x14;
1285
   opus_val32 tmp;
1286
   int flip = x<0;
1287
   x = abs(x);
1288
   x14 = x>>15;
1289
   tmp = (762*x14>>14)-3308;
1290
   tmp = (tmp*x14>>14)+25726;
1291
   tmp = tmp*celt_sqrt(IMAX(0, (1<<30) - (x<<1)))>>16;
1292
   if (flip) tmp = 25736 - tmp;
1293
   return tmp;
1294
}
1295
#endif
1296
1297
/* Compute the LPC coefficients using a least-squares fit for both forward and backward prediction. */
1298
0
static int tone_lpc(const opus_val16 *x, int len, int delay, opus_val32 *lpc) {
1299
0
   int i;
1300
0
   opus_val32 r00=0, r01=0, r11=0, r02=0, r12=0, r22=0;
1301
0
   opus_val32 edges;
1302
0
   opus_val32 num0, num1, den;
1303
0
   celt_assert(len > 2*delay);
1304
   /* Compute correlations as if using the forward prediction covariance method. */
1305
0
   for (i=0;i<len-2*delay;i++) {
1306
0
      r00 += MULT16_16(x[i],x[i]);
1307
0
      r01 += MULT16_16(x[i],x[i+delay]);
1308
0
      r02 += MULT16_16(x[i],x[i+2*delay]);
1309
0
   }
1310
0
   edges = 0;
1311
0
   for (i=0;i<delay;i++) edges += MULT16_16(x[len+i-2*delay],x[len+i-2*delay]) - MULT16_16(x[i],x[i]);
1312
0
   r11 = r00+edges;
1313
0
   edges = 0;
1314
0
   for (i=0;i<delay;i++) edges += MULT16_16(x[len+i-delay],x[len+i-delay]) - MULT16_16(x[i+delay],x[i+delay]);
1315
0
   r22 = r11+edges;
1316
0
   edges = 0;
1317
0
   for (i=0;i<delay;i++) edges += MULT16_16(x[len+i-2*delay],x[len+i-delay]) - MULT16_16(x[i],x[i+delay]);
1318
0
   r12 = r01+edges;
1319
   /* Reverse and sum to get the backward contribution. */
1320
0
   {
1321
0
      opus_val32 R00, R01, R11, R02, R12, R22;
1322
0
      R00 = r00 + r22;
1323
0
      R01 = r01 + r12;
1324
0
      R11 = 2*r11;
1325
0
      R02 = 2*r02;
1326
0
      R12 = r12 + r01;
1327
0
      R22 = r00 + r22;
1328
0
      r00 = R00;
1329
0
      r01 = R01;
1330
0
      r11 = R11;
1331
0
      r02 = R02;
1332
0
      r12 = R12;
1333
0
      r22 = R22;
1334
0
   }
1335
   /* Solve A*x=b, where A=[r00, r01; r01, r11] and b=[r02; r12]. */
1336
0
   den = MULT32_32_Q31(r00,r11) - MULT32_32_Q31(r01,r01);
1337
#ifdef FIXED_POINT
1338
   if (den <= SHR32(MULT32_32_Q31(r00,r11), 10)) return 1;
1339
#else
1340
0
   if (den < .001f*MULT32_32_Q31(r00,r11)) return 1;
1341
0
#endif
1342
0
   num1 = MULT32_32_Q31(r02,r11) - MULT32_32_Q31(r01,r12);
1343
0
   if (num1 >= den) lpc[1] = QCONST32(1.f, 29);
1344
0
   else if (num1 <= -den) lpc[1] = -QCONST32(1.f, 29);
1345
0
   else lpc[1] = frac_div32_q29(num1, den);
1346
0
   num0 = MULT32_32_Q31(r00,r12) - MULT32_32_Q31(r02,r01);
1347
0
   if (HALF32(num0) >= den) lpc[0] = QCONST32(1.999999f, 29);
1348
0
   else if (HALF32(num0) <= -den) lpc[0] = -QCONST32(1.999999f, 29);
1349
0
   else lpc[0] = frac_div32_q29(num0, den);
1350
   /*printf("%f %f\n", lpc[0], lpc[1]);*/
1351
0
   return 0;
1352
0
}
1353
1354
/* Detects pure of nearly pure tones so we can prevent them from causing problems with the encoder. */
1355
0
static opus_val16 tone_detect(const celt_sig *in, int CC, int N, opus_val32 *toneishness, opus_int32 Fs) {
1356
0
   int i;
1357
0
   int delay = 1;
1358
0
   int fail;
1359
0
   opus_val32 lpc[2];
1360
0
   opus_val16 freq;
1361
0
   VARDECL(opus_val16, x);
1362
0
   ALLOC(x, N, opus_val16);
1363
   /* Shift by SIG_SHIFT+2 (+3 for stereo) to account for HF gain of the preemphasis filter. */
1364
0
   if (CC==2) {
1365
0
      for (i=0;i<N;i++) x[i] = PSHR32(ADD32(in[i], in[i+N]), SIG_SHIFT+3);
1366
0
   } else {
1367
0
      for (i=0;i<N;i++) x[i] = PSHR32(in[i], SIG_SHIFT+2);
1368
0
   }
1369
#ifdef FIXED_POINT
1370
   normalize_tone_input(x, N);
1371
#endif
1372
0
   fail = tone_lpc(x, N, delay, lpc);
1373
   /* If our LPC filter resonates too close to DC, retry the analysis with down-sampling. */
1374
0
   while (delay <= Fs/3000 && (fail || (lpc[0] > QCONST32(1.f, 29) && lpc[1] < 0))) {
1375
0
      delay *= 2;
1376
0
      fail = tone_lpc(x, N, delay, lpc);
1377
0
   }
1378
   /* Check that our filter has complex roots. */
1379
0
   if (!fail && MULT32_32_Q31(lpc[0],lpc[0]) + MULT32_32_Q31(QCONST32(3.999999, 29), lpc[1]) < 0) {
1380
      /* Squared radius of the poles. */
1381
0
      *toneishness = -lpc[1];
1382
#ifdef FIXED_POINT
1383
      freq = (acos_approx(lpc[0]>>1)+delay/2)/delay;
1384
#else
1385
0
      freq = acos(.5f*lpc[0])/delay;
1386
0
#endif
1387
0
   } else {
1388
0
      freq = -1;
1389
0
      *toneishness=0;
1390
0
   }
1391
   /*printf("%f %f %f %f\n", freq, lpc[0], lpc[1], *toneishness);*/
1392
0
   return freq;
1393
0
}
1394
1395
static int run_prefilter(CELTEncoder *st, celt_sig *in, celt_sig *prefilter_mem, int CC, int N,
1396
      int prefilter_tapset, int *pitch, opus_val16 *gain, int *qgain, int enabled, int complexity, opus_val16 tf_estimate,
1397
      int nbAvailableBytes, AnalysisInfo *analysis, opus_val16 tone_freq, opus_val32 toneishness ARG_QEXT(int qext_scale))
1398
0
{
1399
0
   int c;
1400
0
   VARDECL(celt_sig, _pre);
1401
0
   celt_sig *pre[2];
1402
0
   const CELTMode *mode;
1403
0
   int pitch_index;
1404
0
   opus_val16 gain1;
1405
0
   opus_val16 pf_threshold;
1406
0
   int pf_on;
1407
0
   int qg;
1408
0
   int overlap;
1409
0
   int min_period, max_period;
1410
0
   opus_val32 before[2]={0}, after[2]={0};
1411
0
   int cancel_pitch=0;
1412
0
   SAVE_STACK;
1413
1414
0
   max_period = QEXT_SCALE(COMBFILTER_MAXPERIOD);
1415
0
   min_period = QEXT_SCALE(COMBFILTER_MINPERIOD);
1416
0
   mode = st->mode;
1417
0
   overlap = mode->overlap;
1418
0
   ALLOC(_pre, CC*(N+max_period), celt_sig);
1419
1420
0
   pre[0] = _pre;
1421
0
   pre[1] = _pre + (N+max_period);
1422
1423
1424
0
   c=0; do {
1425
0
      OPUS_COPY(pre[c], prefilter_mem+c*max_period, max_period);
1426
0
      OPUS_COPY(pre[c]+max_period, in+c*(N+overlap)+overlap, N);
1427
0
   } while (++c<CC);
1428
1429
   /* If we detect that the signal is dominated by a single tone, don't rely on the standard pitch
1430
      estimator, as it can become unreliable. */
1431
0
   if (enabled && toneishness > QCONST32(.99f, 29)) {
1432
0
      int multiple=1;
1433
      /* Using aliased version of the postfilter above 24 kHz.
1434
         First value is purposely slightly above pi to avoid triggering for Fs=48kHz. */
1435
0
      if (QEXT_SCALE(tone_freq) >= QCONST16(3.1416f, 13)) tone_freq = QCONST16(3.141593f, 13) - tone_freq;
1436
      /* If the pitch is too high for our post-filter, apply pitch doubling until
1437
         we can get something that fits (not ideal, but better than nothing). */
1438
0
      while (QEXT_SCALE(tone_freq) >= multiple*QCONST16(0.39f, 13)) multiple++;
1439
0
      if (QEXT_SCALE(tone_freq) > QCONST16(0.006148f, 13)) {
1440
#ifdef FIXED_POINT
1441
         pitch_index = IMIN((51472*multiple+QEXT_SCALE(tone_freq)/2)/QEXT_SCALE(tone_freq), COMBFILTER_MAXPERIOD-2);
1442
#else
1443
0
         pitch_index = IMIN((int)floor(.5+2.f*M_PI*multiple/QEXT_SCALE(tone_freq)), COMBFILTER_MAXPERIOD-2);
1444
0
#endif
1445
0
      } else {
1446
         /* If the pitch is too low, using a very high pitch will actually give us an improvement
1447
            due to the DC component of the filter that will be close to our tone. Again, not ideal,
1448
            but if we only have a single tone, it's better than nothing. */
1449
0
         pitch_index = COMBFILTER_MINPERIOD;
1450
0
      }
1451
0
      gain1 = QCONST16(.75f, 15);
1452
0
   } else if (enabled && complexity >= 5) {
1453
0
      VARDECL(opus_val16, pitch_buf);
1454
0
      ALLOC(pitch_buf, (max_period+N)>>1, opus_val16);
1455
1456
0
      pitch_downsample(pre, pitch_buf, (max_period+N)>>1, CC, 2, st->arch);
1457
      /* Don't search for the fir last 1.5 octave of the range because
1458
         there's too many false-positives due to short-term correlation */
1459
0
      pitch_search(pitch_buf+(max_period>>1), pitch_buf, N,
1460
0
            max_period-3*min_period, &pitch_index,
1461
0
            st->arch);
1462
0
      pitch_index = max_period-pitch_index;
1463
1464
0
      gain1 = remove_doubling(pitch_buf, max_period, min_period,
1465
0
            N, &pitch_index, st->prefilter_period, st->prefilter_gain, st->arch);
1466
0
      if (pitch_index > max_period-QEXT_SCALE(2))
1467
0
         pitch_index = max_period-QEXT_SCALE(2);
1468
#ifdef ENABLE_QEXT
1469
      pitch_index /= qext_scale;
1470
#endif
1471
0
      gain1 = MULT16_16_Q15(QCONST16(.7f,15),gain1);
1472
      /*printf("%d %d %f %f\n", pitch_change, pitch_index, gain1, st->analysis.tonality);*/
1473
0
      if (st->loss_rate>2)
1474
0
         gain1 = HALF32(gain1);
1475
0
      if (st->loss_rate>4)
1476
0
         gain1 = HALF32(gain1);
1477
0
      if (st->loss_rate>8)
1478
0
         gain1 = 0;
1479
0
   } else {
1480
0
      gain1 = 0;
1481
0
      pitch_index = COMBFILTER_MINPERIOD;
1482
0
   }
1483
0
#ifndef DISABLE_FLOAT_API
1484
0
   if (analysis->valid)
1485
0
      gain1 = (opus_val16)(gain1 * analysis->max_pitch_ratio);
1486
#else
1487
   (void)analysis;
1488
#endif
1489
   /* Gain threshold for enabling the prefilter/postfilter */
1490
0
   pf_threshold = QCONST16(.2f,15);
1491
1492
   /* Adjusting the threshold based on rate and continuity */
1493
0
   if (abs(pitch_index-st->prefilter_period)*10>pitch_index)
1494
0
   {
1495
0
      pf_threshold += QCONST16(.2f,15);
1496
      /* Completely disable the prefilter on strong transients without continuity. */
1497
0
      if (tf_estimate > QCONST16(.98f, 14))
1498
0
         gain1 = 0;
1499
0
   }
1500
0
   if (nbAvailableBytes<25)
1501
0
      pf_threshold += QCONST16(.1f,15);
1502
0
   if (nbAvailableBytes<35)
1503
0
      pf_threshold += QCONST16(.1f,15);
1504
0
   if (st->prefilter_gain > QCONST16(.4f,15))
1505
0
      pf_threshold -= QCONST16(.1f,15);
1506
0
   if (st->prefilter_gain > QCONST16(.55f,15))
1507
0
      pf_threshold -= QCONST16(.1f,15);
1508
1509
   /* Hard threshold at 0.2 */
1510
0
   pf_threshold = MAX16(pf_threshold, QCONST16(.2f,15));
1511
0
   if (gain1<pf_threshold)
1512
0
   {
1513
0
      gain1 = 0;
1514
0
      pf_on = 0;
1515
0
      qg = 0;
1516
0
   } else {
1517
      /*This block is not gated by a total bits check only because
1518
        of the nbAvailableBytes check above.*/
1519
0
      if (ABS16(gain1-st->prefilter_gain)<QCONST16(.1f,15))
1520
0
         gain1=st->prefilter_gain;
1521
1522
#ifdef FIXED_POINT
1523
      qg = ((gain1+1536)>>10)/3-1;
1524
#else
1525
0
      qg = (int)floor(.5f+gain1*32/3)-1;
1526
0
#endif
1527
0
      qg = IMAX(0, IMIN(7, qg));
1528
0
      gain1 = QCONST16(0.09375f,15)*(qg+1);
1529
0
      pf_on = 1;
1530
0
   }
1531
   /*printf("%d %f\n", pitch_index, gain1);*/
1532
1533
0
   c=0; do {
1534
0
      int i;
1535
0
      int offset = mode->shortMdctSize-overlap;
1536
0
      st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
1537
0
      OPUS_COPY(in+c*(N+overlap), st->in_mem+c*(overlap), overlap);
1538
0
      for (i=0;i<N;i++) before[c] += ABS32(SHR32(in[c*(N+overlap)+overlap+i], 12));
1539
0
      if (offset)
1540
0
         comb_filter(in+c*(N+overlap)+overlap, pre[c]+max_period,
1541
0
               st->prefilter_period, st->prefilter_period, offset, -st->prefilter_gain, -st->prefilter_gain,
1542
0
               st->prefilter_tapset, st->prefilter_tapset, NULL, 0, st->arch);
1543
1544
0
      comb_filter(in+c*(N+overlap)+overlap+offset, pre[c]+max_period+offset,
1545
0
            st->prefilter_period, pitch_index, N-offset, -st->prefilter_gain, -gain1,
1546
0
            st->prefilter_tapset, prefilter_tapset, mode->window, overlap, st->arch);
1547
0
      for (i=0;i<N;i++) after[c] += ABS32(SHR32(in[c*(N+overlap)+overlap+i], 12));
1548
0
   } while (++c<CC);
1549
1550
0
   if (CC==2) {
1551
0
      opus_val16 thresh[2];
1552
0
      thresh[0] = MULT16_32_Q15(MULT16_16_Q15(QCONST16(.25f, 15), gain1), before[0]) + MULT16_32_Q15(QCONST16(.01f,15), before[1]);
1553
0
      thresh[1] = MULT16_32_Q15(MULT16_16_Q15(QCONST16(.25f, 15), gain1), before[1]) + MULT16_32_Q15(QCONST16(.01f,15), before[0]);
1554
      /* Don't use the filter if one channel gets significantly worse. */
1555
0
      if (after[0]-before[0] > thresh[0] || after[1]-before[1] > thresh[1]) cancel_pitch = 1;
1556
      /* Use the filter only if at least one channel gets significantly better. */
1557
0
      if (before[0]-after[0] <  thresh[0] && before[1]-after[1] < thresh[1]) cancel_pitch = 1;
1558
0
   } else {
1559
      /* Check that the mono channel actually got better. */
1560
0
      if (after[0] > before[0]) cancel_pitch = 1;
1561
0
   }
1562
   /* If needed, revert to a gain of zero. */
1563
0
   if (cancel_pitch) {
1564
0
      c=0; do {
1565
0
         int offset = mode->shortMdctSize-overlap;
1566
0
         OPUS_COPY(in+c*(N+overlap)+overlap, pre[c]+max_period, N);
1567
0
         comb_filter(in+c*(N+overlap)+overlap+offset, pre[c]+max_period+offset,
1568
0
                     st->prefilter_period, pitch_index, overlap, -st->prefilter_gain, -0,
1569
0
                     st->prefilter_tapset, prefilter_tapset, mode->window, overlap, st->arch);
1570
0
      } while (++c<CC);
1571
0
      gain1 = 0;
1572
0
      pf_on = 0;
1573
0
      qg = 0;
1574
0
   }
1575
1576
0
   c=0; do {
1577
0
      OPUS_COPY(st->in_mem+c*(overlap), in+c*(N+overlap)+N, overlap);
1578
1579
0
      if (N>max_period)
1580
0
      {
1581
0
         OPUS_COPY(prefilter_mem+c*max_period, pre[c]+N, max_period);
1582
0
      } else {
1583
0
         OPUS_MOVE(prefilter_mem+c*max_period, prefilter_mem+c*max_period+N, max_period-N);
1584
0
         OPUS_COPY(prefilter_mem+c*max_period+max_period-N, pre[c]+max_period, N);
1585
0
      }
1586
0
   } while (++c<CC);
1587
1588
0
   RESTORE_STACK;
1589
0
   *gain = gain1;
1590
0
   *pitch = pitch_index;
1591
0
   *qgain = qg;
1592
0
   return pf_on;
1593
0
}
1594
1595
static int compute_vbr(const CELTMode *mode, AnalysisInfo *analysis, opus_int32 base_target,
1596
      int LM, opus_int32 bitrate, int lastCodedBands, int C, int intensity,
1597
      int constrained_vbr, opus_val16 stereo_saving, int tot_boost,
1598
      opus_val16 tf_estimate, int pitch_change, celt_glog maxDepth,
1599
      int lfe, int has_surround_mask, celt_glog surround_masking,
1600
      celt_glog temporal_vbr ARG_QEXT(int enable_qext))
1601
0
{
1602
   /* The target rate in 8th bits per frame */
1603
0
   opus_int32 target;
1604
0
   int coded_bins;
1605
0
   int coded_bands;
1606
0
   opus_val16 tf_calibration;
1607
0
   int nbEBands;
1608
0
   const opus_int16 *eBands;
1609
1610
0
   nbEBands = mode->nbEBands;
1611
0
   eBands = mode->eBands;
1612
1613
0
   coded_bands = lastCodedBands ? lastCodedBands : nbEBands;
1614
0
   coded_bins = eBands[coded_bands]<<LM;
1615
0
   if (C==2)
1616
0
      coded_bins += eBands[IMIN(intensity, coded_bands)]<<LM;
1617
1618
0
   target = base_target;
1619
1620
   /*printf("%f %f %f %f %d %d ", st->analysis.activity, st->analysis.tonality, tf_estimate, st->stereo_saving, tot_boost, coded_bands);*/
1621
0
#ifndef DISABLE_FLOAT_API
1622
0
   if (analysis->valid && analysis->activity<.4)
1623
0
      target -= (opus_int32)((coded_bins<<BITRES)*(.4f-analysis->activity));
1624
0
#endif
1625
   /* Stereo savings */
1626
0
   if (C==2)
1627
0
   {
1628
0
      int coded_stereo_bands;
1629
0
      int coded_stereo_dof;
1630
0
      opus_val16 max_frac;
1631
0
      coded_stereo_bands = IMIN(intensity, coded_bands);
1632
0
      coded_stereo_dof = (eBands[coded_stereo_bands]<<LM)-coded_stereo_bands;
1633
      /* Maximum fraction of the bits we can save if the signal is mono. */
1634
0
      max_frac = DIV32_16(MULT16_16(QCONST16(0.8f, 15), coded_stereo_dof), coded_bins);
1635
0
      stereo_saving = MIN16(stereo_saving, QCONST16(1.f, 8));
1636
      /*printf("%d %d %d ", coded_stereo_dof, coded_bins, tot_boost);*/
1637
0
      target -= (opus_int32)MIN32(MULT16_32_Q15(max_frac,target),
1638
0
                      SHR32(MULT16_16(stereo_saving-QCONST16(0.1f,8),(coded_stereo_dof<<BITRES)),8));
1639
0
   }
1640
   /* Boost the rate according to dynalloc (minus the dynalloc average for calibration). */
1641
0
   target += tot_boost-(19<<LM);
1642
   /* Apply transient boost, compensating for average boost. */
1643
0
   tf_calibration = QCONST16(0.044f,14);
1644
0
   target += (opus_int32)SHL32(MULT16_32_Q15(tf_estimate-tf_calibration, target),1);
1645
1646
0
#ifndef DISABLE_FLOAT_API
1647
   /* Apply tonality boost */
1648
0
   if (analysis->valid && !lfe)
1649
0
   {
1650
0
      opus_int32 tonal_target;
1651
0
      float tonal;
1652
1653
      /* Tonality boost (compensating for the average). */
1654
0
      tonal = MAX16(0.f,analysis->tonality-.15f)-0.12f;
1655
0
      tonal_target = target + (opus_int32)((coded_bins<<BITRES)*1.2f*tonal);
1656
0
      if (pitch_change)
1657
0
         tonal_target +=  (opus_int32)((coded_bins<<BITRES)*.8f);
1658
      /*printf("%f %f ", analysis->tonality, tonal);*/
1659
0
      target = tonal_target;
1660
0
   }
1661
#else
1662
   (void)analysis;
1663
   (void)pitch_change;
1664
#endif
1665
1666
0
   if (has_surround_mask&&!lfe)
1667
0
   {
1668
0
      opus_int32 surround_target = target + (opus_int32)SHR32(MULT16_16(SHR32(surround_masking,DB_SHIFT-10),coded_bins<<BITRES), 10);
1669
      /*printf("%f %d %d %d %d %d %d ", surround_masking, coded_bins, st->end, st->intensity, surround_target, target, st->bitrate);*/
1670
0
      target = IMAX(target/4, surround_target);
1671
0
   }
1672
1673
0
   {
1674
0
      opus_int32 floor_depth;
1675
0
      int bins;
1676
0
      bins = eBands[nbEBands-2]<<LM;
1677
#ifdef ENABLE_QEXT
1678
      if (enable_qext) bins  = mode->shortMdctSize<<LM;
1679
#endif
1680
      /*floor_depth = SHR32(MULT16_16((C*bins<<BITRES),celt_log2(SHL32(MAX16(1,sample_max),13))), DB_SHIFT);*/
1681
0
      floor_depth = (opus_int32)SHR32(MULT16_32_Q15((C*bins<<BITRES),maxDepth), DB_SHIFT-15);
1682
0
      floor_depth = IMAX(floor_depth, target>>2);
1683
0
      target = IMIN(target, floor_depth);
1684
      /*printf("%f %d\n", maxDepth, floor_depth);*/
1685
0
   }
1686
1687
   /* Make VBR less aggressive for constrained VBR because we can't keep a higher bitrate
1688
      for long. Needs tuning. */
1689
0
   if ((!has_surround_mask||lfe) && constrained_vbr)
1690
0
   {
1691
0
      target = base_target + (opus_int32)MULT16_32_Q15(QCONST16(0.67f, 15), target-base_target);
1692
0
   }
1693
1694
0
   if (!has_surround_mask && tf_estimate < QCONST16(.2f, 14))
1695
0
   {
1696
0
      opus_val16 amount;
1697
0
      opus_val16 tvbr_factor;
1698
0
      amount = MULT16_16_Q15(QCONST16(.0000031f, 30), IMAX(0, IMIN(32000, 96000-bitrate)));
1699
0
      tvbr_factor = SHR32(MULT16_16(SHR32(temporal_vbr, DB_SHIFT-10), amount), 10);
1700
0
      target += (opus_int32)MULT16_32_Q15(tvbr_factor, target);
1701
0
   }
1702
1703
   /* Don't allow more than doubling the rate */
1704
0
   target = IMIN(2*base_target, target);
1705
1706
0
   return target;
1707
0
}
1708
1709
#ifdef ENABLE_QEXT
1710
static void encode_qext_stereo_params(ec_enc *ec, int qext_end, int qext_intensity, int qext_dual_stereo) {
1711
   ec_enc_uint(ec, qext_intensity, qext_end+1);
1712
   if (qext_intensity != 0) ec_enc_bit_logp(ec, qext_dual_stereo, 1);
1713
}
1714
#endif
1715
1716
int celt_encode_with_ec(CELTEncoder * OPUS_RESTRICT st, const opus_res * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes, ec_enc *enc)
1717
0
{
1718
0
   int i, c, N;
1719
0
   opus_int32 bits;
1720
0
   ec_enc _enc;
1721
0
   VARDECL(celt_sig, in);
1722
0
   VARDECL(celt_sig, freq);
1723
0
   VARDECL(celt_norm, X);
1724
0
   VARDECL(celt_ener, bandE);
1725
0
   VARDECL(celt_glog, bandLogE);
1726
0
   VARDECL(celt_glog, bandLogE2);
1727
0
   VARDECL(int, fine_quant);
1728
0
   VARDECL(celt_glog, error);
1729
0
   VARDECL(int, pulses);
1730
0
   VARDECL(int, cap);
1731
0
   VARDECL(int, offsets);
1732
0
   VARDECL(int, importance);
1733
0
   VARDECL(int, spread_weight);
1734
0
   VARDECL(int, fine_priority);
1735
0
   VARDECL(int, tf_res);
1736
0
   VARDECL(unsigned char, collapse_masks);
1737
0
   celt_sig *prefilter_mem;
1738
0
   celt_glog *oldBandE, *oldLogE, *oldLogE2, *energyError;
1739
0
   int shortBlocks=0;
1740
0
   int isTransient=0;
1741
0
   const int CC = st->channels;
1742
0
   const int C = st->stream_channels;
1743
0
   int LM, M;
1744
0
   int tf_select;
1745
0
   int nbFilledBytes, nbAvailableBytes;
1746
0
   opus_int32 min_allowed;
1747
0
   int start;
1748
0
   int end;
1749
0
   int effEnd;
1750
0
   int codedBands;
1751
0
   int alloc_trim;
1752
0
   int pitch_index=COMBFILTER_MINPERIOD;
1753
0
   opus_val16 gain1 = 0;
1754
0
   int dual_stereo=0;
1755
0
   int effectiveBytes;
1756
0
   int dynalloc_logp;
1757
0
   opus_int32 vbr_rate;
1758
0
   opus_int32 total_bits;
1759
0
   opus_int32 total_boost;
1760
0
   opus_int32 balance;
1761
0
   opus_int32 tell;
1762
0
   opus_int32 tell0_frac;
1763
0
   int prefilter_tapset=0;
1764
0
   int pf_on;
1765
0
   int anti_collapse_rsv;
1766
0
   int anti_collapse_on=0;
1767
0
   int silence=0;
1768
0
   int tf_chan = 0;
1769
0
   opus_val16 tf_estimate;
1770
0
   int pitch_change=0;
1771
0
   opus_int32 tot_boost;
1772
0
   opus_val32 sample_max;
1773
0
   celt_glog maxDepth;
1774
0
   const OpusCustomMode *mode;
1775
0
   int nbEBands;
1776
0
   int overlap;
1777
0
   const opus_int16 *eBands;
1778
0
   int secondMdct;
1779
0
   int signalBandwidth;
1780
0
   int transient_got_disabled=0;
1781
0
   celt_glog surround_masking=0;
1782
0
   celt_glog temporal_vbr=0;
1783
0
   celt_glog surround_trim = 0;
1784
0
   opus_int32 equiv_rate;
1785
0
   int hybrid;
1786
0
   int weak_transient = 0;
1787
0
   int enable_tf_analysis;
1788
0
   opus_val16 tone_freq=-1;
1789
0
   opus_val32 toneishness=0;
1790
0
   VARDECL(celt_glog, surround_dynalloc);
1791
0
   int qext_bytes=0;
1792
0
   int packet_size_cap = 1275;
1793
#ifdef ENABLE_QEXT
1794
   int qext_scale;
1795
   int qext_end=0;
1796
   int qext_intensity=0;
1797
   int qext_dual_stereo=0;
1798
   int padding_len_bytes=0;
1799
   unsigned char *ext_payload;
1800
   opus_int32 qext_bits;
1801
   ec_enc ext_enc;
1802
   VARDECL(int, extra_quant);
1803
   VARDECL(int, extra_pulses);
1804
   VARDECL(celt_glog, error_bak);
1805
   const CELTMode *qext_mode = NULL;
1806
   CELTMode qext_mode_struct;
1807
   celt_ener qext_bandE[2*NB_QEXT_BANDS];
1808
   celt_glog qext_bandLogE[2*NB_QEXT_BANDS];
1809
   celt_glog *qext_oldBandE=NULL;
1810
   celt_glog qext_error[2*NB_QEXT_BANDS];
1811
#endif
1812
0
   ALLOC_STACK;
1813
1814
0
   mode = st->mode;
1815
0
   nbEBands = mode->nbEBands;
1816
0
   overlap = mode->overlap;
1817
0
   eBands = mode->eBands;
1818
0
   start = st->start;
1819
0
   end = st->end;
1820
0
   hybrid = start != 0;
1821
0
   tf_estimate = 0;
1822
0
   if (nbCompressedBytes<2 || pcm==NULL)
1823
0
   {
1824
0
      RESTORE_STACK;
1825
0
      return OPUS_BAD_ARG;
1826
0
   }
1827
1828
0
   frame_size *= st->upsample;
1829
0
   for (LM=0;LM<=mode->maxLM;LM++)
1830
0
      if (mode->shortMdctSize<<LM==frame_size)
1831
0
         break;
1832
0
   if (LM>mode->maxLM)
1833
0
   {
1834
0
      RESTORE_STACK;
1835
0
      return OPUS_BAD_ARG;
1836
0
   }
1837
0
   M=1<<LM;
1838
0
   N = M*mode->shortMdctSize;
1839
1840
#ifdef ENABLE_QEXT
1841
   qext_scale = st->qext_scale;
1842
   if (st->enable_qext) packet_size_cap = QEXT_PACKET_SIZE_CAP;
1843
#endif
1844
1845
0
   prefilter_mem = st->in_mem+CC*(overlap);
1846
0
   oldBandE = (celt_glog*)(st->in_mem+CC*(overlap+QEXT_SCALE(COMBFILTER_MAXPERIOD)));
1847
0
   oldLogE = oldBandE + CC*nbEBands;
1848
0
   oldLogE2 = oldLogE + CC*nbEBands;
1849
0
   energyError = oldLogE2 + CC*nbEBands;
1850
1851
0
   if (enc==NULL)
1852
0
   {
1853
0
      tell0_frac=tell=1;
1854
0
      nbFilledBytes=0;
1855
0
   } else {
1856
0
      tell0_frac=ec_tell_frac(enc);
1857
0
      tell=ec_tell(enc);
1858
0
      nbFilledBytes=(tell+4)>>3;
1859
0
   }
1860
1861
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
1862
   if (st->signalling && enc==NULL)
1863
   {
1864
      int tmp = (mode->effEBands-end)>>1;
1865
      end = st->end = IMAX(1, mode->effEBands-tmp);
1866
      compressed[0] = tmp<<5;
1867
      compressed[0] |= LM<<3;
1868
      compressed[0] |= (C==2)<<2;
1869
      /* Convert "standard mode" to Opus header */
1870
# ifndef ENABLE_QEXT
1871
      if (mode->Fs==48000 && mode->shortMdctSize==120)
1872
# endif
1873
      {
1874
         int c0 = toOpus(compressed[0]);
1875
         if (c0<0)
1876
         {
1877
            RESTORE_STACK;
1878
            return OPUS_BAD_ARG;
1879
         }
1880
         compressed[0] = c0;
1881
      }
1882
      compressed++;
1883
      nbCompressedBytes--;
1884
   }
1885
#else
1886
0
   celt_assert(st->signalling==0);
1887
0
#endif
1888
1889
   /* Can't produce more than 1275 output bytes for the main payload, plus any QEXT extra data. */
1890
0
   nbCompressedBytes = IMIN(nbCompressedBytes,packet_size_cap);
1891
1892
0
   if (st->vbr && st->bitrate!=OPUS_BITRATE_MAX)
1893
0
   {
1894
0
      opus_int32 den=mode->Fs>>(BITRES+2);
1895
0
      vbr_rate=((st->bitrate*(frame_size>>2))+(den>>1))/den;
1896
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
1897
      if (st->signalling)
1898
         vbr_rate -= 8<<BITRES;
1899
#endif
1900
0
      effectiveBytes = vbr_rate>>(3+BITRES);
1901
0
   } else {
1902
0
      opus_int32 tmp;
1903
0
      vbr_rate = 0;
1904
0
      tmp = st->bitrate*frame_size;
1905
0
      if (tell>1)
1906
0
         tmp += tell*mode->Fs;
1907
0
      if (st->bitrate!=OPUS_BITRATE_MAX)
1908
0
      {
1909
0
         nbCompressedBytes = IMAX(2, IMIN(nbCompressedBytes,
1910
0
               (tmp+4*mode->Fs)/(8*mode->Fs)-!!st->signalling));
1911
0
         if (enc != NULL)
1912
0
            ec_enc_shrink(enc, nbCompressedBytes);
1913
0
      }
1914
0
      effectiveBytes = nbCompressedBytes - nbFilledBytes;
1915
0
   }
1916
0
   nbAvailableBytes = nbCompressedBytes - nbFilledBytes;
1917
0
   equiv_rate = ((opus_int32)nbCompressedBytes*8*50 << (3-LM)) - (40*C+20)*((400>>LM) - 50);
1918
0
   if (st->bitrate != OPUS_BITRATE_MAX)
1919
0
      equiv_rate = IMIN(equiv_rate, st->bitrate - (40*C+20)*((400>>LM) - 50));
1920
1921
0
   if (enc==NULL)
1922
0
   {
1923
0
      ec_enc_init(&_enc, compressed, nbCompressedBytes);
1924
0
      enc = &_enc;
1925
0
   }
1926
1927
0
   if (vbr_rate>0)
1928
0
   {
1929
      /* Computes the max bit-rate allowed in VBR mode to avoid violating the
1930
          target rate and buffering.
1931
         We must do this up front so that bust-prevention logic triggers
1932
          correctly if we don't have enough bits. */
1933
0
      if (st->constrained_vbr)
1934
0
      {
1935
0
         opus_int32 vbr_bound;
1936
0
         opus_int32 max_allowed;
1937
         /* We could use any multiple of vbr_rate as bound (depending on the
1938
             delay).
1939
            This is clamped to ensure we use at least two bytes if the encoder
1940
             was entirely empty, but to allow 0 in hybrid mode. */
1941
0
         vbr_bound = vbr_rate;
1942
0
         max_allowed = IMIN(IMAX(tell==1?2:0,
1943
0
               (vbr_rate+vbr_bound-st->vbr_reservoir)>>(BITRES+3)),
1944
0
               nbAvailableBytes);
1945
0
         if(max_allowed < nbAvailableBytes)
1946
0
         {
1947
0
            nbCompressedBytes = nbFilledBytes+max_allowed;
1948
0
            nbAvailableBytes = max_allowed;
1949
0
            ec_enc_shrink(enc, nbCompressedBytes);
1950
0
         }
1951
0
      }
1952
0
   }
1953
0
   total_bits = nbCompressedBytes*8;
1954
1955
0
   effEnd = end;
1956
0
   if (effEnd > mode->effEBands)
1957
0
      effEnd = mode->effEBands;
1958
1959
0
   ALLOC(in, CC*(N+overlap), celt_sig);
1960
1961
0
   sample_max=MAX32(st->overlap_max, celt_maxabs_res(pcm, C*(N-overlap)/st->upsample));
1962
0
   st->overlap_max=celt_maxabs_res(pcm+C*(N-overlap)/st->upsample, C*overlap/st->upsample);
1963
0
   sample_max=MAX32(sample_max, st->overlap_max);
1964
#ifdef FIXED_POINT
1965
   silence = (sample_max==0);
1966
#else
1967
0
   silence = (sample_max <= (opus_val16)1/(1<<st->lsb_depth));
1968
0
#endif
1969
#ifdef FUZZING
1970
   if ((rand()&0x3F)==0)
1971
      silence = 1;
1972
#endif
1973
0
   if (tell==1)
1974
0
      ec_enc_bit_logp(enc, silence, 15);
1975
0
   else
1976
0
      silence=0;
1977
0
   if (silence)
1978
0
   {
1979
      /*In VBR mode there is no need to send more than the minimum. */
1980
0
      if (vbr_rate>0)
1981
0
      {
1982
0
         effectiveBytes=nbCompressedBytes=IMIN(nbCompressedBytes, nbFilledBytes+2);
1983
0
         total_bits=nbCompressedBytes*8;
1984
0
         nbAvailableBytes=2;
1985
0
         ec_enc_shrink(enc, nbCompressedBytes);
1986
0
      }
1987
#ifdef ENABLE_QEXT
1988
      else if (st->enable_qext) {
1989
         nbCompressedBytes = IMIN(nbCompressedBytes, 1275);
1990
         nbAvailableBytes = nbCompressedBytes - nbFilledBytes;
1991
         total_bits = nbCompressedBytes*8;
1992
         ec_enc_shrink(enc, nbCompressedBytes);
1993
      }
1994
#endif
1995
      /* Pretend we've filled all the remaining bits with zeros
1996
            (that's what the initialiser did anyway) */
1997
0
      tell = nbCompressedBytes*8;
1998
0
      enc->nbits_total+=tell-ec_tell(enc);
1999
0
   }
2000
0
   c=0; do {
2001
0
      int need_clip=0;
2002
0
#ifndef FIXED_POINT
2003
0
      need_clip = st->clip && sample_max>65536.f;
2004
0
#endif
2005
0
      celt_preemphasis(pcm+c, in+c*(N+overlap)+overlap, N, CC, st->upsample,
2006
0
                  mode->preemph, st->preemph_memE+c, need_clip);
2007
0
      OPUS_COPY(in+c*(N+overlap), &prefilter_mem[(1+c)*QEXT_SCALE(COMBFILTER_MAXPERIOD)-overlap], overlap);
2008
0
   } while (++c<CC);
2009
2010
2011
0
   tone_freq = tone_detect(in, CC, N+overlap, &toneishness, mode->Fs);
2012
0
   isTransient = 0;
2013
0
   shortBlocks = 0;
2014
0
   if (st->complexity >= 1 && !st->lfe)
2015
0
   {
2016
      /* Reduces the likelihood of energy instability on fricatives at low bitrate
2017
         in hybrid mode. It seems like we still want to have real transients on vowels
2018
         though (small SILK quantization offset value). */
2019
0
      int allow_weak_transients = hybrid && effectiveBytes<15 && st->silk_info.signalType != 2;
2020
0
      isTransient = transient_analysis(in, N+overlap, CC,
2021
0
            &tf_estimate, &tf_chan, allow_weak_transients, &weak_transient, tone_freq, toneishness);
2022
0
   }
2023
0
   toneishness = MIN32(toneishness, QCONST32(1.f, 29)-SHL32(tf_estimate, 15));
2024
   /* Find pitch period and gain */
2025
0
   {
2026
0
      int enabled;
2027
0
      int qg;
2028
0
      enabled = ((st->lfe&&nbAvailableBytes>3) || nbAvailableBytes>12*C) && !hybrid && !silence && tell+16<=total_bits && !st->disable_pf;
2029
2030
0
      prefilter_tapset = st->tapset_decision;
2031
0
      pf_on = run_prefilter(st, in, prefilter_mem, CC, N, prefilter_tapset, &pitch_index, &gain1, &qg, enabled, st->complexity, tf_estimate, nbAvailableBytes, &st->analysis, tone_freq, toneishness ARG_QEXT(qext_scale));
2032
0
      if ((gain1 > QCONST16(.4f,15) || st->prefilter_gain > QCONST16(.4f,15)) && (!st->analysis.valid || st->analysis.tonality > .3)
2033
0
            && (pitch_index > 1.26*st->prefilter_period || pitch_index < .79*st->prefilter_period))
2034
0
         pitch_change = 1;
2035
0
      if (pf_on==0)
2036
0
      {
2037
0
         if(!hybrid && tell+16<=total_bits)
2038
0
            ec_enc_bit_logp(enc, 0, 1);
2039
0
      } else {
2040
         /*This block is not gated by a total bits check only because
2041
           of the nbAvailableBytes check above.*/
2042
0
         int octave;
2043
0
         ec_enc_bit_logp(enc, 1, 1);
2044
0
         pitch_index += 1;
2045
0
         octave = EC_ILOG(pitch_index)-5;
2046
0
         ec_enc_uint(enc, octave, 6);
2047
0
         ec_enc_bits(enc, pitch_index-(16<<octave), 4+octave);
2048
0
         pitch_index -= 1;
2049
0
         ec_enc_bits(enc, qg, 3);
2050
0
         ec_enc_icdf(enc, prefilter_tapset, tapset_icdf, 2);
2051
0
      }
2052
0
   }
2053
0
   if (LM>0 && ec_tell(enc)+3<=total_bits)
2054
0
   {
2055
0
      if (isTransient)
2056
0
         shortBlocks = M;
2057
0
   } else {
2058
0
      isTransient = 0;
2059
0
      transient_got_disabled=1;
2060
0
   }
2061
2062
0
   ALLOC(freq, CC*N, celt_sig); /**< Interleaved signal MDCTs */
2063
0
   ALLOC(bandE,nbEBands*CC, celt_ener);
2064
0
   ALLOC(bandLogE,nbEBands*CC, celt_glog);
2065
2066
0
   secondMdct = shortBlocks && st->complexity>=8;
2067
0
   ALLOC(bandLogE2, C*nbEBands, celt_glog);
2068
0
   if (secondMdct)
2069
0
   {
2070
0
      compute_mdcts(mode, 0, in, freq, C, CC, LM, st->upsample, st->arch);
2071
0
      compute_band_energies(mode, freq, bandE, effEnd, C, LM, st->arch);
2072
0
      amp2Log2(mode, effEnd, end, bandE, bandLogE2, C);
2073
0
      for (c=0;c<C;c++)
2074
0
      {
2075
0
         for (i=0;i<end;i++)
2076
0
            bandLogE2[nbEBands*c+i] += HALF32(SHL32(LM, DB_SHIFT));
2077
0
      }
2078
0
   }
2079
2080
0
   compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample, st->arch);
2081
   /* This should catch any NaN in the CELT input. Since we're not supposed to see any (they're filtered
2082
      at the Opus layer), just abort. */
2083
0
   celt_assert(!celt_isnan(freq[0]) && (C==1 || !celt_isnan(freq[N])));
2084
0
   if (CC==2&&C==1)
2085
0
      tf_chan = 0;
2086
0
   compute_band_energies(mode, freq, bandE, effEnd, C, LM, st->arch);
2087
2088
0
   if (st->lfe)
2089
0
   {
2090
0
      for (i=2;i<end;i++)
2091
0
      {
2092
0
         bandE[i] = IMIN(bandE[i], MULT16_32_Q15(QCONST16(1e-4f,15),bandE[0]));
2093
0
         bandE[i] = MAX32(bandE[i], EPSILON);
2094
0
      }
2095
0
   }
2096
0
   amp2Log2(mode, effEnd, end, bandE, bandLogE, C);
2097
2098
0
   ALLOC(surround_dynalloc, C*nbEBands, celt_glog);
2099
0
   OPUS_CLEAR(surround_dynalloc, end);
2100
   /* This computes how much masking takes place between surround channels */
2101
0
   if (!hybrid&&st->energy_mask&&!st->lfe)
2102
0
   {
2103
0
      int mask_end;
2104
0
      int midband;
2105
0
      int count_dynalloc;
2106
0
      opus_val32 mask_avg=0;
2107
0
      opus_val32 diff=0;
2108
0
      int count=0;
2109
0
      mask_end = IMAX(2,st->lastCodedBands);
2110
0
      for (c=0;c<C;c++)
2111
0
      {
2112
0
         for(i=0;i<mask_end;i++)
2113
0
         {
2114
0
            celt_glog mask;
2115
0
            opus_val16 mask16;
2116
0
            mask = MAXG(MING(st->energy_mask[nbEBands*c+i],
2117
0
                   GCONST(.25f)), -GCONST(2.0f));
2118
0
            if (mask > 0)
2119
0
               mask = HALF32(mask);
2120
0
            mask16 = SHR32(mask, DB_SHIFT-10);
2121
0
            mask_avg += MULT16_16(mask16, eBands[i+1]-eBands[i]);
2122
0
            count += eBands[i+1]-eBands[i];
2123
0
            diff += MULT16_16(mask16, 1+2*i-mask_end);
2124
0
         }
2125
0
      }
2126
0
      celt_assert(count>0);
2127
0
      mask_avg = SHL32(DIV32_16(mask_avg,count), DB_SHIFT-10);
2128
0
      mask_avg += GCONST(.2f);
2129
0
      diff = SHL32(diff*6/(C*(mask_end-1)*(mask_end+1)*mask_end), DB_SHIFT-10);
2130
      /* Again, being conservative */
2131
0
      diff = HALF32(diff);
2132
0
      diff = MAX32(MIN32(diff, GCONST(.031f)), -GCONST(.031f));
2133
      /* Find the band that's in the middle of the coded spectrum */
2134
0
      for (midband=0;eBands[midband+1] < eBands[mask_end]/2;midband++);
2135
0
      count_dynalloc=0;
2136
0
      for(i=0;i<mask_end;i++)
2137
0
      {
2138
0
         opus_val32 lin;
2139
0
         celt_glog unmask;
2140
0
         lin = mask_avg + diff*(i-midband);
2141
0
         if (C==2)
2142
0
            unmask = MAXG(st->energy_mask[i], st->energy_mask[nbEBands+i]);
2143
0
         else
2144
0
            unmask = st->energy_mask[i];
2145
0
         unmask = MING(unmask, GCONST(.0f));
2146
0
         unmask -= lin;
2147
0
         if (unmask > GCONST(.25f))
2148
0
         {
2149
0
            surround_dynalloc[i] = unmask - GCONST(.25f);
2150
0
            count_dynalloc++;
2151
0
         }
2152
0
      }
2153
0
      if (count_dynalloc>=3)
2154
0
      {
2155
         /* If we need dynalloc in many bands, it's probably because our
2156
            initial masking rate was too low. */
2157
0
         mask_avg += GCONST(.25f);
2158
0
         if (mask_avg>0)
2159
0
         {
2160
            /* Something went really wrong in the original calculations,
2161
               disabling masking. */
2162
0
            mask_avg = 0;
2163
0
            diff = 0;
2164
0
            OPUS_CLEAR(surround_dynalloc, mask_end);
2165
0
         } else {
2166
0
            for(i=0;i<mask_end;i++)
2167
0
               surround_dynalloc[i] = MAXG(0, surround_dynalloc[i]-GCONST(.25f));
2168
0
         }
2169
0
      }
2170
0
      mask_avg += GCONST(.2f);
2171
      /* Convert to 1/64th units used for the trim */
2172
0
      surround_trim = 64*diff;
2173
      /*printf("%d %d ", mask_avg, surround_trim);*/
2174
0
      surround_masking = mask_avg;
2175
0
   }
2176
   /* Temporal VBR (but not for LFE) */
2177
0
   if (!st->lfe)
2178
0
   {
2179
0
      celt_glog follow=-QCONST32(10.0f, DB_SHIFT-5);
2180
0
      opus_val32 frame_avg=0;
2181
0
      celt_glog offset = shortBlocks?HALF32(SHL32(LM, DB_SHIFT-5)):0;
2182
0
      for(i=start;i<end;i++)
2183
0
      {
2184
0
         follow = MAXG(follow-QCONST32(1.0f, DB_SHIFT-5), SHR32(bandLogE[i],5)-offset);
2185
0
         if (C==2)
2186
0
            follow = MAXG(follow, SHR32(bandLogE[i+nbEBands],5)-offset);
2187
0
         frame_avg += follow;
2188
0
      }
2189
0
      frame_avg /= (end-start);
2190
0
      temporal_vbr = SUB32(SHL32(frame_avg, 5),st->spec_avg);
2191
0
      temporal_vbr = MING(GCONST(3.f), MAXG(-GCONST(1.5f), temporal_vbr));
2192
0
      st->spec_avg += MULT16_32_Q15(QCONST16(.02f, 15), temporal_vbr);
2193
0
   }
2194
   /*for (i=0;i<21;i++)
2195
      printf("%f ", bandLogE[i]);
2196
   printf("\n");*/
2197
2198
0
   if (!secondMdct)
2199
0
   {
2200
0
      OPUS_COPY(bandLogE2, bandLogE, C*nbEBands);
2201
0
   }
2202
2203
   /* Last chance to catch any transient we might have missed in the
2204
      time-domain analysis */
2205
0
   if (LM>0 && ec_tell(enc)+3<=total_bits && !isTransient && st->complexity>=5 && !st->lfe && !hybrid)
2206
0
   {
2207
0
      if (patch_transient_decision(bandLogE, oldBandE, nbEBands, start, end, C))
2208
0
      {
2209
0
         isTransient = 1;
2210
0
         shortBlocks = M;
2211
0
         compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample, st->arch);
2212
0
         compute_band_energies(mode, freq, bandE, effEnd, C, LM, st->arch);
2213
0
         amp2Log2(mode, effEnd, end, bandE, bandLogE, C);
2214
         /* Compensate for the scaling of short vs long mdcts */
2215
0
         for (c=0;c<C;c++)
2216
0
         {
2217
0
            for (i=0;i<end;i++)
2218
0
               bandLogE2[nbEBands*c+i] += HALF32(SHL32(LM, DB_SHIFT));
2219
0
         }
2220
0
         tf_estimate = QCONST16(.2f,14);
2221
0
      }
2222
0
   }
2223
2224
0
   if (LM>0 && ec_tell(enc)+3<=total_bits)
2225
0
      ec_enc_bit_logp(enc, isTransient, 3);
2226
2227
0
   ALLOC(X, C*N, celt_norm);         /**< Interleaved normalised MDCTs */
2228
2229
   /* Band normalisation */
2230
0
   normalise_bands(mode, freq, X, bandE, effEnd, C, M);
2231
2232
0
   enable_tf_analysis = effectiveBytes>=15*C && !hybrid && st->complexity>=2 && !st->lfe && toneishness < QCONST32(.98f, 29);
2233
2234
0
   ALLOC(offsets, nbEBands, int);
2235
0
   ALLOC(importance, nbEBands, int);
2236
0
   ALLOC(spread_weight, nbEBands, int);
2237
2238
0
   maxDepth = dynalloc_analysis(bandLogE, bandLogE2, oldBandE, nbEBands, start, end, C, offsets,
2239
0
         st->lsb_depth, mode->logN, isTransient, st->vbr, st->constrained_vbr,
2240
0
         eBands, LM, effectiveBytes, &tot_boost, st->lfe, surround_dynalloc, &st->analysis, importance, spread_weight, tone_freq, toneishness ARG_QEXT(qext_scale));
2241
2242
0
   ALLOC(tf_res, nbEBands, int);
2243
   /* Disable variable tf resolution for hybrid and at very low bitrate */
2244
0
   if (enable_tf_analysis)
2245
0
   {
2246
0
      int lambda;
2247
0
      lambda = IMAX(80, 20480/effectiveBytes + 2);
2248
0
      tf_select = tf_analysis(mode, effEnd, isTransient, tf_res, lambda, X, N, LM, tf_estimate, tf_chan, importance);
2249
0
      for (i=effEnd;i<end;i++)
2250
0
         tf_res[i] = tf_res[effEnd-1];
2251
0
   } else if (hybrid && weak_transient)
2252
0
   {
2253
      /* For weak transients, we rely on the fact that improving time resolution using
2254
         TF on a long window is imperfect and will not result in an energy collapse at
2255
         low bitrate. */
2256
0
      for (i=0;i<end;i++)
2257
0
         tf_res[i] = 1;
2258
0
      tf_select=0;
2259
0
   } else if (hybrid && effectiveBytes<15 && st->silk_info.signalType != 2)
2260
0
   {
2261
      /* For low bitrate hybrid, we force temporal resolution to 5 ms rather than 2.5 ms. */
2262
0
      for (i=0;i<end;i++)
2263
0
         tf_res[i] = 0;
2264
0
      tf_select=isTransient;
2265
0
   } else {
2266
0
      for (i=0;i<end;i++)
2267
0
         tf_res[i] = isTransient;
2268
0
      tf_select=0;
2269
0
   }
2270
2271
0
   ALLOC(error, C*nbEBands, celt_glog);
2272
0
   c=0;
2273
0
   do {
2274
0
      for (i=start;i<end;i++)
2275
0
      {
2276
         /* When the energy is stable, slightly bias energy quantization towards
2277
            the previous error to make the gain more stable (a constant offset is
2278
            better than fluctuations). */
2279
0
         if (ABS32(SUB32(bandLogE[i+c*nbEBands], oldBandE[i+c*nbEBands])) < GCONST(2.f))
2280
0
         {
2281
0
            bandLogE[i+c*nbEBands] -= MULT16_32_Q15(QCONST16(0.25f, 15), energyError[i+c*nbEBands]);
2282
0
         }
2283
0
      }
2284
0
   } while (++c < C);
2285
0
   quant_coarse_energy(mode, start, end, effEnd, bandLogE,
2286
0
         oldBandE, total_bits, error, enc,
2287
0
         C, LM, nbAvailableBytes, st->force_intra,
2288
0
         &st->delayedIntra, st->complexity >= 4, st->loss_rate, st->lfe);
2289
2290
0
   tf_encode(start, end, isTransient, tf_res, LM, tf_select, enc);
2291
2292
0
   if (ec_tell(enc)+4<=total_bits)
2293
0
   {
2294
0
      if (st->lfe)
2295
0
      {
2296
0
         st->tapset_decision = 0;
2297
0
         st->spread_decision = SPREAD_NORMAL;
2298
0
      } else if (hybrid)
2299
0
      {
2300
0
         if (st->complexity == 0)
2301
0
            st->spread_decision = SPREAD_NONE;
2302
0
         else if (isTransient)
2303
0
            st->spread_decision = SPREAD_NORMAL;
2304
0
         else
2305
0
            st->spread_decision = SPREAD_AGGRESSIVE;
2306
0
      } else if (shortBlocks || st->complexity < 3 || nbAvailableBytes < 10*C)
2307
0
      {
2308
0
         if (st->complexity == 0)
2309
0
            st->spread_decision = SPREAD_NONE;
2310
0
         else
2311
0
            st->spread_decision = SPREAD_NORMAL;
2312
0
      } else {
2313
         /* Disable new spreading+tapset estimator until we can show it works
2314
            better than the old one. So far it seems like spreading_decision()
2315
            works best. */
2316
#if 0
2317
         if (st->analysis.valid)
2318
         {
2319
            static const opus_val16 spread_thresholds[3] = {-QCONST16(.6f, 15), -QCONST16(.2f, 15), -QCONST16(.07f, 15)};
2320
            static const opus_val16 spread_histeresis[3] = {QCONST16(.15f, 15), QCONST16(.07f, 15), QCONST16(.02f, 15)};
2321
            static const opus_val16 tapset_thresholds[2] = {QCONST16(.0f, 15), QCONST16(.15f, 15)};
2322
            static const opus_val16 tapset_histeresis[2] = {QCONST16(.1f, 15), QCONST16(.05f, 15)};
2323
            st->spread_decision = hysteresis_decision(-st->analysis.tonality, spread_thresholds, spread_histeresis, 3, st->spread_decision);
2324
            st->tapset_decision = hysteresis_decision(st->analysis.tonality_slope, tapset_thresholds, tapset_histeresis, 2, st->tapset_decision);
2325
         } else
2326
#endif
2327
0
         {
2328
0
            st->spread_decision = spreading_decision(mode, X,
2329
0
                  &st->tonal_average, st->spread_decision, &st->hf_average,
2330
0
                  &st->tapset_decision, pf_on&&!shortBlocks, effEnd, C, M, spread_weight);
2331
0
         }
2332
         /*printf("%d %d\n", st->tapset_decision, st->spread_decision);*/
2333
         /*printf("%f %d %f %d\n\n", st->analysis.tonality, st->spread_decision, st->analysis.tonality_slope, st->tapset_decision);*/
2334
0
      }
2335
0
      ec_enc_icdf(enc, st->spread_decision, spread_icdf, 5);
2336
0
   } else {
2337
0
      st->spread_decision = SPREAD_NORMAL;
2338
0
   }
2339
2340
   /* For LFE, everything interesting is in the first band */
2341
0
   if (st->lfe)
2342
0
      offsets[0] = IMIN(8, effectiveBytes/3);
2343
0
   ALLOC(cap, nbEBands, int);
2344
0
   init_caps(mode,cap,LM,C);
2345
2346
0
   dynalloc_logp = 6;
2347
0
   total_bits<<=BITRES;
2348
0
   total_boost = 0;
2349
0
   tell = ec_tell_frac(enc);
2350
0
   for (i=start;i<end;i++)
2351
0
   {
2352
0
      int width, quanta;
2353
0
      int dynalloc_loop_logp;
2354
0
      int boost;
2355
0
      int j;
2356
0
      width = C*(eBands[i+1]-eBands[i])<<LM;
2357
      /* quanta is 6 bits, but no more than 1 bit/sample
2358
         and no less than 1/8 bit/sample */
2359
0
      quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
2360
0
      dynalloc_loop_logp = dynalloc_logp;
2361
0
      boost = 0;
2362
0
      for (j = 0; tell+(dynalloc_loop_logp<<BITRES) < total_bits-total_boost
2363
0
            && boost < cap[i]; j++)
2364
0
      {
2365
0
         int flag;
2366
0
         flag = j<offsets[i];
2367
0
         ec_enc_bit_logp(enc, flag, dynalloc_loop_logp);
2368
0
         tell = ec_tell_frac(enc);
2369
0
         if (!flag)
2370
0
            break;
2371
0
         boost += quanta;
2372
0
         total_boost += quanta;
2373
0
         dynalloc_loop_logp = 1;
2374
0
      }
2375
      /* Making dynalloc more likely */
2376
0
      if (j)
2377
0
         dynalloc_logp = IMAX(2, dynalloc_logp-1);
2378
0
      offsets[i] = boost;
2379
0
   }
2380
2381
0
   if (C==2)
2382
0
   {
2383
0
      static const opus_val16 intensity_thresholds[21]=
2384
      /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19  20  off*/
2385
0
        {  1, 2, 3, 4, 5, 6, 7, 8,16,24,36,44,50,56,62,67,72,79,88,106,134};
2386
0
      static const opus_val16 intensity_histeresis[21]=
2387
0
        {  1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 5, 6,  8, 8};
2388
2389
      /* Always use MS for 2.5 ms frames until we can do a better analysis */
2390
0
      if (LM!=0)
2391
0
         dual_stereo = stereo_analysis(mode, X, LM, N);
2392
2393
0
      st->intensity = hysteresis_decision((opus_val16)(equiv_rate/1000),
2394
0
            intensity_thresholds, intensity_histeresis, 21, st->intensity);
2395
0
      st->intensity = IMIN(end,IMAX(start, st->intensity));
2396
0
   }
2397
2398
0
   alloc_trim = 5;
2399
0
   if (tell+(6<<BITRES) <= total_bits - total_boost)
2400
0
   {
2401
0
      if (start > 0 || st->lfe)
2402
0
      {
2403
0
         st->stereo_saving = 0;
2404
0
         alloc_trim = 5;
2405
0
      } else {
2406
0
         alloc_trim = alloc_trim_analysis(mode, X, bandLogE,
2407
0
            end, LM, C, N, &st->analysis, &st->stereo_saving, tf_estimate,
2408
0
            st->intensity, surround_trim, equiv_rate, st->arch);
2409
0
      }
2410
0
      ec_enc_icdf(enc, alloc_trim, trim_icdf, 7);
2411
0
      tell = ec_tell_frac(enc);
2412
0
   }
2413
2414
   /* In VBR mode the frame size must not be reduced so much that it would
2415
       result in the encoder running out of bits.
2416
      The margin of 2 bytes ensures that none of the bust-prevention logic
2417
       in the decoder will have triggered so far. */
2418
0
   min_allowed = ((tell+total_boost+(1<<(BITRES+3))-1)>>(BITRES+3)) + 2;
2419
   /* Take into account the 37 bits we need to have left in the packet to
2420
      signal a redundant frame in hybrid mode. Creating a shorter packet would
2421
      create an entropy coder desync. */
2422
0
   if (hybrid)
2423
0
      min_allowed = IMAX(min_allowed, (tell0_frac+(37<<BITRES)+total_boost+(1<<(BITRES+3))-1)>>(BITRES+3));
2424
   /* Variable bitrate */
2425
0
   if (vbr_rate>0)
2426
0
   {
2427
0
     opus_val16 alpha;
2428
0
     opus_int32 delta;
2429
     /* The target rate in 8th bits per frame */
2430
0
     opus_int32 target, base_target;
2431
0
     int lm_diff = mode->maxLM - LM;
2432
2433
     /* Don't attempt to use more than 510 kb/s, even for frames smaller than 20 ms.
2434
        The CELT allocator will just not be able to use more than that anyway. */
2435
0
     nbCompressedBytes = IMIN(nbCompressedBytes,packet_size_cap>>(3-LM));
2436
0
     if (!hybrid)
2437
0
     {
2438
0
        base_target = vbr_rate - ((40*C+20)<<BITRES);
2439
0
     } else {
2440
0
        base_target = IMAX(0, vbr_rate - ((9*C+4)<<BITRES));
2441
0
     }
2442
2443
0
     if (st->constrained_vbr)
2444
0
        base_target += (st->vbr_offset>>lm_diff);
2445
2446
0
     if (!hybrid)
2447
0
     {
2448
0
        target = compute_vbr(mode, &st->analysis, base_target, LM, equiv_rate,
2449
0
           st->lastCodedBands, C, st->intensity, st->constrained_vbr,
2450
0
           st->stereo_saving, tot_boost, tf_estimate, pitch_change, maxDepth,
2451
0
           st->lfe, st->energy_mask!=NULL, surround_masking,
2452
0
           temporal_vbr ARG_QEXT(st->enable_qext));
2453
0
     } else {
2454
0
        target = base_target;
2455
        /* Tonal frames (offset<100) need more bits than noisy (offset>100) ones. */
2456
0
        if (st->silk_info.offset < 100) target += 12 << BITRES >> (3-LM);
2457
0
        if (st->silk_info.offset > 100) target -= 18 << BITRES >> (3-LM);
2458
        /* Boosting bitrate on transients and vowels with significant temporal
2459
           spikes. */
2460
0
        target += (opus_int32)MULT16_16_Q14(tf_estimate-QCONST16(.25f,14), (50<<BITRES));
2461
        /* If we have a strong transient, let's make sure it has enough bits to code
2462
           the first two bands, so that it can use folding rather than noise. */
2463
0
        if (tf_estimate > QCONST16(.7f,14))
2464
0
           target = IMAX(target, 50<<BITRES);
2465
0
     }
2466
     /* The current offset is removed from the target and the space used
2467
        so far is added*/
2468
0
     target=target+tell;
2469
2470
0
     nbAvailableBytes = (target+(1<<(BITRES+2)))>>(BITRES+3);
2471
0
     nbAvailableBytes = IMAX(min_allowed,nbAvailableBytes);
2472
0
     nbAvailableBytes = IMIN(nbCompressedBytes,nbAvailableBytes);
2473
2474
     /* By how much did we "miss" the target on that frame */
2475
0
     delta = target - vbr_rate;
2476
2477
0
     target=nbAvailableBytes<<(BITRES+3);
2478
2479
     /*If the frame is silent we don't adjust our drift, otherwise
2480
       the encoder will shoot to very high rates after hitting a
2481
       span of silence, but we do allow the bitres to refill.
2482
       This means that we'll undershoot our target in CVBR/VBR modes
2483
       on files with lots of silence. */
2484
0
     if(silence)
2485
0
     {
2486
0
       nbAvailableBytes = 2;
2487
0
       target = 2*8<<BITRES;
2488
0
       delta = 0;
2489
0
     }
2490
2491
0
     if (st->vbr_count < 970)
2492
0
     {
2493
0
        st->vbr_count++;
2494
0
        alpha = celt_rcp(SHL32(EXTEND32(st->vbr_count+20),16));
2495
0
     } else
2496
0
        alpha = QCONST16(.001f,15);
2497
     /* How many bits have we used in excess of what we're allowed */
2498
0
     if (st->constrained_vbr)
2499
0
        st->vbr_reservoir += target - vbr_rate;
2500
     /*printf ("%d\n", st->vbr_reservoir);*/
2501
2502
     /* Compute the offset we need to apply in order to reach the target */
2503
0
     if (st->constrained_vbr)
2504
0
     {
2505
0
        st->vbr_drift += (opus_int32)MULT16_32_Q15(alpha,(delta*(1<<lm_diff))-st->vbr_offset-st->vbr_drift);
2506
0
        st->vbr_offset = -st->vbr_drift;
2507
0
     }
2508
     /*printf ("%d\n", st->vbr_drift);*/
2509
2510
0
     if (st->constrained_vbr && st->vbr_reservoir < 0)
2511
0
     {
2512
        /* We're under the min value -- increase rate */
2513
0
        int adjust = (-st->vbr_reservoir)/(8<<BITRES);
2514
        /* Unless we're just coding silence */
2515
0
        nbAvailableBytes += silence?0:adjust;
2516
0
        st->vbr_reservoir = 0;
2517
        /*printf ("+%d\n", adjust);*/
2518
0
     }
2519
0
     nbCompressedBytes = IMIN(nbCompressedBytes,nbAvailableBytes);
2520
     /*printf("%d\n", nbCompressedBytes*50*8);*/
2521
     /* This moves the raw bits to take into account the new compressed size */
2522
0
     ec_enc_shrink(enc, nbCompressedBytes);
2523
0
   }
2524
#ifdef ENABLE_QEXT
2525
   if (st->enable_qext) {
2526
      int new_compressedBytes;
2527
      /* Don't give any bits for the first 80 kb/s per channel. Then 80% of the excess. */
2528
      opus_int32 offset = C*80000*frame_size/mode->Fs/8;
2529
      qext_bytes = IMAX(nbCompressedBytes-1275, IMAX(0, (nbCompressedBytes-offset)*4/5));
2530
      if (qext_bytes > 20) {
2531
         opus_int32 target;
2532
         opus_val16 scale;
2533
         target = ((nbCompressedBytes-qext_bytes/3)*8<<BITRES);
2534
         if (!vbr_rate) {
2535
            opus_val16 tf_estimate2;
2536
            target -= ((40*C+20)<<BITRES);
2537
            tf_estimate2 = MIN32(QCONST16(1.f, 14), 2*EXTEND32(tf_estimate));
2538
            target = compute_vbr(mode, &st->analysis, target, LM, equiv_rate,
2539
                  st->lastCodedBands, C, st->intensity, st->constrained_vbr,
2540
                  st->stereo_saving, tot_boost, tf_estimate2, pitch_change, maxDepth,
2541
                  st->lfe, st->energy_mask!=NULL, surround_masking,
2542
                  temporal_vbr ARG_QEXT(st->enable_qext));
2543
            target += tell;
2544
         }
2545
         scale = PSHR32(toneishness,14);
2546
         scale = Q15ONE - MULT16_16_Q15(scale, scale);
2547
         qext_bytes += MULT16_32_Q15(scale, (nbCompressedBytes-(target/(8<<BITRES))) - qext_bytes);
2548
         qext_bytes = IMAX(nbCompressedBytes-1275, IMAX(21, qext_bytes));
2549
      }
2550
      padding_len_bytes = (qext_bytes+253)/254;
2551
      qext_bytes = IMIN(qext_bytes, nbCompressedBytes-min_allowed-padding_len_bytes-1);
2552
      padding_len_bytes = (qext_bytes+253)/254;
2553
      if (qext_bytes > 20) {
2554
         new_compressedBytes = nbCompressedBytes-qext_bytes-padding_len_bytes-1;
2555
         ec_enc_shrink(enc, new_compressedBytes);
2556
         if (compressed == NULL) {
2557
            compressed = enc->buf;
2558
         }
2559
         compressed[-1] |= 0x03; /* Code 3 packet */
2560
         enc->buf += 1+padding_len_bytes;
2561
         OPUS_MOVE(compressed+1+padding_len_bytes, compressed, new_compressedBytes);
2562
         compressed[0] = 0x41; /* Set padding */
2563
         for (i=0;i<padding_len_bytes-1;i++) compressed[i+1] = 255;
2564
         compressed[padding_len_bytes] = qext_bytes%254 == 0 ? 254 : qext_bytes%254;
2565
         ext_payload = compressed+padding_len_bytes+1+new_compressedBytes;
2566
         ext_payload[0] = QEXT_EXTENSION_ID<<1;
2567
         ext_payload += 1;
2568
         qext_bytes -= 1;
2569
         OPUS_CLEAR(ext_payload, qext_bytes);
2570
         ec_enc_init(&ext_enc, ext_payload, qext_bytes);
2571
         nbCompressedBytes = new_compressedBytes;
2572
         if (end == nbEBands && (mode->Fs == 48000 ||  mode->Fs == 96000) && (mode->shortMdctSize==120*qext_scale || mode->shortMdctSize==90*qext_scale)) {
2573
            compute_qext_mode(&qext_mode_struct, mode);
2574
            qext_mode = &qext_mode_struct;
2575
            qext_end = (qext_scale == 2) ? NB_QEXT_BANDS : 2;
2576
            ec_enc_bit_logp(&ext_enc, qext_end == NB_QEXT_BANDS, 1);
2577
         }
2578
      } else {
2579
         ec_enc_init(&ext_enc, NULL, 0);
2580
         qext_bytes = 0;
2581
      }
2582
   } else {
2583
      ec_enc_init(&ext_enc, NULL, 0);
2584
   }
2585
#endif
2586
2587
   /* Bit allocation */
2588
0
   ALLOC(fine_quant, nbEBands, int);
2589
0
   ALLOC(pulses, nbEBands, int);
2590
0
   ALLOC(fine_priority, nbEBands, int);
2591
2592
   /* bits =           packet size                    - where we are - safety*/
2593
0
   bits = (((opus_int32)nbCompressedBytes*8)<<BITRES) - (opus_int32)ec_tell_frac(enc) - 1;
2594
0
   anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
2595
0
   bits -= anti_collapse_rsv;
2596
0
   signalBandwidth = end-1;
2597
0
#ifndef DISABLE_FLOAT_API
2598
0
   if (st->analysis.valid)
2599
0
   {
2600
0
      int min_bandwidth;
2601
0
      if (equiv_rate < (opus_int32)32000*C)
2602
0
         min_bandwidth = 13;
2603
0
      else if (equiv_rate < (opus_int32)48000*C)
2604
0
         min_bandwidth = 16;
2605
0
      else if (equiv_rate < (opus_int32)60000*C)
2606
0
         min_bandwidth = 18;
2607
0
      else  if (equiv_rate < (opus_int32)80000*C)
2608
0
         min_bandwidth = 19;
2609
0
      else
2610
0
         min_bandwidth = 20;
2611
0
      signalBandwidth = IMAX(st->analysis.bandwidth, min_bandwidth);
2612
0
   }
2613
0
#endif
2614
0
   if (st->lfe)
2615
0
      signalBandwidth = 1;
2616
0
   codedBands = clt_compute_allocation(mode, start, end, offsets, cap,
2617
0
         alloc_trim, &st->intensity, &dual_stereo, bits, &balance, pulses,
2618
0
         fine_quant, fine_priority, C, LM, enc, 1, st->lastCodedBands, signalBandwidth);
2619
0
   if (st->lastCodedBands)
2620
0
      st->lastCodedBands = IMIN(st->lastCodedBands+1,IMAX(st->lastCodedBands-1,codedBands));
2621
0
   else
2622
0
      st->lastCodedBands = codedBands;
2623
2624
0
   quant_fine_energy(mode, start, end, oldBandE, error, NULL, fine_quant, enc, C);
2625
0
   OPUS_CLEAR(energyError, nbEBands*CC);
2626
#ifdef ENABLE_QEXT
2627
   if (qext_mode)
2628
   {
2629
      /* Don't bias for intra. */
2630
      opus_val32 qext_delayedIntra=0;
2631
      qext_oldBandE = energyError + CC*nbEBands;
2632
      compute_band_energies(qext_mode, freq, qext_bandE, qext_end, C, LM, st->arch);
2633
      normalise_bands(qext_mode, freq, X, qext_bandE, qext_end, C, M);
2634
      amp2Log2(qext_mode, qext_end, qext_end, qext_bandE, qext_bandLogE, C);
2635
      if (C==2) {
2636
         qext_intensity = qext_end;
2637
         qext_dual_stereo = dual_stereo;
2638
         encode_qext_stereo_params(&ext_enc, qext_end, qext_intensity, qext_dual_stereo);
2639
      }
2640
      quant_coarse_energy(qext_mode, 0, qext_end, qext_end, qext_bandLogE,
2641
               qext_oldBandE, qext_bytes*8, qext_error, &ext_enc,
2642
               C, LM, qext_bytes, st->force_intra,
2643
               &qext_delayedIntra, st->complexity >= 4, st->loss_rate, st->lfe);
2644
   }
2645
   ALLOC(extra_quant, nbEBands+NB_QEXT_BANDS, int);
2646
   ALLOC(extra_pulses, nbEBands+NB_QEXT_BANDS, int);
2647
   ALLOC(error_bak, C*nbEBands, celt_glog);
2648
2649
   qext_bits = ((opus_int32)qext_bytes*8<<BITRES) - (opus_int32)ec_tell_frac(enc) - 1;
2650
   clt_compute_extra_allocation(mode, qext_mode, start, end, qext_end, bandLogE, qext_bandLogE,
2651
         qext_bits, extra_pulses, extra_quant, C, LM, &ext_enc, 1, tone_freq, toneishness);
2652
   OPUS_COPY(error_bak, error, C*nbEBands);
2653
   if (qext_bytes > 0) {
2654
      quant_fine_energy(mode, start, end, oldBandE, error, fine_quant, extra_quant, &ext_enc, C);
2655
   }
2656
#endif
2657
2658
   /* Residual quantisation */
2659
0
   ALLOC(collapse_masks, C*nbEBands, unsigned char);
2660
0
   quant_all_bands(1, mode, start, end, X, C==2 ? X+N : NULL, collapse_masks,
2661
0
         bandE, pulses, shortBlocks, st->spread_decision,
2662
0
         dual_stereo, st->intensity, tf_res, nbCompressedBytes*(8<<BITRES)-anti_collapse_rsv,
2663
0
         balance, enc, LM, codedBands, &st->rng, st->complexity, st->arch, st->disable_inv
2664
0
         ARG_QEXT(&ext_enc) ARG_QEXT(extra_pulses)
2665
0
         ARG_QEXT(qext_bytes*(8<<BITRES)) ARG_QEXT(cap));
2666
2667
#ifdef ENABLE_QEXT
2668
   if (qext_mode) {
2669
      VARDECL(int, zeros);
2670
      VARDECL(unsigned char, qext_collapse_masks);
2671
      ec_enc dummy_enc;
2672
      int ext_balance;
2673
      ALLOC(zeros, nbEBands, int);
2674
      ALLOC(qext_collapse_masks, C*NB_QEXT_BANDS, unsigned char);
2675
      ec_enc_init(&dummy_enc, NULL, 0);
2676
      OPUS_CLEAR(zeros, end);
2677
      ext_balance = qext_bytes*(8<<BITRES) - ec_tell_frac(&ext_enc);
2678
      for (i=0;i<qext_end;i++) ext_balance -= extra_pulses[nbEBands+i] + C*(extra_quant[nbEBands+1]<<BITRES);
2679
      quant_fine_energy(qext_mode, 0, qext_end, qext_oldBandE, qext_error, NULL, &extra_quant[nbEBands], &ext_enc, C);
2680
      quant_all_bands(1, qext_mode, 0, qext_end, X, C==2 ? X+N : NULL, qext_collapse_masks,
2681
            qext_bandE, &extra_pulses[nbEBands], shortBlocks, st->spread_decision,
2682
            qext_dual_stereo, qext_intensity, zeros, qext_bytes*(8<<BITRES),
2683
            ext_balance, &ext_enc, LM, qext_end, &st->rng, st->complexity, st->arch, st->disable_inv, &dummy_enc, zeros, 0, NULL);
2684
   }
2685
#endif
2686
2687
0
   if (anti_collapse_rsv > 0)
2688
0
   {
2689
0
      anti_collapse_on = st->consec_transient<2;
2690
#ifdef FUZZING
2691
      anti_collapse_on = rand()&0x1;
2692
#endif
2693
0
      ec_enc_bits(enc, anti_collapse_on, 1);
2694
0
   }
2695
0
   if (qext_bytes == 0)
2696
0
      quant_energy_finalise(mode, start, end, oldBandE, error, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, C);
2697
0
   c=0;
2698
0
   do {
2699
0
      for (i=start;i<end;i++)
2700
0
      {
2701
0
         energyError[i+c*nbEBands] = MAXG(-GCONST(0.5f), MING(GCONST(0.5f), error[i+c*nbEBands]));
2702
0
      }
2703
0
   } while (++c < C);
2704
#ifdef ENABLE_QEXT
2705
   if (qext_bytes > 0)
2706
      quant_energy_finalise(mode, start, end, NULL, error_bak, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, C);
2707
#endif
2708
0
   if (silence)
2709
0
   {
2710
0
      for (i=0;i<C*nbEBands;i++)
2711
0
         oldBandE[i] = -GCONST(28.f);
2712
0
   }
2713
2714
#ifdef RESYNTH
2715
   /* Re-synthesis of the coded audio if required */
2716
   {
2717
      celt_sig *out_mem[2];
2718
2719
      if (anti_collapse_on)
2720
      {
2721
         anti_collapse(mode, X, collapse_masks, LM, C, N,
2722
               start, end, oldBandE, oldLogE, oldLogE2, pulses, st->rng, 1, st->arch);
2723
      }
2724
2725
      c=0; do {
2726
         OPUS_MOVE(st->syn_mem[c], st->syn_mem[c]+N, QEXT_SCALE(DEC_PITCH_BUF_SIZE)-N+overlap/2);
2727
      } while (++c<CC);
2728
2729
      c=0; do {
2730
         out_mem[c] = st->syn_mem[c]+QEXT_SCALE(DEC_PITCH_BUF_SIZE)-N;
2731
      } while (++c<CC);
2732
2733
      celt_synthesis(mode, X, out_mem, oldBandE, start, effEnd,
2734
                     C, CC, isTransient, LM, st->upsample, silence, st->arch ARG_QEXT(qext_mode) ARG_QEXT(qext_oldBandE) ARG_QEXT(qext_end));
2735
2736
      c=0; do {
2737
         st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
2738
         st->prefilter_period_old=IMAX(st->prefilter_period_old, COMBFILTER_MINPERIOD);
2739
         comb_filter(out_mem[c], out_mem[c], st->prefilter_period_old, st->prefilter_period, mode->shortMdctSize,
2740
               st->prefilter_gain_old, st->prefilter_gain, st->prefilter_tapset_old, st->prefilter_tapset,
2741
               mode->window, overlap, st->arch);
2742
         if (LM!=0)
2743
            comb_filter(out_mem[c]+mode->shortMdctSize, out_mem[c]+mode->shortMdctSize, st->prefilter_period, pitch_index, N-mode->shortMdctSize,
2744
                  st->prefilter_gain, gain1, st->prefilter_tapset, prefilter_tapset,
2745
                  mode->window, overlap, st->arch);
2746
      } while (++c<CC);
2747
2748
      /* We reuse freq[] as scratch space for the de-emphasis */
2749
      deemphasis(out_mem, (opus_res*)pcm, N, CC, st->upsample, mode->preemph, st->preemph_memD, 0);
2750
      st->prefilter_period_old = st->prefilter_period;
2751
      st->prefilter_gain_old = st->prefilter_gain;
2752
      st->prefilter_tapset_old = st->prefilter_tapset;
2753
   }
2754
#endif
2755
2756
0
   st->prefilter_period = pitch_index;
2757
0
   st->prefilter_gain = gain1;
2758
0
   st->prefilter_tapset = prefilter_tapset;
2759
#ifdef RESYNTH
2760
   if (LM!=0)
2761
   {
2762
      st->prefilter_period_old = st->prefilter_period;
2763
      st->prefilter_gain_old = st->prefilter_gain;
2764
      st->prefilter_tapset_old = st->prefilter_tapset;
2765
   }
2766
#endif
2767
2768
0
   if (CC==2&&C==1) {
2769
0
      OPUS_COPY(&oldBandE[nbEBands], oldBandE, nbEBands);
2770
0
   }
2771
2772
0
   if (!isTransient)
2773
0
   {
2774
0
      OPUS_COPY(oldLogE2, oldLogE, CC*nbEBands);
2775
0
      OPUS_COPY(oldLogE, oldBandE, CC*nbEBands);
2776
0
   } else {
2777
0
      for (i=0;i<CC*nbEBands;i++)
2778
0
         oldLogE[i] = MING(oldLogE[i], oldBandE[i]);
2779
0
   }
2780
   /* In case start or end were to change */
2781
0
   c=0; do
2782
0
   {
2783
0
      for (i=0;i<start;i++)
2784
0
      {
2785
0
         oldBandE[c*nbEBands+i]=0;
2786
0
         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-GCONST(28.f);
2787
0
      }
2788
0
      for (i=end;i<nbEBands;i++)
2789
0
      {
2790
0
         oldBandE[c*nbEBands+i]=0;
2791
0
         oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-GCONST(28.f);
2792
0
      }
2793
0
   } while (++c<CC);
2794
2795
0
   if (isTransient || transient_got_disabled)
2796
0
      st->consec_transient++;
2797
0
   else
2798
0
      st->consec_transient=0;
2799
0
   st->rng = enc->rng;
2800
2801
   /* If there's any room left (can only happen for very high rates),
2802
      it's already filled with zeros */
2803
0
   ec_enc_done(enc);
2804
#ifdef ENABLE_QEXT
2805
   ec_enc_done(&ext_enc);
2806
   if (qext_bytes > 0)
2807
      nbCompressedBytes += padding_len_bytes+2+qext_bytes;
2808
   if (qext_bytes) st->rng = st->rng ^ ext_enc.rng;
2809
   if (ec_get_error(&ext_enc))
2810
      return OPUS_INTERNAL_ERROR;
2811
#endif
2812
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
2813
   if (st->signalling)
2814
      nbCompressedBytes++;
2815
#endif
2816
2817
0
   RESTORE_STACK;
2818
0
   if (ec_get_error(enc))
2819
0
      return OPUS_INTERNAL_ERROR;
2820
0
   else
2821
0
      return nbCompressedBytes;
2822
0
}
2823
2824
2825
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
2826
2827
#if defined(FIXED_POINT) && !defined(ENABLE_RES24)
2828
int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
2829
{
2830
   return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
2831
}
2832
#else
2833
int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
2834
{
2835
   int j, ret, C, N;
2836
   VARDECL(opus_res, in);
2837
   ALLOC_STACK;
2838
2839
   if (pcm==NULL)
2840
      return OPUS_BAD_ARG;
2841
2842
   C = st->channels;
2843
   N = frame_size;
2844
   ALLOC(in, C*N, opus_res);
2845
2846
   for (j=0;j<C*N;j++)
2847
     in[j] = INT16TORES(pcm[j]);
2848
2849
   ret=celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
2850
#ifdef RESYNTH
2851
   for (j=0;j<C*N;j++)
2852
      ((opus_int16*)pcm)[j]=RES2INT16(in[j]);
2853
#endif
2854
   RESTORE_STACK;
2855
   return ret;
2856
}
2857
#endif
2858
2859
2860
#if defined(FIXED_POINT) && defined(ENABLE_RES24)
2861
int opus_custom_encode24(CELTEncoder * OPUS_RESTRICT st, const opus_int32 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
2862
{
2863
   return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
2864
}
2865
#else
2866
int opus_custom_encode24(CELTEncoder * OPUS_RESTRICT st, const opus_int32 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
2867
{
2868
   int j, ret, C, N;
2869
   VARDECL(opus_res, in);
2870
   ALLOC_STACK;
2871
2872
   if (pcm==NULL)
2873
      return OPUS_BAD_ARG;
2874
2875
   C = st->channels;
2876
   N = frame_size;
2877
   ALLOC(in, C*N, opus_res);
2878
2879
   for (j=0;j<C*N;j++)
2880
     in[j] = INT24TORES(pcm[j]);
2881
2882
   ret=celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
2883
#ifdef RESYNTH
2884
   for (j=0;j<C*N;j++)
2885
      ((opus_int32*)pcm)[j]=RES2INT24(in[j]);
2886
#endif
2887
   RESTORE_STACK;
2888
   return ret;
2889
}
2890
#endif
2891
2892
2893
#ifndef DISABLE_FLOAT_API
2894
2895
# if !defined(FIXED_POINT)
2896
int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
2897
{
2898
   return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
2899
}
2900
# else
2901
int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
2902
{
2903
   int j, ret, C, N;
2904
   VARDECL(opus_res, in);
2905
   ALLOC_STACK;
2906
2907
   if (pcm==NULL)
2908
      return OPUS_BAD_ARG;
2909
2910
   C = st->channels;
2911
   N = frame_size;
2912
   ALLOC(in, C*N, opus_res);
2913
2914
   for (j=0;j<C*N;j++)
2915
     in[j] = FLOAT2RES(pcm[j]);
2916
2917
   ret=celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
2918
#ifdef RESYNTH
2919
   for (j=0;j<C*N;j++)
2920
      ((float*)pcm)[j]=RES2FLOAT(in[j]);
2921
#endif
2922
   RESTORE_STACK;
2923
   return ret;
2924
}
2925
# endif
2926
2927
#endif
2928
2929
#endif /* CUSTOM_MODES */
2930
2931
int opus_custom_encoder_ctl(CELTEncoder * OPUS_RESTRICT st, int request, ...)
2932
0
{
2933
0
   va_list ap;
2934
2935
0
   va_start(ap, request);
2936
0
   switch (request)
2937
0
   {
2938
0
      case OPUS_SET_COMPLEXITY_REQUEST:
2939
0
      {
2940
0
         int value = va_arg(ap, opus_int32);
2941
0
         if (value<0 || value>10)
2942
0
            goto bad_arg;
2943
0
         st->complexity = value;
2944
0
      }
2945
0
      break;
2946
0
      case CELT_SET_START_BAND_REQUEST:
2947
0
      {
2948
0
         opus_int32 value = va_arg(ap, opus_int32);
2949
0
         if (value<0 || value>=st->mode->nbEBands)
2950
0
            goto bad_arg;
2951
0
         st->start = value;
2952
0
      }
2953
0
      break;
2954
0
      case CELT_SET_END_BAND_REQUEST:
2955
0
      {
2956
0
         opus_int32 value = va_arg(ap, opus_int32);
2957
0
         if (value<1 || value>st->mode->nbEBands)
2958
0
            goto bad_arg;
2959
0
         st->end = value;
2960
0
      }
2961
0
      break;
2962
0
      case CELT_SET_PREDICTION_REQUEST:
2963
0
      {
2964
0
         int value = va_arg(ap, opus_int32);
2965
0
         if (value<0 || value>2)
2966
0
            goto bad_arg;
2967
0
         st->disable_pf = value<=1;
2968
0
         st->force_intra = value==0;
2969
0
      }
2970
0
      break;
2971
0
      case OPUS_SET_PACKET_LOSS_PERC_REQUEST:
2972
0
      {
2973
0
         int value = va_arg(ap, opus_int32);
2974
0
         if (value<0 || value>100)
2975
0
            goto bad_arg;
2976
0
         st->loss_rate = value;
2977
0
      }
2978
0
      break;
2979
0
      case OPUS_SET_VBR_CONSTRAINT_REQUEST:
2980
0
      {
2981
0
         opus_int32 value = va_arg(ap, opus_int32);
2982
0
         st->constrained_vbr = value;
2983
0
      }
2984
0
      break;
2985
0
      case OPUS_SET_VBR_REQUEST:
2986
0
      {
2987
0
         opus_int32 value = va_arg(ap, opus_int32);
2988
0
         st->vbr = value;
2989
0
      }
2990
0
      break;
2991
0
      case OPUS_SET_BITRATE_REQUEST:
2992
0
      {
2993
0
         opus_int32 value = va_arg(ap, opus_int32);
2994
0
         if (value<=500 && value!=OPUS_BITRATE_MAX)
2995
0
            goto bad_arg;
2996
0
         value = IMIN(value, 750000*st->channels);
2997
0
         st->bitrate = value;
2998
0
      }
2999
0
      break;
3000
0
      case CELT_SET_CHANNELS_REQUEST:
3001
0
      {
3002
0
         opus_int32 value = va_arg(ap, opus_int32);
3003
0
         if (value<1 || value>2)
3004
0
            goto bad_arg;
3005
0
         st->stream_channels = value;
3006
0
      }
3007
0
      break;
3008
0
      case OPUS_SET_LSB_DEPTH_REQUEST:
3009
0
      {
3010
0
          opus_int32 value = va_arg(ap, opus_int32);
3011
0
          if (value<8 || value>24)
3012
0
             goto bad_arg;
3013
0
          st->lsb_depth=value;
3014
0
      }
3015
0
      break;
3016
0
      case OPUS_GET_LSB_DEPTH_REQUEST:
3017
0
      {
3018
0
          opus_int32 *value = va_arg(ap, opus_int32*);
3019
0
          *value=st->lsb_depth;
3020
0
      }
3021
0
      break;
3022
0
      case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST:
3023
0
      {
3024
0
          opus_int32 value = va_arg(ap, opus_int32);
3025
0
          if(value<0 || value>1)
3026
0
          {
3027
0
             goto bad_arg;
3028
0
          }
3029
0
          st->disable_inv = value;
3030
0
      }
3031
0
      break;
3032
0
      case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST:
3033
0
      {
3034
0
          opus_int32 *value = va_arg(ap, opus_int32*);
3035
0
          if (!value)
3036
0
          {
3037
0
             goto bad_arg;
3038
0
          }
3039
0
          *value = st->disable_inv;
3040
0
      }
3041
0
      break;
3042
#ifdef ENABLE_QEXT
3043
      case OPUS_SET_QEXT_REQUEST:
3044
      {
3045
          opus_int32 value = va_arg(ap, opus_int32);
3046
          if(value<0 || value>1)
3047
          {
3048
             goto bad_arg;
3049
          }
3050
          st->enable_qext = value;
3051
      }
3052
      break;
3053
      case OPUS_GET_QEXT_REQUEST:
3054
      {
3055
          opus_int32 *value = va_arg(ap, opus_int32*);
3056
          if (!value)
3057
          {
3058
             goto bad_arg;
3059
          }
3060
          *value = st->enable_qext;
3061
      }
3062
      break;
3063
#endif
3064
0
      case OPUS_RESET_STATE:
3065
0
      {
3066
0
         int i;
3067
0
         celt_glog *oldBandE, *oldLogE, *oldLogE2;
3068
0
         oldBandE = (celt_glog*)(st->in_mem+st->channels*(st->mode->overlap+QEXT_SCALE2(COMBFILTER_MAXPERIOD, st->qext_scale)));
3069
0
         oldLogE = oldBandE + st->channels*st->mode->nbEBands;
3070
0
         oldLogE2 = oldLogE + st->channels*st->mode->nbEBands;
3071
0
         OPUS_CLEAR((char*)&st->ENCODER_RESET_START,
3072
0
               opus_custom_encoder_get_size(st->mode, st->channels)-
3073
0
               ((char*)&st->ENCODER_RESET_START - (char*)st));
3074
0
         for (i=0;i<st->channels*st->mode->nbEBands;i++)
3075
0
            oldLogE[i]=oldLogE2[i]=-GCONST(28.f);
3076
0
         st->vbr_offset = 0;
3077
0
         st->delayedIntra = 1;
3078
0
         st->spread_decision = SPREAD_NORMAL;
3079
0
         st->tonal_average = 256;
3080
0
         st->hf_average = 0;
3081
0
         st->tapset_decision = 0;
3082
0
      }
3083
0
      break;
3084
#if defined(CUSTOM_MODES) || defined(ENABLE_OPUS_CUSTOM_API)
3085
      case CELT_SET_INPUT_CLIPPING_REQUEST:
3086
      {
3087
         opus_int32 value = va_arg(ap, opus_int32);
3088
         st->clip = value;
3089
      }
3090
      break;
3091
#endif
3092
0
      case CELT_SET_SIGNALLING_REQUEST:
3093
0
      {
3094
0
         opus_int32 value = va_arg(ap, opus_int32);
3095
0
         st->signalling = value;
3096
0
      }
3097
0
      break;
3098
0
      case CELT_SET_ANALYSIS_REQUEST:
3099
0
      {
3100
0
         AnalysisInfo *info = va_arg(ap, AnalysisInfo *);
3101
0
         if (info)
3102
0
            OPUS_COPY(&st->analysis, info, 1);
3103
0
      }
3104
0
      break;
3105
0
      case CELT_SET_SILK_INFO_REQUEST:
3106
0
      {
3107
0
         SILKInfo *info = va_arg(ap, SILKInfo *);
3108
0
         if (info)
3109
0
            OPUS_COPY(&st->silk_info, info, 1);
3110
0
      }
3111
0
      break;
3112
0
      case CELT_GET_MODE_REQUEST:
3113
0
      {
3114
0
         const CELTMode ** value = va_arg(ap, const CELTMode**);
3115
0
         if (value==0)
3116
0
            goto bad_arg;
3117
0
         *value=st->mode;
3118
0
      }
3119
0
      break;
3120
0
      case OPUS_GET_FINAL_RANGE_REQUEST:
3121
0
      {
3122
0
         opus_uint32 * value = va_arg(ap, opus_uint32 *);
3123
0
         if (value==0)
3124
0
            goto bad_arg;
3125
0
         *value=st->rng;
3126
0
      }
3127
0
      break;
3128
0
      case OPUS_SET_LFE_REQUEST:
3129
0
      {
3130
0
          opus_int32 value = va_arg(ap, opus_int32);
3131
0
          st->lfe = value;
3132
0
      }
3133
0
      break;
3134
0
      case OPUS_SET_ENERGY_MASK_REQUEST:
3135
0
      {
3136
0
         celt_glog *value = va_arg(ap, celt_glog*);
3137
0
          st->energy_mask = value;
3138
0
      }
3139
0
      break;
3140
0
      default:
3141
0
         goto bad_request;
3142
0
   }
3143
0
   va_end(ap);
3144
0
   return OPUS_OK;
3145
0
bad_arg:
3146
0
   va_end(ap);
3147
0
   return OPUS_BAD_ARG;
3148
0
bad_request:
3149
0
   va_end(ap);
3150
0
   return OPUS_UNIMPLEMENTED;
3151
0
}