1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/media/libopus/celt/celt_encoder.c Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,2353 @@ 1.4 +/* Copyright (c) 2007-2008 CSIRO 1.5 + Copyright (c) 2007-2010 Xiph.Org Foundation 1.6 + Copyright (c) 2008 Gregory Maxwell 1.7 + Written by Jean-Marc Valin and Gregory Maxwell */ 1.8 +/* 1.9 + Redistribution and use in source and binary forms, with or without 1.10 + modification, are permitted provided that the following conditions 1.11 + are met: 1.12 + 1.13 + - Redistributions of source code must retain the above copyright 1.14 + notice, this list of conditions and the following disclaimer. 1.15 + 1.16 + - Redistributions in binary form must reproduce the above copyright 1.17 + notice, this list of conditions and the following disclaimer in the 1.18 + documentation and/or other materials provided with the distribution. 1.19 + 1.20 + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 1.21 + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 1.22 + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 1.23 + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 1.24 + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 1.25 + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 1.26 + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 1.27 + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 1.28 + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 1.29 + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 1.30 + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 1.31 +*/ 1.32 + 1.33 +#ifdef HAVE_CONFIG_H 1.34 +#include "config.h" 1.35 +#endif 1.36 + 1.37 +#define CELT_ENCODER_C 1.38 + 1.39 +#include "cpu_support.h" 1.40 +#include "os_support.h" 1.41 +#include "mdct.h" 1.42 +#include <math.h> 1.43 +#include "celt.h" 1.44 +#include "pitch.h" 1.45 +#include "bands.h" 1.46 +#include "modes.h" 1.47 +#include "entcode.h" 1.48 +#include "quant_bands.h" 1.49 +#include "rate.h" 1.50 +#include "stack_alloc.h" 1.51 +#include "mathops.h" 1.52 +#include "float_cast.h" 1.53 +#include <stdarg.h> 1.54 +#include "celt_lpc.h" 1.55 +#include "vq.h" 1.56 + 1.57 + 1.58 +/** Encoder state 1.59 + @brief Encoder state 1.60 + */ 1.61 +struct OpusCustomEncoder { 1.62 + const OpusCustomMode *mode; /**< Mode used by the encoder */ 1.63 + int overlap; 1.64 + int channels; 1.65 + int stream_channels; 1.66 + 1.67 + int force_intra; 1.68 + int clip; 1.69 + int disable_pf; 1.70 + int complexity; 1.71 + int upsample; 1.72 + int start, end; 1.73 + 1.74 + opus_int32 bitrate; 1.75 + int vbr; 1.76 + int signalling; 1.77 + int constrained_vbr; /* If zero, VBR can do whatever it likes with the rate */ 1.78 + int loss_rate; 1.79 + int lsb_depth; 1.80 + int variable_duration; 1.81 + int lfe; 1.82 + int arch; 1.83 + 1.84 + /* Everything beyond this point gets cleared on a reset */ 1.85 +#define ENCODER_RESET_START rng 1.86 + 1.87 + opus_uint32 rng; 1.88 + int spread_decision; 1.89 + opus_val32 delayedIntra; 1.90 + int tonal_average; 1.91 + int lastCodedBands; 1.92 + int hf_average; 1.93 + int tapset_decision; 1.94 + 1.95 + int prefilter_period; 1.96 + opus_val16 prefilter_gain; 1.97 + int prefilter_tapset; 1.98 +#ifdef RESYNTH 1.99 + int prefilter_period_old; 1.100 + opus_val16 prefilter_gain_old; 1.101 + int prefilter_tapset_old; 1.102 +#endif 1.103 + int consec_transient; 1.104 + AnalysisInfo analysis; 1.105 + 1.106 + opus_val32 preemph_memE[2]; 1.107 + opus_val32 preemph_memD[2]; 1.108 + 1.109 + /* VBR-related parameters */ 1.110 + opus_int32 vbr_reservoir; 1.111 + opus_int32 vbr_drift; 1.112 + opus_int32 vbr_offset; 1.113 + opus_int32 vbr_count; 1.114 + opus_val32 overlap_max; 1.115 + opus_val16 stereo_saving; 1.116 + int intensity; 1.117 + opus_val16 *energy_mask; 1.118 + opus_val16 spec_avg; 1.119 + 1.120 +#ifdef RESYNTH 1.121 + /* +MAX_PERIOD/2 to make space for overlap */ 1.122 + celt_sig syn_mem[2][2*MAX_PERIOD+MAX_PERIOD/2]; 1.123 +#endif 1.124 + 1.125 + celt_sig in_mem[1]; /* Size = channels*mode->overlap */ 1.126 + /* celt_sig prefilter_mem[], Size = channels*COMBFILTER_MAXPERIOD */ 1.127 + /* opus_val16 oldBandE[], Size = channels*mode->nbEBands */ 1.128 + /* opus_val16 oldLogE[], Size = channels*mode->nbEBands */ 1.129 + /* opus_val16 oldLogE2[], Size = channels*mode->nbEBands */ 1.130 +}; 1.131 + 1.132 +int celt_encoder_get_size(int channels) 1.133 +{ 1.134 + CELTMode *mode = opus_custom_mode_create(48000, 960, NULL); 1.135 + return opus_custom_encoder_get_size(mode, channels); 1.136 +} 1.137 + 1.138 +OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_get_size(const CELTMode *mode, int channels) 1.139 +{ 1.140 + int size = sizeof(struct CELTEncoder) 1.141 + + (channels*mode->overlap-1)*sizeof(celt_sig) /* celt_sig in_mem[channels*mode->overlap]; */ 1.142 + + channels*COMBFILTER_MAXPERIOD*sizeof(celt_sig) /* celt_sig prefilter_mem[channels*COMBFILTER_MAXPERIOD]; */ 1.143 + + 3*channels*mode->nbEBands*sizeof(opus_val16); /* opus_val16 oldBandE[channels*mode->nbEBands]; */ 1.144 + /* opus_val16 oldLogE[channels*mode->nbEBands]; */ 1.145 + /* opus_val16 oldLogE2[channels*mode->nbEBands]; */ 1.146 + return size; 1.147 +} 1.148 + 1.149 +#ifdef CUSTOM_MODES 1.150 +CELTEncoder *opus_custom_encoder_create(const CELTMode *mode, int channels, int *error) 1.151 +{ 1.152 + int ret; 1.153 + CELTEncoder *st = (CELTEncoder *)opus_alloc(opus_custom_encoder_get_size(mode, channels)); 1.154 + /* init will handle the NULL case */ 1.155 + ret = opus_custom_encoder_init(st, mode, channels); 1.156 + if (ret != OPUS_OK) 1.157 + { 1.158 + opus_custom_encoder_destroy(st); 1.159 + st = NULL; 1.160 + } 1.161 + if (error) 1.162 + *error = ret; 1.163 + return st; 1.164 +} 1.165 +#endif /* CUSTOM_MODES */ 1.166 + 1.167 +static int opus_custom_encoder_init_arch(CELTEncoder *st, const CELTMode *mode, 1.168 + int channels, int arch) 1.169 +{ 1.170 + if (channels < 0 || channels > 2) 1.171 + return OPUS_BAD_ARG; 1.172 + 1.173 + if (st==NULL || mode==NULL) 1.174 + return OPUS_ALLOC_FAIL; 1.175 + 1.176 + OPUS_CLEAR((char*)st, opus_custom_encoder_get_size(mode, channels)); 1.177 + 1.178 + st->mode = mode; 1.179 + st->overlap = mode->overlap; 1.180 + st->stream_channels = st->channels = channels; 1.181 + 1.182 + st->upsample = 1; 1.183 + st->start = 0; 1.184 + st->end = st->mode->effEBands; 1.185 + st->signalling = 1; 1.186 + 1.187 + st->arch = arch; 1.188 + 1.189 + st->constrained_vbr = 1; 1.190 + st->clip = 1; 1.191 + 1.192 + st->bitrate = OPUS_BITRATE_MAX; 1.193 + st->vbr = 0; 1.194 + st->force_intra = 0; 1.195 + st->complexity = 5; 1.196 + st->lsb_depth=24; 1.197 + 1.198 + opus_custom_encoder_ctl(st, OPUS_RESET_STATE); 1.199 + 1.200 + return OPUS_OK; 1.201 +} 1.202 + 1.203 +#ifdef CUSTOM_MODES 1.204 +int opus_custom_encoder_init(CELTEncoder *st, const CELTMode *mode, int channels) 1.205 +{ 1.206 + return opus_custom_encoder_init_arch(st, mode, channels, opus_select_arch()); 1.207 +} 1.208 +#endif 1.209 + 1.210 +int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels, 1.211 + int arch) 1.212 +{ 1.213 + int ret; 1.214 + ret = opus_custom_encoder_init_arch(st, 1.215 + opus_custom_mode_create(48000, 960, NULL), channels, arch); 1.216 + if (ret != OPUS_OK) 1.217 + return ret; 1.218 + st->upsample = resampling_factor(sampling_rate); 1.219 + return OPUS_OK; 1.220 +} 1.221 + 1.222 +#ifdef CUSTOM_MODES 1.223 +void opus_custom_encoder_destroy(CELTEncoder *st) 1.224 +{ 1.225 + opus_free(st); 1.226 +} 1.227 +#endif /* CUSTOM_MODES */ 1.228 + 1.229 + 1.230 +static int transient_analysis(const opus_val32 * OPUS_RESTRICT in, int len, int C, 1.231 + opus_val16 *tf_estimate, int *tf_chan) 1.232 +{ 1.233 + int i; 1.234 + VARDECL(opus_val16, tmp); 1.235 + opus_val32 mem0,mem1; 1.236 + int is_transient = 0; 1.237 + opus_int32 mask_metric = 0; 1.238 + int c; 1.239 + opus_val16 tf_max; 1.240 + int len2; 1.241 + /* Table of 6*64/x, trained on real data to minimize the average error */ 1.242 + static const unsigned char inv_table[128] = { 1.243 + 255,255,156,110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25, 1.244 + 23, 22, 21, 20, 19, 18, 17, 16, 16, 15, 15, 14, 13, 13, 12, 12, 1.245 + 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 9, 9, 8, 8, 1.246 + 8, 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 1.247 + 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 1.248 + 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1.249 + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 1.250 + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1.251 + }; 1.252 + SAVE_STACK; 1.253 + ALLOC(tmp, len, opus_val16); 1.254 + 1.255 + len2=len/2; 1.256 + for (c=0;c<C;c++) 1.257 + { 1.258 + opus_val32 mean; 1.259 + opus_int32 unmask=0; 1.260 + opus_val32 norm; 1.261 + opus_val16 maxE; 1.262 + mem0=0; 1.263 + mem1=0; 1.264 + /* High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) */ 1.265 + for (i=0;i<len;i++) 1.266 + { 1.267 + opus_val32 x,y; 1.268 + x = SHR32(in[i+c*len],SIG_SHIFT); 1.269 + y = ADD32(mem0, x); 1.270 +#ifdef FIXED_POINT 1.271 + mem0 = mem1 + y - SHL32(x,1); 1.272 + mem1 = x - SHR32(y,1); 1.273 +#else 1.274 + mem0 = mem1 + y - 2*x; 1.275 + mem1 = x - .5f*y; 1.276 +#endif 1.277 + tmp[i] = EXTRACT16(SHR32(y,2)); 1.278 + /*printf("%f ", tmp[i]);*/ 1.279 + } 1.280 + /*printf("\n");*/ 1.281 + /* First few samples are bad because we don't propagate the memory */ 1.282 + for (i=0;i<12;i++) 1.283 + tmp[i] = 0; 1.284 + 1.285 +#ifdef FIXED_POINT 1.286 + /* Normalize tmp to max range */ 1.287 + { 1.288 + int shift=0; 1.289 + shift = 14-celt_ilog2(1+celt_maxabs16(tmp, len)); 1.290 + if (shift!=0) 1.291 + { 1.292 + for (i=0;i<len;i++) 1.293 + tmp[i] = SHL16(tmp[i], shift); 1.294 + } 1.295 + } 1.296 +#endif 1.297 + 1.298 + mean=0; 1.299 + mem0=0; 1.300 + /* Grouping by two to reduce complexity */ 1.301 + /* Forward pass to compute the post-echo threshold*/ 1.302 + for (i=0;i<len2;i++) 1.303 + { 1.304 + opus_val16 x2 = PSHR32(MULT16_16(tmp[2*i],tmp[2*i]) + MULT16_16(tmp[2*i+1],tmp[2*i+1]),16); 1.305 + mean += x2; 1.306 +#ifdef FIXED_POINT 1.307 + /* FIXME: Use PSHR16() instead */ 1.308 + tmp[i] = mem0 + PSHR32(x2-mem0,4); 1.309 +#else 1.310 + tmp[i] = mem0 + MULT16_16_P15(QCONST16(.0625f,15),x2-mem0); 1.311 +#endif 1.312 + mem0 = tmp[i]; 1.313 + } 1.314 + 1.315 + mem0=0; 1.316 + maxE=0; 1.317 + /* Backward pass to compute the pre-echo threshold */ 1.318 + for (i=len2-1;i>=0;i--) 1.319 + { 1.320 +#ifdef FIXED_POINT 1.321 + /* FIXME: Use PSHR16() instead */ 1.322 + tmp[i] = mem0 + PSHR32(tmp[i]-mem0,3); 1.323 +#else 1.324 + tmp[i] = mem0 + MULT16_16_P15(QCONST16(0.125f,15),tmp[i]-mem0); 1.325 +#endif 1.326 + mem0 = tmp[i]; 1.327 + maxE = MAX16(maxE, mem0); 1.328 + } 1.329 + /*for (i=0;i<len2;i++)printf("%f ", tmp[i]/mean);printf("\n");*/ 1.330 + 1.331 + /* Compute the ratio of the "frame energy" over the harmonic mean of the energy. 1.332 + This essentially corresponds to a bitrate-normalized temporal noise-to-mask 1.333 + ratio */ 1.334 + 1.335 + /* As a compromise with the old transient detector, frame energy is the 1.336 + geometric mean of the energy and half the max */ 1.337 +#ifdef FIXED_POINT 1.338 + /* Costs two sqrt() to avoid overflows */ 1.339 + mean = MULT16_16(celt_sqrt(mean), celt_sqrt(MULT16_16(maxE,len2>>1))); 1.340 +#else 1.341 + mean = celt_sqrt(mean * maxE*.5*len2); 1.342 +#endif 1.343 + /* Inverse of the mean energy in Q15+6 */ 1.344 + norm = SHL32(EXTEND32(len2),6+14)/ADD32(EPSILON,SHR32(mean,1)); 1.345 + /* Compute harmonic mean discarding the unreliable boundaries 1.346 + The data is smooth, so we only take 1/4th of the samples */ 1.347 + unmask=0; 1.348 + for (i=12;i<len2-5;i+=4) 1.349 + { 1.350 + int id; 1.351 +#ifdef FIXED_POINT 1.352 + id = IMAX(0,IMIN(127,MULT16_32_Q15(tmp[i],norm))); /* Do not round to nearest */ 1.353 +#else 1.354 + id = IMAX(0,IMIN(127,(int)floor(64*norm*tmp[i]))); /* Do not round to nearest */ 1.355 +#endif 1.356 + unmask += inv_table[id]; 1.357 + } 1.358 + /*printf("%d\n", unmask);*/ 1.359 + /* Normalize, compensate for the 1/4th of the sample and the factor of 6 in the inverse table */ 1.360 + unmask = 64*unmask*4/(6*(len2-17)); 1.361 + if (unmask>mask_metric) 1.362 + { 1.363 + *tf_chan = c; 1.364 + mask_metric = unmask; 1.365 + } 1.366 + } 1.367 + is_transient = mask_metric>200; 1.368 + 1.369 + /* Arbitrary metric for VBR boost */ 1.370 + tf_max = MAX16(0,celt_sqrt(27*mask_metric)-42); 1.371 + /* *tf_estimate = 1 + MIN16(1, sqrt(MAX16(0, tf_max-30))/20); */ 1.372 + *tf_estimate = celt_sqrt(MAX16(0, SHL32(MULT16_16(QCONST16(0.0069,14),MIN16(163,tf_max)),14)-QCONST32(0.139,28))); 1.373 + /*printf("%d %f\n", tf_max, mask_metric);*/ 1.374 + RESTORE_STACK; 1.375 +#ifdef FUZZING 1.376 + is_transient = rand()&0x1; 1.377 +#endif 1.378 + /*printf("%d %f %d\n", is_transient, (float)*tf_estimate, tf_max);*/ 1.379 + return is_transient; 1.380 +} 1.381 + 1.382 +/* Looks for sudden increases of energy to decide whether we need to patch 1.383 + the transient decision */ 1.384 +int patch_transient_decision(opus_val16 *newE, opus_val16 *oldE, int nbEBands, 1.385 + int end, int C) 1.386 +{ 1.387 + int i, c; 1.388 + opus_val32 mean_diff=0; 1.389 + opus_val16 spread_old[26]; 1.390 + /* Apply an aggressive (-6 dB/Bark) spreading function to the old frame to 1.391 + avoid false detection caused by irrelevant bands */ 1.392 + if (C==1) 1.393 + { 1.394 + spread_old[0] = oldE[0]; 1.395 + for (i=1;i<end;i++) 1.396 + spread_old[i] = MAX16(spread_old[i-1]-QCONST16(1.0f, DB_SHIFT), oldE[i]); 1.397 + } else { 1.398 + spread_old[0] = MAX16(oldE[0],oldE[nbEBands]); 1.399 + for (i=1;i<end;i++) 1.400 + spread_old[i] = MAX16(spread_old[i-1]-QCONST16(1.0f, DB_SHIFT), 1.401 + MAX16(oldE[i],oldE[i+nbEBands])); 1.402 + } 1.403 + for (i=end-2;i>=0;i--) 1.404 + spread_old[i] = MAX16(spread_old[i], spread_old[i+1]-QCONST16(1.0f, DB_SHIFT)); 1.405 + /* Compute mean increase */ 1.406 + c=0; do { 1.407 + for (i=2;i<end-1;i++) 1.408 + { 1.409 + opus_val16 x1, x2; 1.410 + x1 = MAX16(0, newE[i]); 1.411 + x2 = MAX16(0, spread_old[i]); 1.412 + mean_diff = ADD32(mean_diff, EXTEND32(MAX16(0, SUB16(x1, x2)))); 1.413 + } 1.414 + } while (++c<C); 1.415 + mean_diff = DIV32(mean_diff, C*(end-3)); 1.416 + /*printf("%f %f %d\n", mean_diff, max_diff, count);*/ 1.417 + return mean_diff > QCONST16(1.f, DB_SHIFT); 1.418 +} 1.419 + 1.420 +/** Apply window and compute the MDCT for all sub-frames and 1.421 + all channels in a frame */ 1.422 +static void compute_mdcts(const CELTMode *mode, int shortBlocks, celt_sig * OPUS_RESTRICT in, 1.423 + celt_sig * OPUS_RESTRICT out, int C, int CC, int LM, int upsample) 1.424 +{ 1.425 + const int overlap = OVERLAP(mode); 1.426 + int N; 1.427 + int B; 1.428 + int shift; 1.429 + int i, b, c; 1.430 + if (shortBlocks) 1.431 + { 1.432 + B = shortBlocks; 1.433 + N = mode->shortMdctSize; 1.434 + shift = mode->maxLM; 1.435 + } else { 1.436 + B = 1; 1.437 + N = mode->shortMdctSize<<LM; 1.438 + shift = mode->maxLM-LM; 1.439 + } 1.440 + c=0; do { 1.441 + for (b=0;b<B;b++) 1.442 + { 1.443 + /* Interleaving the sub-frames while doing the MDCTs */ 1.444 + clt_mdct_forward(&mode->mdct, in+c*(B*N+overlap)+b*N, &out[b+c*N*B], mode->window, overlap, shift, B); 1.445 + } 1.446 + } while (++c<CC); 1.447 + if (CC==2&&C==1) 1.448 + { 1.449 + for (i=0;i<B*N;i++) 1.450 + out[i] = ADD32(HALF32(out[i]), HALF32(out[B*N+i])); 1.451 + } 1.452 + if (upsample != 1) 1.453 + { 1.454 + c=0; do 1.455 + { 1.456 + int bound = B*N/upsample; 1.457 + for (i=0;i<bound;i++) 1.458 + out[c*B*N+i] *= upsample; 1.459 + for (;i<B*N;i++) 1.460 + out[c*B*N+i] = 0; 1.461 + } while (++c<C); 1.462 + } 1.463 +} 1.464 + 1.465 + 1.466 +void celt_preemphasis(const opus_val16 * OPUS_RESTRICT pcmp, celt_sig * OPUS_RESTRICT inp, 1.467 + int N, int CC, int upsample, const opus_val16 *coef, celt_sig *mem, int clip) 1.468 +{ 1.469 + int i; 1.470 + opus_val16 coef0; 1.471 + celt_sig m; 1.472 + int Nu; 1.473 + 1.474 + coef0 = coef[0]; 1.475 + 1.476 + 1.477 + Nu = N/upsample; 1.478 + if (upsample!=1) 1.479 + { 1.480 + for (i=0;i<N;i++) 1.481 + inp[i] = 0; 1.482 + } 1.483 + for (i=0;i<Nu;i++) 1.484 + { 1.485 + celt_sig x; 1.486 + 1.487 + x = SCALEIN(pcmp[CC*i]); 1.488 +#ifndef FIXED_POINT 1.489 + /* Replace NaNs with zeros */ 1.490 + if (!(x==x)) 1.491 + x = 0; 1.492 +#endif 1.493 + inp[i*upsample] = x; 1.494 + } 1.495 + 1.496 +#ifndef FIXED_POINT 1.497 + if (clip) 1.498 + { 1.499 + /* Clip input to avoid encoding non-portable files */ 1.500 + for (i=0;i<Nu;i++) 1.501 + inp[i*upsample] = MAX32(-65536.f, MIN32(65536.f,inp[i*upsample])); 1.502 + } 1.503 +#else 1.504 + (void)clip; /* Avoids a warning about clip being unused. */ 1.505 +#endif 1.506 + m = *mem; 1.507 +#ifdef CUSTOM_MODES 1.508 + if (coef[1] != 0) 1.509 + { 1.510 + opus_val16 coef1 = coef[1]; 1.511 + opus_val16 coef2 = coef[2]; 1.512 + for (i=0;i<N;i++) 1.513 + { 1.514 + celt_sig x, tmp; 1.515 + x = inp[i]; 1.516 + /* Apply pre-emphasis */ 1.517 + tmp = MULT16_16(coef2, x); 1.518 + inp[i] = tmp + m; 1.519 + m = MULT16_32_Q15(coef1, inp[i]) - MULT16_32_Q15(coef0, tmp); 1.520 + } 1.521 + } else 1.522 +#endif 1.523 + { 1.524 + for (i=0;i<N;i++) 1.525 + { 1.526 + celt_sig x; 1.527 + x = SHL32(inp[i], SIG_SHIFT); 1.528 + /* Apply pre-emphasis */ 1.529 + inp[i] = x + m; 1.530 + m = - MULT16_32_Q15(coef0, x); 1.531 + } 1.532 + } 1.533 + *mem = m; 1.534 +} 1.535 + 1.536 + 1.537 + 1.538 +static opus_val32 l1_metric(const celt_norm *tmp, int N, int LM, opus_val16 bias) 1.539 +{ 1.540 + int i; 1.541 + opus_val32 L1; 1.542 + L1 = 0; 1.543 + for (i=0;i<N;i++) 1.544 + L1 += EXTEND32(ABS16(tmp[i])); 1.545 + /* When in doubt, prefer good freq resolution */ 1.546 + L1 = MAC16_32_Q15(L1, LM*bias, L1); 1.547 + return L1; 1.548 + 1.549 +} 1.550 + 1.551 +static int tf_analysis(const CELTMode *m, int len, int isTransient, 1.552 + int *tf_res, int lambda, celt_norm *X, int N0, int LM, 1.553 + int *tf_sum, opus_val16 tf_estimate, int tf_chan) 1.554 +{ 1.555 + int i; 1.556 + VARDECL(int, metric); 1.557 + int cost0; 1.558 + int cost1; 1.559 + VARDECL(int, path0); 1.560 + VARDECL(int, path1); 1.561 + VARDECL(celt_norm, tmp); 1.562 + VARDECL(celt_norm, tmp_1); 1.563 + int sel; 1.564 + int selcost[2]; 1.565 + int tf_select=0; 1.566 + opus_val16 bias; 1.567 + 1.568 + SAVE_STACK; 1.569 + bias = MULT16_16_Q14(QCONST16(.04f,15), MAX16(-QCONST16(.25f,14), QCONST16(.5f,14)-tf_estimate)); 1.570 + /*printf("%f ", bias);*/ 1.571 + 1.572 + ALLOC(metric, len, int); 1.573 + ALLOC(tmp, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm); 1.574 + ALLOC(tmp_1, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm); 1.575 + ALLOC(path0, len, int); 1.576 + ALLOC(path1, len, int); 1.577 + 1.578 + *tf_sum = 0; 1.579 + for (i=0;i<len;i++) 1.580 + { 1.581 + int j, k, N; 1.582 + int narrow; 1.583 + opus_val32 L1, best_L1; 1.584 + int best_level=0; 1.585 + N = (m->eBands[i+1]-m->eBands[i])<<LM; 1.586 + /* band is too narrow to be split down to LM=-1 */ 1.587 + narrow = (m->eBands[i+1]-m->eBands[i])==1; 1.588 + for (j=0;j<N;j++) 1.589 + tmp[j] = X[tf_chan*N0 + j+(m->eBands[i]<<LM)]; 1.590 + /* Just add the right channel if we're in stereo */ 1.591 + /*if (C==2) 1.592 + for (j=0;j<N;j++) 1.593 + tmp[j] = ADD16(SHR16(tmp[j], 1),SHR16(X[N0+j+(m->eBands[i]<<LM)], 1));*/ 1.594 + L1 = l1_metric(tmp, N, isTransient ? LM : 0, bias); 1.595 + best_L1 = L1; 1.596 + /* Check the -1 case for transients */ 1.597 + if (isTransient && !narrow) 1.598 + { 1.599 + for (j=0;j<N;j++) 1.600 + tmp_1[j] = tmp[j]; 1.601 + haar1(tmp_1, N>>LM, 1<<LM); 1.602 + L1 = l1_metric(tmp_1, N, LM+1, bias); 1.603 + if (L1<best_L1) 1.604 + { 1.605 + best_L1 = L1; 1.606 + best_level = -1; 1.607 + } 1.608 + } 1.609 + /*printf ("%f ", L1);*/ 1.610 + for (k=0;k<LM+!(isTransient||narrow);k++) 1.611 + { 1.612 + int B; 1.613 + 1.614 + if (isTransient) 1.615 + B = (LM-k-1); 1.616 + else 1.617 + B = k+1; 1.618 + 1.619 + haar1(tmp, N>>k, 1<<k); 1.620 + 1.621 + L1 = l1_metric(tmp, N, B, bias); 1.622 + 1.623 + if (L1 < best_L1) 1.624 + { 1.625 + best_L1 = L1; 1.626 + best_level = k+1; 1.627 + } 1.628 + } 1.629 + /*printf ("%d ", isTransient ? LM-best_level : best_level);*/ 1.630 + /* metric is in Q1 to be able to select the mid-point (-0.5) for narrower bands */ 1.631 + if (isTransient) 1.632 + metric[i] = 2*best_level; 1.633 + else 1.634 + metric[i] = -2*best_level; 1.635 + *tf_sum += (isTransient ? LM : 0) - metric[i]/2; 1.636 + /* For bands that can't be split to -1, set the metric to the half-way point to avoid 1.637 + biasing the decision */ 1.638 + if (narrow && (metric[i]==0 || metric[i]==-2*LM)) 1.639 + metric[i]-=1; 1.640 + /*printf("%d ", metric[i]);*/ 1.641 + } 1.642 + /*printf("\n");*/ 1.643 + /* Search for the optimal tf resolution, including tf_select */ 1.644 + tf_select = 0; 1.645 + for (sel=0;sel<2;sel++) 1.646 + { 1.647 + cost0 = 0; 1.648 + cost1 = isTransient ? 0 : lambda; 1.649 + for (i=1;i<len;i++) 1.650 + { 1.651 + int curr0, curr1; 1.652 + curr0 = IMIN(cost0, cost1 + lambda); 1.653 + curr1 = IMIN(cost0 + lambda, cost1); 1.654 + cost0 = curr0 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*sel+0]); 1.655 + cost1 = curr1 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*sel+1]); 1.656 + } 1.657 + cost0 = IMIN(cost0, cost1); 1.658 + selcost[sel]=cost0; 1.659 + } 1.660 + /* For now, we're conservative and only allow tf_select=1 for transients. 1.661 + * If tests confirm it's useful for non-transients, we could allow it. */ 1.662 + if (selcost[1]<selcost[0] && isTransient) 1.663 + tf_select=1; 1.664 + cost0 = 0; 1.665 + cost1 = isTransient ? 0 : lambda; 1.666 + /* Viterbi forward pass */ 1.667 + for (i=1;i<len;i++) 1.668 + { 1.669 + int curr0, curr1; 1.670 + int from0, from1; 1.671 + 1.672 + from0 = cost0; 1.673 + from1 = cost1 + lambda; 1.674 + if (from0 < from1) 1.675 + { 1.676 + curr0 = from0; 1.677 + path0[i]= 0; 1.678 + } else { 1.679 + curr0 = from1; 1.680 + path0[i]= 1; 1.681 + } 1.682 + 1.683 + from0 = cost0 + lambda; 1.684 + from1 = cost1; 1.685 + if (from0 < from1) 1.686 + { 1.687 + curr1 = from0; 1.688 + path1[i]= 0; 1.689 + } else { 1.690 + curr1 = from1; 1.691 + path1[i]= 1; 1.692 + } 1.693 + cost0 = curr0 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*tf_select+0]); 1.694 + cost1 = curr1 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*tf_select+1]); 1.695 + } 1.696 + tf_res[len-1] = cost0 < cost1 ? 0 : 1; 1.697 + /* Viterbi backward pass to check the decisions */ 1.698 + for (i=len-2;i>=0;i--) 1.699 + { 1.700 + if (tf_res[i+1] == 1) 1.701 + tf_res[i] = path1[i+1]; 1.702 + else 1.703 + tf_res[i] = path0[i+1]; 1.704 + } 1.705 + /*printf("%d %f\n", *tf_sum, tf_estimate);*/ 1.706 + RESTORE_STACK; 1.707 +#ifdef FUZZING 1.708 + tf_select = rand()&0x1; 1.709 + tf_res[0] = rand()&0x1; 1.710 + for (i=1;i<len;i++) 1.711 + tf_res[i] = tf_res[i-1] ^ ((rand()&0xF) == 0); 1.712 +#endif 1.713 + return tf_select; 1.714 +} 1.715 + 1.716 +static void tf_encode(int start, int end, int isTransient, int *tf_res, int LM, int tf_select, ec_enc *enc) 1.717 +{ 1.718 + int curr, i; 1.719 + int tf_select_rsv; 1.720 + int tf_changed; 1.721 + int logp; 1.722 + opus_uint32 budget; 1.723 + opus_uint32 tell; 1.724 + budget = enc->storage*8; 1.725 + tell = ec_tell(enc); 1.726 + logp = isTransient ? 2 : 4; 1.727 + /* Reserve space to code the tf_select decision. */ 1.728 + tf_select_rsv = LM>0 && tell+logp+1 <= budget; 1.729 + budget -= tf_select_rsv; 1.730 + curr = tf_changed = 0; 1.731 + for (i=start;i<end;i++) 1.732 + { 1.733 + if (tell+logp<=budget) 1.734 + { 1.735 + ec_enc_bit_logp(enc, tf_res[i] ^ curr, logp); 1.736 + tell = ec_tell(enc); 1.737 + curr = tf_res[i]; 1.738 + tf_changed |= curr; 1.739 + } 1.740 + else 1.741 + tf_res[i] = curr; 1.742 + logp = isTransient ? 4 : 5; 1.743 + } 1.744 + /* Only code tf_select if it would actually make a difference. */ 1.745 + if (tf_select_rsv && 1.746 + tf_select_table[LM][4*isTransient+0+tf_changed]!= 1.747 + tf_select_table[LM][4*isTransient+2+tf_changed]) 1.748 + ec_enc_bit_logp(enc, tf_select, 1); 1.749 + else 1.750 + tf_select = 0; 1.751 + for (i=start;i<end;i++) 1.752 + tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]]; 1.753 + /*for(i=0;i<end;i++)printf("%d ", isTransient ? tf_res[i] : LM+tf_res[i]);printf("\n");*/ 1.754 +} 1.755 + 1.756 + 1.757 +static int alloc_trim_analysis(const CELTMode *m, const celt_norm *X, 1.758 + const opus_val16 *bandLogE, int end, int LM, int C, int N0, 1.759 + AnalysisInfo *analysis, opus_val16 *stereo_saving, opus_val16 tf_estimate, 1.760 + int intensity, opus_val16 surround_trim) 1.761 +{ 1.762 + int i; 1.763 + opus_val32 diff=0; 1.764 + int c; 1.765 + int trim_index = 5; 1.766 + opus_val16 trim = QCONST16(5.f, 8); 1.767 + opus_val16 logXC, logXC2; 1.768 + if (C==2) 1.769 + { 1.770 + opus_val16 sum = 0; /* Q10 */ 1.771 + opus_val16 minXC; /* Q10 */ 1.772 + /* Compute inter-channel correlation for low frequencies */ 1.773 + for (i=0;i<8;i++) 1.774 + { 1.775 + int j; 1.776 + opus_val32 partial = 0; 1.777 + for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++) 1.778 + partial = MAC16_16(partial, X[j], X[N0+j]); 1.779 + sum = ADD16(sum, EXTRACT16(SHR32(partial, 18))); 1.780 + } 1.781 + sum = MULT16_16_Q15(QCONST16(1.f/8, 15), sum); 1.782 + sum = MIN16(QCONST16(1.f, 10), ABS16(sum)); 1.783 + minXC = sum; 1.784 + for (i=8;i<intensity;i++) 1.785 + { 1.786 + int j; 1.787 + opus_val32 partial = 0; 1.788 + for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++) 1.789 + partial = MAC16_16(partial, X[j], X[N0+j]); 1.790 + minXC = MIN16(minXC, ABS16(EXTRACT16(SHR32(partial, 18)))); 1.791 + } 1.792 + minXC = MIN16(QCONST16(1.f, 10), ABS16(minXC)); 1.793 + /*printf ("%f\n", sum);*/ 1.794 + if (sum > QCONST16(.995f,10)) 1.795 + trim_index-=4; 1.796 + else if (sum > QCONST16(.92f,10)) 1.797 + trim_index-=3; 1.798 + else if (sum > QCONST16(.85f,10)) 1.799 + trim_index-=2; 1.800 + else if (sum > QCONST16(.8f,10)) 1.801 + trim_index-=1; 1.802 + /* mid-side savings estimations based on the LF average*/ 1.803 + logXC = celt_log2(QCONST32(1.001f, 20)-MULT16_16(sum, sum)); 1.804 + /* mid-side savings estimations based on min correlation */ 1.805 + logXC2 = MAX16(HALF16(logXC), celt_log2(QCONST32(1.001f, 20)-MULT16_16(minXC, minXC))); 1.806 +#ifdef FIXED_POINT 1.807 + /* Compensate for Q20 vs Q14 input and convert output to Q8 */ 1.808 + logXC = PSHR32(logXC-QCONST16(6.f, DB_SHIFT),DB_SHIFT-8); 1.809 + logXC2 = PSHR32(logXC2-QCONST16(6.f, DB_SHIFT),DB_SHIFT-8); 1.810 +#endif 1.811 + 1.812 + trim += MAX16(-QCONST16(4.f, 8), MULT16_16_Q15(QCONST16(.75f,15),logXC)); 1.813 + *stereo_saving = MIN16(*stereo_saving + QCONST16(0.25f, 8), -HALF16(logXC2)); 1.814 + } 1.815 + 1.816 + /* Estimate spectral tilt */ 1.817 + c=0; do { 1.818 + for (i=0;i<end-1;i++) 1.819 + { 1.820 + diff += bandLogE[i+c*m->nbEBands]*(opus_int32)(2+2*i-end); 1.821 + } 1.822 + } while (++c<C); 1.823 + diff /= C*(end-1); 1.824 + /*printf("%f\n", diff);*/ 1.825 + if (diff > QCONST16(2.f, DB_SHIFT)) 1.826 + trim_index--; 1.827 + if (diff > QCONST16(8.f, DB_SHIFT)) 1.828 + trim_index--; 1.829 + if (diff < -QCONST16(4.f, DB_SHIFT)) 1.830 + trim_index++; 1.831 + if (diff < -QCONST16(10.f, DB_SHIFT)) 1.832 + trim_index++; 1.833 + trim -= MAX16(-QCONST16(2.f, 8), MIN16(QCONST16(2.f, 8), SHR16(diff+QCONST16(1.f, DB_SHIFT),DB_SHIFT-8)/6 )); 1.834 + trim -= SHR16(surround_trim, DB_SHIFT-8); 1.835 + trim -= 2*SHR16(tf_estimate, 14-8); 1.836 +#ifndef DISABLE_FLOAT_API 1.837 + if (analysis->valid) 1.838 + { 1.839 + trim -= MAX16(-QCONST16(2.f, 8), MIN16(QCONST16(2.f, 8), 1.840 + (opus_val16)(QCONST16(2.f, 8)*(analysis->tonality_slope+.05f)))); 1.841 + } 1.842 +#endif 1.843 + 1.844 +#ifdef FIXED_POINT 1.845 + trim_index = PSHR32(trim, 8); 1.846 +#else 1.847 + trim_index = (int)floor(.5f+trim); 1.848 +#endif 1.849 + if (trim_index<0) 1.850 + trim_index = 0; 1.851 + if (trim_index>10) 1.852 + trim_index = 10; 1.853 + /*printf("%d\n", trim_index);*/ 1.854 +#ifdef FUZZING 1.855 + trim_index = rand()%11; 1.856 +#endif 1.857 + return trim_index; 1.858 +} 1.859 + 1.860 +static int stereo_analysis(const CELTMode *m, const celt_norm *X, 1.861 + int LM, int N0) 1.862 +{ 1.863 + int i; 1.864 + int thetas; 1.865 + opus_val32 sumLR = EPSILON, sumMS = EPSILON; 1.866 + 1.867 + /* Use the L1 norm to model the entropy of the L/R signal vs the M/S signal */ 1.868 + for (i=0;i<13;i++) 1.869 + { 1.870 + int j; 1.871 + for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++) 1.872 + { 1.873 + opus_val32 L, R, M, S; 1.874 + /* We cast to 32-bit first because of the -32768 case */ 1.875 + L = EXTEND32(X[j]); 1.876 + R = EXTEND32(X[N0+j]); 1.877 + M = ADD32(L, R); 1.878 + S = SUB32(L, R); 1.879 + sumLR = ADD32(sumLR, ADD32(ABS32(L), ABS32(R))); 1.880 + sumMS = ADD32(sumMS, ADD32(ABS32(M), ABS32(S))); 1.881 + } 1.882 + } 1.883 + sumMS = MULT16_32_Q15(QCONST16(0.707107f, 15), sumMS); 1.884 + thetas = 13; 1.885 + /* We don't need thetas for lower bands with LM<=1 */ 1.886 + if (LM<=1) 1.887 + thetas -= 8; 1.888 + return MULT16_32_Q15((m->eBands[13]<<(LM+1))+thetas, sumMS) 1.889 + > MULT16_32_Q15(m->eBands[13]<<(LM+1), sumLR); 1.890 +} 1.891 + 1.892 +static opus_val16 dynalloc_analysis(const opus_val16 *bandLogE, const opus_val16 *bandLogE2, 1.893 + int nbEBands, int start, int end, int C, int *offsets, int lsb_depth, const opus_int16 *logN, 1.894 + int isTransient, int vbr, int constrained_vbr, const opus_int16 *eBands, int LM, 1.895 + int effectiveBytes, opus_int32 *tot_boost_, int lfe, opus_val16 *surround_dynalloc) 1.896 +{ 1.897 + int i, c; 1.898 + opus_int32 tot_boost=0; 1.899 + opus_val16 maxDepth; 1.900 + VARDECL(opus_val16, follower); 1.901 + VARDECL(opus_val16, noise_floor); 1.902 + SAVE_STACK; 1.903 + ALLOC(follower, C*nbEBands, opus_val16); 1.904 + ALLOC(noise_floor, C*nbEBands, opus_val16); 1.905 + for (i=0;i<nbEBands;i++) 1.906 + offsets[i] = 0; 1.907 + /* Dynamic allocation code */ 1.908 + maxDepth=-QCONST16(31.9f, DB_SHIFT); 1.909 + for (i=0;i<end;i++) 1.910 + { 1.911 + /* Noise floor must take into account eMeans, the depth, the width of the bands 1.912 + and the preemphasis filter (approx. square of bark band ID) */ 1.913 + noise_floor[i] = MULT16_16(QCONST16(0.0625f, DB_SHIFT),logN[i]) 1.914 + +QCONST16(.5f,DB_SHIFT)+SHL16(9-lsb_depth,DB_SHIFT)-SHL16(eMeans[i],6) 1.915 + +MULT16_16(QCONST16(.0062,DB_SHIFT),(i+5)*(i+5)); 1.916 + } 1.917 + c=0;do 1.918 + { 1.919 + for (i=0;i<end;i++) 1.920 + maxDepth = MAX16(maxDepth, bandLogE[c*nbEBands+i]-noise_floor[i]); 1.921 + } while (++c<C); 1.922 + /* Make sure that dynamic allocation can't make us bust the budget */ 1.923 + if (effectiveBytes > 50 && LM>=1 && !lfe) 1.924 + { 1.925 + int last=0; 1.926 + c=0;do 1.927 + { 1.928 + follower[c*nbEBands] = bandLogE2[c*nbEBands]; 1.929 + for (i=1;i<end;i++) 1.930 + { 1.931 + /* The last band to be at least 3 dB higher than the previous one 1.932 + is the last we'll consider. Otherwise, we run into problems on 1.933 + bandlimited signals. */ 1.934 + if (bandLogE2[c*nbEBands+i] > bandLogE2[c*nbEBands+i-1]+QCONST16(.5f,DB_SHIFT)) 1.935 + last=i; 1.936 + follower[c*nbEBands+i] = MIN16(follower[c*nbEBands+i-1]+QCONST16(1.5f,DB_SHIFT), bandLogE2[c*nbEBands+i]); 1.937 + } 1.938 + for (i=last-1;i>=0;i--) 1.939 + follower[c*nbEBands+i] = MIN16(follower[c*nbEBands+i], MIN16(follower[c*nbEBands+i+1]+QCONST16(2.f,DB_SHIFT), bandLogE2[c*nbEBands+i])); 1.940 + for (i=0;i<end;i++) 1.941 + follower[c*nbEBands+i] = MAX16(follower[c*nbEBands+i], noise_floor[i]); 1.942 + } while (++c<C); 1.943 + if (C==2) 1.944 + { 1.945 + for (i=start;i<end;i++) 1.946 + { 1.947 + /* Consider 24 dB "cross-talk" */ 1.948 + follower[nbEBands+i] = MAX16(follower[nbEBands+i], follower[ i]-QCONST16(4.f,DB_SHIFT)); 1.949 + follower[ i] = MAX16(follower[ i], follower[nbEBands+i]-QCONST16(4.f,DB_SHIFT)); 1.950 + follower[i] = HALF16(MAX16(0, bandLogE[i]-follower[i]) + MAX16(0, bandLogE[nbEBands+i]-follower[nbEBands+i])); 1.951 + } 1.952 + } else { 1.953 + for (i=start;i<end;i++) 1.954 + { 1.955 + follower[i] = MAX16(0, bandLogE[i]-follower[i]); 1.956 + } 1.957 + } 1.958 + for (i=start;i<end;i++) 1.959 + follower[i] = MAX16(follower[i], surround_dynalloc[i]); 1.960 + /* For non-transient CBR/CVBR frames, halve the dynalloc contribution */ 1.961 + if ((!vbr || constrained_vbr)&&!isTransient) 1.962 + { 1.963 + for (i=start;i<end;i++) 1.964 + follower[i] = HALF16(follower[i]); 1.965 + } 1.966 + for (i=start;i<end;i++) 1.967 + { 1.968 + int width; 1.969 + int boost; 1.970 + int boost_bits; 1.971 + 1.972 + if (i<8) 1.973 + follower[i] *= 2; 1.974 + if (i>=12) 1.975 + follower[i] = HALF16(follower[i]); 1.976 + follower[i] = MIN16(follower[i], QCONST16(4, DB_SHIFT)); 1.977 + 1.978 + width = C*(eBands[i+1]-eBands[i])<<LM; 1.979 + if (width<6) 1.980 + { 1.981 + boost = (int)SHR32(EXTEND32(follower[i]),DB_SHIFT); 1.982 + boost_bits = boost*width<<BITRES; 1.983 + } else if (width > 48) { 1.984 + boost = (int)SHR32(EXTEND32(follower[i])*8,DB_SHIFT); 1.985 + boost_bits = (boost*width<<BITRES)/8; 1.986 + } else { 1.987 + boost = (int)SHR32(EXTEND32(follower[i])*width/6,DB_SHIFT); 1.988 + boost_bits = boost*6<<BITRES; 1.989 + } 1.990 + /* For CBR and non-transient CVBR frames, limit dynalloc to 1/4 of the bits */ 1.991 + if ((!vbr || (constrained_vbr&&!isTransient)) 1.992 + && (tot_boost+boost_bits)>>BITRES>>3 > effectiveBytes/4) 1.993 + { 1.994 + opus_int32 cap = ((effectiveBytes/4)<<BITRES<<3); 1.995 + offsets[i] = cap-tot_boost; 1.996 + tot_boost = cap; 1.997 + break; 1.998 + } else { 1.999 + offsets[i] = boost; 1.1000 + tot_boost += boost_bits; 1.1001 + } 1.1002 + } 1.1003 + } 1.1004 + *tot_boost_ = tot_boost; 1.1005 + RESTORE_STACK; 1.1006 + return maxDepth; 1.1007 +} 1.1008 + 1.1009 + 1.1010 +static int run_prefilter(CELTEncoder *st, celt_sig *in, celt_sig *prefilter_mem, int CC, int N, 1.1011 + int prefilter_tapset, int *pitch, opus_val16 *gain, int *qgain, int enabled, int nbAvailableBytes) 1.1012 +{ 1.1013 + int c; 1.1014 + VARDECL(celt_sig, _pre); 1.1015 + celt_sig *pre[2]; 1.1016 + const CELTMode *mode; 1.1017 + int pitch_index; 1.1018 + opus_val16 gain1; 1.1019 + opus_val16 pf_threshold; 1.1020 + int pf_on; 1.1021 + int qg; 1.1022 + SAVE_STACK; 1.1023 + 1.1024 + mode = st->mode; 1.1025 + ALLOC(_pre, CC*(N+COMBFILTER_MAXPERIOD), celt_sig); 1.1026 + 1.1027 + pre[0] = _pre; 1.1028 + pre[1] = _pre + (N+COMBFILTER_MAXPERIOD); 1.1029 + 1.1030 + 1.1031 + c=0; do { 1.1032 + OPUS_COPY(pre[c], prefilter_mem+c*COMBFILTER_MAXPERIOD, COMBFILTER_MAXPERIOD); 1.1033 + OPUS_COPY(pre[c]+COMBFILTER_MAXPERIOD, in+c*(N+st->overlap)+st->overlap, N); 1.1034 + } while (++c<CC); 1.1035 + 1.1036 + if (enabled) 1.1037 + { 1.1038 + VARDECL(opus_val16, pitch_buf); 1.1039 + ALLOC(pitch_buf, (COMBFILTER_MAXPERIOD+N)>>1, opus_val16); 1.1040 + 1.1041 + pitch_downsample(pre, pitch_buf, COMBFILTER_MAXPERIOD+N, CC, st->arch); 1.1042 + /* Don't search for the fir last 1.5 octave of the range because 1.1043 + there's too many false-positives due to short-term correlation */ 1.1044 + pitch_search(pitch_buf+(COMBFILTER_MAXPERIOD>>1), pitch_buf, N, 1.1045 + COMBFILTER_MAXPERIOD-3*COMBFILTER_MINPERIOD, &pitch_index, 1.1046 + st->arch); 1.1047 + pitch_index = COMBFILTER_MAXPERIOD-pitch_index; 1.1048 + 1.1049 + gain1 = remove_doubling(pitch_buf, COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD, 1.1050 + N, &pitch_index, st->prefilter_period, st->prefilter_gain); 1.1051 + if (pitch_index > COMBFILTER_MAXPERIOD-2) 1.1052 + pitch_index = COMBFILTER_MAXPERIOD-2; 1.1053 + gain1 = MULT16_16_Q15(QCONST16(.7f,15),gain1); 1.1054 + /*printf("%d %d %f %f\n", pitch_change, pitch_index, gain1, st->analysis.tonality);*/ 1.1055 + if (st->loss_rate>2) 1.1056 + gain1 = HALF32(gain1); 1.1057 + if (st->loss_rate>4) 1.1058 + gain1 = HALF32(gain1); 1.1059 + if (st->loss_rate>8) 1.1060 + gain1 = 0; 1.1061 + } else { 1.1062 + gain1 = 0; 1.1063 + pitch_index = COMBFILTER_MINPERIOD; 1.1064 + } 1.1065 + 1.1066 + /* Gain threshold for enabling the prefilter/postfilter */ 1.1067 + pf_threshold = QCONST16(.2f,15); 1.1068 + 1.1069 + /* Adjusting the threshold based on rate and continuity */ 1.1070 + if (abs(pitch_index-st->prefilter_period)*10>pitch_index) 1.1071 + pf_threshold += QCONST16(.2f,15); 1.1072 + if (nbAvailableBytes<25) 1.1073 + pf_threshold += QCONST16(.1f,15); 1.1074 + if (nbAvailableBytes<35) 1.1075 + pf_threshold += QCONST16(.1f,15); 1.1076 + if (st->prefilter_gain > QCONST16(.4f,15)) 1.1077 + pf_threshold -= QCONST16(.1f,15); 1.1078 + if (st->prefilter_gain > QCONST16(.55f,15)) 1.1079 + pf_threshold -= QCONST16(.1f,15); 1.1080 + 1.1081 + /* Hard threshold at 0.2 */ 1.1082 + pf_threshold = MAX16(pf_threshold, QCONST16(.2f,15)); 1.1083 + if (gain1<pf_threshold) 1.1084 + { 1.1085 + gain1 = 0; 1.1086 + pf_on = 0; 1.1087 + qg = 0; 1.1088 + } else { 1.1089 + /*This block is not gated by a total bits check only because 1.1090 + of the nbAvailableBytes check above.*/ 1.1091 + if (ABS16(gain1-st->prefilter_gain)<QCONST16(.1f,15)) 1.1092 + gain1=st->prefilter_gain; 1.1093 + 1.1094 +#ifdef FIXED_POINT 1.1095 + qg = ((gain1+1536)>>10)/3-1; 1.1096 +#else 1.1097 + qg = (int)floor(.5f+gain1*32/3)-1; 1.1098 +#endif 1.1099 + qg = IMAX(0, IMIN(7, qg)); 1.1100 + gain1 = QCONST16(0.09375f,15)*(qg+1); 1.1101 + pf_on = 1; 1.1102 + } 1.1103 + /*printf("%d %f\n", pitch_index, gain1);*/ 1.1104 + 1.1105 + c=0; do { 1.1106 + int offset = mode->shortMdctSize-st->overlap; 1.1107 + st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD); 1.1108 + OPUS_COPY(in+c*(N+st->overlap), st->in_mem+c*(st->overlap), st->overlap); 1.1109 + if (offset) 1.1110 + comb_filter(in+c*(N+st->overlap)+st->overlap, pre[c]+COMBFILTER_MAXPERIOD, 1.1111 + st->prefilter_period, st->prefilter_period, offset, -st->prefilter_gain, -st->prefilter_gain, 1.1112 + st->prefilter_tapset, st->prefilter_tapset, NULL, 0); 1.1113 + 1.1114 + comb_filter(in+c*(N+st->overlap)+st->overlap+offset, pre[c]+COMBFILTER_MAXPERIOD+offset, 1.1115 + st->prefilter_period, pitch_index, N-offset, -st->prefilter_gain, -gain1, 1.1116 + st->prefilter_tapset, prefilter_tapset, mode->window, st->overlap); 1.1117 + OPUS_COPY(st->in_mem+c*(st->overlap), in+c*(N+st->overlap)+N, st->overlap); 1.1118 + 1.1119 + if (N>COMBFILTER_MAXPERIOD) 1.1120 + { 1.1121 + OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD, pre[c]+N, COMBFILTER_MAXPERIOD); 1.1122 + } else { 1.1123 + OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD, prefilter_mem+c*COMBFILTER_MAXPERIOD+N, COMBFILTER_MAXPERIOD-N); 1.1124 + OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD+COMBFILTER_MAXPERIOD-N, pre[c]+COMBFILTER_MAXPERIOD, N); 1.1125 + } 1.1126 + } while (++c<CC); 1.1127 + 1.1128 + RESTORE_STACK; 1.1129 + *gain = gain1; 1.1130 + *pitch = pitch_index; 1.1131 + *qgain = qg; 1.1132 + return pf_on; 1.1133 +} 1.1134 + 1.1135 +static int compute_vbr(const CELTMode *mode, AnalysisInfo *analysis, opus_int32 base_target, 1.1136 + int LM, opus_int32 bitrate, int lastCodedBands, int C, int intensity, 1.1137 + int constrained_vbr, opus_val16 stereo_saving, int tot_boost, 1.1138 + opus_val16 tf_estimate, int pitch_change, opus_val16 maxDepth, 1.1139 + int variable_duration, int lfe, int has_surround_mask, opus_val16 surround_masking, 1.1140 + opus_val16 temporal_vbr) 1.1141 +{ 1.1142 + /* The target rate in 8th bits per frame */ 1.1143 + opus_int32 target; 1.1144 + int coded_bins; 1.1145 + int coded_bands; 1.1146 + opus_val16 tf_calibration; 1.1147 + int nbEBands; 1.1148 + const opus_int16 *eBands; 1.1149 + 1.1150 + nbEBands = mode->nbEBands; 1.1151 + eBands = mode->eBands; 1.1152 + 1.1153 + coded_bands = lastCodedBands ? lastCodedBands : nbEBands; 1.1154 + coded_bins = eBands[coded_bands]<<LM; 1.1155 + if (C==2) 1.1156 + coded_bins += eBands[IMIN(intensity, coded_bands)]<<LM; 1.1157 + 1.1158 + target = base_target; 1.1159 + 1.1160 + /*printf("%f %f %f %f %d %d ", st->analysis.activity, st->analysis.tonality, tf_estimate, st->stereo_saving, tot_boost, coded_bands);*/ 1.1161 +#ifndef DISABLE_FLOAT_API 1.1162 + if (analysis->valid && analysis->activity<.4) 1.1163 + target -= (opus_int32)((coded_bins<<BITRES)*(.4f-analysis->activity)); 1.1164 +#endif 1.1165 + /* Stereo savings */ 1.1166 + if (C==2) 1.1167 + { 1.1168 + int coded_stereo_bands; 1.1169 + int coded_stereo_dof; 1.1170 + opus_val16 max_frac; 1.1171 + coded_stereo_bands = IMIN(intensity, coded_bands); 1.1172 + coded_stereo_dof = (eBands[coded_stereo_bands]<<LM)-coded_stereo_bands; 1.1173 + /* Maximum fraction of the bits we can save if the signal is mono. */ 1.1174 + max_frac = DIV32_16(MULT16_16(QCONST16(0.8f, 15), coded_stereo_dof), coded_bins); 1.1175 + stereo_saving = MIN16(stereo_saving, QCONST16(1.f, 8)); 1.1176 + /*printf("%d %d %d ", coded_stereo_dof, coded_bins, tot_boost);*/ 1.1177 + target -= (opus_int32)MIN32(MULT16_32_Q15(max_frac,target), 1.1178 + SHR32(MULT16_16(stereo_saving-QCONST16(0.1f,8),(coded_stereo_dof<<BITRES)),8)); 1.1179 + } 1.1180 + /* Boost the rate according to dynalloc (minus the dynalloc average for calibration). */ 1.1181 + target += tot_boost-(16<<LM); 1.1182 + /* Apply transient boost, compensating for average boost. */ 1.1183 + tf_calibration = variable_duration==OPUS_FRAMESIZE_VARIABLE ? 1.1184 + QCONST16(0.02f,14) : QCONST16(0.04f,14); 1.1185 + target += (opus_int32)SHL32(MULT16_32_Q15(tf_estimate-tf_calibration, target),1); 1.1186 + 1.1187 +#ifndef DISABLE_FLOAT_API 1.1188 + /* Apply tonality boost */ 1.1189 + if (analysis->valid && !lfe) 1.1190 + { 1.1191 + opus_int32 tonal_target; 1.1192 + float tonal; 1.1193 + 1.1194 + /* Tonality boost (compensating for the average). */ 1.1195 + tonal = MAX16(0.f,analysis->tonality-.15f)-0.09f; 1.1196 + tonal_target = target + (opus_int32)((coded_bins<<BITRES)*1.2f*tonal); 1.1197 + if (pitch_change) 1.1198 + tonal_target += (opus_int32)((coded_bins<<BITRES)*.8f); 1.1199 + /*printf("%f %f ", analysis->tonality, tonal);*/ 1.1200 + target = tonal_target; 1.1201 + } 1.1202 +#endif 1.1203 + 1.1204 + if (has_surround_mask&&!lfe) 1.1205 + { 1.1206 + opus_int32 surround_target = target + (opus_int32)SHR32(MULT16_16(surround_masking,coded_bins<<BITRES), DB_SHIFT); 1.1207 + /*printf("%f %d %d %d %d %d %d ", surround_masking, coded_bins, st->end, st->intensity, surround_target, target, st->bitrate);*/ 1.1208 + target = IMAX(target/4, surround_target); 1.1209 + } 1.1210 + 1.1211 + { 1.1212 + opus_int32 floor_depth; 1.1213 + int bins; 1.1214 + bins = eBands[nbEBands-2]<<LM; 1.1215 + /*floor_depth = SHR32(MULT16_16((C*bins<<BITRES),celt_log2(SHL32(MAX16(1,sample_max),13))), DB_SHIFT);*/ 1.1216 + floor_depth = (opus_int32)SHR32(MULT16_16((C*bins<<BITRES),maxDepth), DB_SHIFT); 1.1217 + floor_depth = IMAX(floor_depth, target>>2); 1.1218 + target = IMIN(target, floor_depth); 1.1219 + /*printf("%f %d\n", maxDepth, floor_depth);*/ 1.1220 + } 1.1221 + 1.1222 + if ((!has_surround_mask||lfe) && (constrained_vbr || bitrate<64000)) 1.1223 + { 1.1224 + opus_val16 rate_factor; 1.1225 +#ifdef FIXED_POINT 1.1226 + rate_factor = MAX16(0,(bitrate-32000)); 1.1227 +#else 1.1228 + rate_factor = MAX16(0,(1.f/32768)*(bitrate-32000)); 1.1229 +#endif 1.1230 + if (constrained_vbr) 1.1231 + rate_factor = MIN16(rate_factor, QCONST16(0.67f, 15)); 1.1232 + target = base_target + (opus_int32)MULT16_32_Q15(rate_factor, target-base_target); 1.1233 + 1.1234 + } 1.1235 + 1.1236 + if (!has_surround_mask && tf_estimate < QCONST16(.2f, 14)) 1.1237 + { 1.1238 + opus_val16 amount; 1.1239 + opus_val16 tvbr_factor; 1.1240 + amount = MULT16_16_Q15(QCONST16(.0000031f, 30), IMAX(0, IMIN(32000, 96000-bitrate))); 1.1241 + tvbr_factor = SHR32(MULT16_16(temporal_vbr, amount), DB_SHIFT); 1.1242 + target += (opus_int32)MULT16_32_Q15(tvbr_factor, target); 1.1243 + } 1.1244 + 1.1245 + /* Don't allow more than doubling the rate */ 1.1246 + target = IMIN(2*base_target, target); 1.1247 + 1.1248 + return target; 1.1249 +} 1.1250 + 1.1251 +int celt_encode_with_ec(CELTEncoder * OPUS_RESTRICT st, const opus_val16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes, ec_enc *enc) 1.1252 +{ 1.1253 + int i, c, N; 1.1254 + opus_int32 bits; 1.1255 + ec_enc _enc; 1.1256 + VARDECL(celt_sig, in); 1.1257 + VARDECL(celt_sig, freq); 1.1258 + VARDECL(celt_norm, X); 1.1259 + VARDECL(celt_ener, bandE); 1.1260 + VARDECL(opus_val16, bandLogE); 1.1261 + VARDECL(opus_val16, bandLogE2); 1.1262 + VARDECL(int, fine_quant); 1.1263 + VARDECL(opus_val16, error); 1.1264 + VARDECL(int, pulses); 1.1265 + VARDECL(int, cap); 1.1266 + VARDECL(int, offsets); 1.1267 + VARDECL(int, fine_priority); 1.1268 + VARDECL(int, tf_res); 1.1269 + VARDECL(unsigned char, collapse_masks); 1.1270 + celt_sig *prefilter_mem; 1.1271 + opus_val16 *oldBandE, *oldLogE, *oldLogE2; 1.1272 + int shortBlocks=0; 1.1273 + int isTransient=0; 1.1274 + const int CC = st->channels; 1.1275 + const int C = st->stream_channels; 1.1276 + int LM, M; 1.1277 + int tf_select; 1.1278 + int nbFilledBytes, nbAvailableBytes; 1.1279 + int effEnd; 1.1280 + int codedBands; 1.1281 + int tf_sum; 1.1282 + int alloc_trim; 1.1283 + int pitch_index=COMBFILTER_MINPERIOD; 1.1284 + opus_val16 gain1 = 0; 1.1285 + int dual_stereo=0; 1.1286 + int effectiveBytes; 1.1287 + int dynalloc_logp; 1.1288 + opus_int32 vbr_rate; 1.1289 + opus_int32 total_bits; 1.1290 + opus_int32 total_boost; 1.1291 + opus_int32 balance; 1.1292 + opus_int32 tell; 1.1293 + int prefilter_tapset=0; 1.1294 + int pf_on; 1.1295 + int anti_collapse_rsv; 1.1296 + int anti_collapse_on=0; 1.1297 + int silence=0; 1.1298 + int tf_chan = 0; 1.1299 + opus_val16 tf_estimate; 1.1300 + int pitch_change=0; 1.1301 + opus_int32 tot_boost; 1.1302 + opus_val32 sample_max; 1.1303 + opus_val16 maxDepth; 1.1304 + const OpusCustomMode *mode; 1.1305 + int nbEBands; 1.1306 + int overlap; 1.1307 + const opus_int16 *eBands; 1.1308 + int secondMdct; 1.1309 + int signalBandwidth; 1.1310 + int transient_got_disabled=0; 1.1311 + opus_val16 surround_masking=0; 1.1312 + opus_val16 temporal_vbr=0; 1.1313 + opus_val16 surround_trim = 0; 1.1314 + opus_int32 equiv_rate = 510000; 1.1315 + VARDECL(opus_val16, surround_dynalloc); 1.1316 + ALLOC_STACK; 1.1317 + 1.1318 + mode = st->mode; 1.1319 + nbEBands = mode->nbEBands; 1.1320 + overlap = mode->overlap; 1.1321 + eBands = mode->eBands; 1.1322 + tf_estimate = 0; 1.1323 + if (nbCompressedBytes<2 || pcm==NULL) 1.1324 + { 1.1325 + RESTORE_STACK; 1.1326 + return OPUS_BAD_ARG; 1.1327 + } 1.1328 + 1.1329 + frame_size *= st->upsample; 1.1330 + for (LM=0;LM<=mode->maxLM;LM++) 1.1331 + if (mode->shortMdctSize<<LM==frame_size) 1.1332 + break; 1.1333 + if (LM>mode->maxLM) 1.1334 + { 1.1335 + RESTORE_STACK; 1.1336 + return OPUS_BAD_ARG; 1.1337 + } 1.1338 + M=1<<LM; 1.1339 + N = M*mode->shortMdctSize; 1.1340 + 1.1341 + prefilter_mem = st->in_mem+CC*(st->overlap); 1.1342 + oldBandE = (opus_val16*)(st->in_mem+CC*(st->overlap+COMBFILTER_MAXPERIOD)); 1.1343 + oldLogE = oldBandE + CC*nbEBands; 1.1344 + oldLogE2 = oldLogE + CC*nbEBands; 1.1345 + 1.1346 + if (enc==NULL) 1.1347 + { 1.1348 + tell=1; 1.1349 + nbFilledBytes=0; 1.1350 + } else { 1.1351 + tell=ec_tell(enc); 1.1352 + nbFilledBytes=(tell+4)>>3; 1.1353 + } 1.1354 + 1.1355 +#ifdef CUSTOM_MODES 1.1356 + if (st->signalling && enc==NULL) 1.1357 + { 1.1358 + int tmp = (mode->effEBands-st->end)>>1; 1.1359 + st->end = IMAX(1, mode->effEBands-tmp); 1.1360 + compressed[0] = tmp<<5; 1.1361 + compressed[0] |= LM<<3; 1.1362 + compressed[0] |= (C==2)<<2; 1.1363 + /* Convert "standard mode" to Opus header */ 1.1364 + if (mode->Fs==48000 && mode->shortMdctSize==120) 1.1365 + { 1.1366 + int c0 = toOpus(compressed[0]); 1.1367 + if (c0<0) 1.1368 + { 1.1369 + RESTORE_STACK; 1.1370 + return OPUS_BAD_ARG; 1.1371 + } 1.1372 + compressed[0] = c0; 1.1373 + } 1.1374 + compressed++; 1.1375 + nbCompressedBytes--; 1.1376 + } 1.1377 +#else 1.1378 + celt_assert(st->signalling==0); 1.1379 +#endif 1.1380 + 1.1381 + /* Can't produce more than 1275 output bytes */ 1.1382 + nbCompressedBytes = IMIN(nbCompressedBytes,1275); 1.1383 + nbAvailableBytes = nbCompressedBytes - nbFilledBytes; 1.1384 + 1.1385 + if (st->vbr && st->bitrate!=OPUS_BITRATE_MAX) 1.1386 + { 1.1387 + opus_int32 den=mode->Fs>>BITRES; 1.1388 + vbr_rate=(st->bitrate*frame_size+(den>>1))/den; 1.1389 +#ifdef CUSTOM_MODES 1.1390 + if (st->signalling) 1.1391 + vbr_rate -= 8<<BITRES; 1.1392 +#endif 1.1393 + effectiveBytes = vbr_rate>>(3+BITRES); 1.1394 + } else { 1.1395 + opus_int32 tmp; 1.1396 + vbr_rate = 0; 1.1397 + tmp = st->bitrate*frame_size; 1.1398 + if (tell>1) 1.1399 + tmp += tell; 1.1400 + if (st->bitrate!=OPUS_BITRATE_MAX) 1.1401 + nbCompressedBytes = IMAX(2, IMIN(nbCompressedBytes, 1.1402 + (tmp+4*mode->Fs)/(8*mode->Fs)-!!st->signalling)); 1.1403 + effectiveBytes = nbCompressedBytes; 1.1404 + } 1.1405 + if (st->bitrate != OPUS_BITRATE_MAX) 1.1406 + equiv_rate = st->bitrate - (40*C+20)*((400>>LM) - 50); 1.1407 + 1.1408 + if (enc==NULL) 1.1409 + { 1.1410 + ec_enc_init(&_enc, compressed, nbCompressedBytes); 1.1411 + enc = &_enc; 1.1412 + } 1.1413 + 1.1414 + if (vbr_rate>0) 1.1415 + { 1.1416 + /* Computes the max bit-rate allowed in VBR mode to avoid violating the 1.1417 + target rate and buffering. 1.1418 + We must do this up front so that bust-prevention logic triggers 1.1419 + correctly if we don't have enough bits. */ 1.1420 + if (st->constrained_vbr) 1.1421 + { 1.1422 + opus_int32 vbr_bound; 1.1423 + opus_int32 max_allowed; 1.1424 + /* We could use any multiple of vbr_rate as bound (depending on the 1.1425 + delay). 1.1426 + This is clamped to ensure we use at least two bytes if the encoder 1.1427 + was entirely empty, but to allow 0 in hybrid mode. */ 1.1428 + vbr_bound = vbr_rate; 1.1429 + max_allowed = IMIN(IMAX(tell==1?2:0, 1.1430 + (vbr_rate+vbr_bound-st->vbr_reservoir)>>(BITRES+3)), 1.1431 + nbAvailableBytes); 1.1432 + if(max_allowed < nbAvailableBytes) 1.1433 + { 1.1434 + nbCompressedBytes = nbFilledBytes+max_allowed; 1.1435 + nbAvailableBytes = max_allowed; 1.1436 + ec_enc_shrink(enc, nbCompressedBytes); 1.1437 + } 1.1438 + } 1.1439 + } 1.1440 + total_bits = nbCompressedBytes*8; 1.1441 + 1.1442 + effEnd = st->end; 1.1443 + if (effEnd > mode->effEBands) 1.1444 + effEnd = mode->effEBands; 1.1445 + 1.1446 + ALLOC(in, CC*(N+st->overlap), celt_sig); 1.1447 + 1.1448 + sample_max=MAX32(st->overlap_max, celt_maxabs16(pcm, C*(N-overlap)/st->upsample)); 1.1449 + st->overlap_max=celt_maxabs16(pcm+C*(N-overlap)/st->upsample, C*overlap/st->upsample); 1.1450 + sample_max=MAX32(sample_max, st->overlap_max); 1.1451 +#ifdef FIXED_POINT 1.1452 + silence = (sample_max==0); 1.1453 +#else 1.1454 + silence = (sample_max <= (opus_val16)1/(1<<st->lsb_depth)); 1.1455 +#endif 1.1456 +#ifdef FUZZING 1.1457 + if ((rand()&0x3F)==0) 1.1458 + silence = 1; 1.1459 +#endif 1.1460 + if (tell==1) 1.1461 + ec_enc_bit_logp(enc, silence, 15); 1.1462 + else 1.1463 + silence=0; 1.1464 + if (silence) 1.1465 + { 1.1466 + /*In VBR mode there is no need to send more than the minimum. */ 1.1467 + if (vbr_rate>0) 1.1468 + { 1.1469 + effectiveBytes=nbCompressedBytes=IMIN(nbCompressedBytes, nbFilledBytes+2); 1.1470 + total_bits=nbCompressedBytes*8; 1.1471 + nbAvailableBytes=2; 1.1472 + ec_enc_shrink(enc, nbCompressedBytes); 1.1473 + } 1.1474 + /* Pretend we've filled all the remaining bits with zeros 1.1475 + (that's what the initialiser did anyway) */ 1.1476 + tell = nbCompressedBytes*8; 1.1477 + enc->nbits_total+=tell-ec_tell(enc); 1.1478 + } 1.1479 + c=0; do { 1.1480 + celt_preemphasis(pcm+c, in+c*(N+st->overlap)+st->overlap, N, CC, st->upsample, 1.1481 + mode->preemph, st->preemph_memE+c, st->clip); 1.1482 + } while (++c<CC); 1.1483 + 1.1484 + 1.1485 + 1.1486 + /* Find pitch period and gain */ 1.1487 + { 1.1488 + int enabled; 1.1489 + int qg; 1.1490 + enabled = ((st->lfe&&nbAvailableBytes>3) || nbAvailableBytes>12*C) && st->start==0 && !silence && !st->disable_pf 1.1491 + && st->complexity >= 5 && !(st->consec_transient && LM!=3 && st->variable_duration==OPUS_FRAMESIZE_VARIABLE); 1.1492 + 1.1493 + prefilter_tapset = st->tapset_decision; 1.1494 + pf_on = run_prefilter(st, in, prefilter_mem, CC, N, prefilter_tapset, &pitch_index, &gain1, &qg, enabled, nbAvailableBytes); 1.1495 + if ((gain1 > QCONST16(.4f,15) || st->prefilter_gain > QCONST16(.4f,15)) && (!st->analysis.valid || st->analysis.tonality > .3) 1.1496 + && (pitch_index > 1.26*st->prefilter_period || pitch_index < .79*st->prefilter_period)) 1.1497 + pitch_change = 1; 1.1498 + if (pf_on==0) 1.1499 + { 1.1500 + if(st->start==0 && tell+16<=total_bits) 1.1501 + ec_enc_bit_logp(enc, 0, 1); 1.1502 + } else { 1.1503 + /*This block is not gated by a total bits check only because 1.1504 + of the nbAvailableBytes check above.*/ 1.1505 + int octave; 1.1506 + ec_enc_bit_logp(enc, 1, 1); 1.1507 + pitch_index += 1; 1.1508 + octave = EC_ILOG(pitch_index)-5; 1.1509 + ec_enc_uint(enc, octave, 6); 1.1510 + ec_enc_bits(enc, pitch_index-(16<<octave), 4+octave); 1.1511 + pitch_index -= 1; 1.1512 + ec_enc_bits(enc, qg, 3); 1.1513 + ec_enc_icdf(enc, prefilter_tapset, tapset_icdf, 2); 1.1514 + } 1.1515 + } 1.1516 + 1.1517 + isTransient = 0; 1.1518 + shortBlocks = 0; 1.1519 + if (st->complexity >= 1 && !st->lfe) 1.1520 + { 1.1521 + isTransient = transient_analysis(in, N+st->overlap, CC, 1.1522 + &tf_estimate, &tf_chan); 1.1523 + } 1.1524 + if (LM>0 && ec_tell(enc)+3<=total_bits) 1.1525 + { 1.1526 + if (isTransient) 1.1527 + shortBlocks = M; 1.1528 + } else { 1.1529 + isTransient = 0; 1.1530 + transient_got_disabled=1; 1.1531 + } 1.1532 + 1.1533 + ALLOC(freq, CC*N, celt_sig); /**< Interleaved signal MDCTs */ 1.1534 + ALLOC(bandE,nbEBands*CC, celt_ener); 1.1535 + ALLOC(bandLogE,nbEBands*CC, opus_val16); 1.1536 + 1.1537 + secondMdct = shortBlocks && st->complexity>=8; 1.1538 + ALLOC(bandLogE2, C*nbEBands, opus_val16); 1.1539 + if (secondMdct) 1.1540 + { 1.1541 + compute_mdcts(mode, 0, in, freq, C, CC, LM, st->upsample); 1.1542 + compute_band_energies(mode, freq, bandE, effEnd, C, M); 1.1543 + amp2Log2(mode, effEnd, st->end, bandE, bandLogE2, C); 1.1544 + for (i=0;i<C*nbEBands;i++) 1.1545 + bandLogE2[i] += HALF16(SHL16(LM, DB_SHIFT)); 1.1546 + } 1.1547 + 1.1548 + compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample); 1.1549 + if (CC==2&&C==1) 1.1550 + tf_chan = 0; 1.1551 + compute_band_energies(mode, freq, bandE, effEnd, C, M); 1.1552 + 1.1553 + if (st->lfe) 1.1554 + { 1.1555 + for (i=2;i<st->end;i++) 1.1556 + { 1.1557 + bandE[i] = IMIN(bandE[i], MULT16_32_Q15(QCONST16(1e-4f,15),bandE[0])); 1.1558 + bandE[i] = MAX32(bandE[i], EPSILON); 1.1559 + } 1.1560 + } 1.1561 + amp2Log2(mode, effEnd, st->end, bandE, bandLogE, C); 1.1562 + 1.1563 + ALLOC(surround_dynalloc, C*nbEBands, opus_val16); 1.1564 + for(i=0;i<st->end;i++) 1.1565 + surround_dynalloc[i] = 0; 1.1566 + /* This computes how much masking takes place between surround channels */ 1.1567 + if (st->start==0&&st->energy_mask&&!st->lfe) 1.1568 + { 1.1569 + int mask_end; 1.1570 + int midband; 1.1571 + int count_dynalloc; 1.1572 + opus_val32 mask_avg=0; 1.1573 + opus_val32 diff=0; 1.1574 + int count=0; 1.1575 + mask_end = IMAX(2,st->lastCodedBands); 1.1576 + for (c=0;c<C;c++) 1.1577 + { 1.1578 + for(i=0;i<mask_end;i++) 1.1579 + { 1.1580 + opus_val16 mask; 1.1581 + mask = MAX16(MIN16(st->energy_mask[nbEBands*c+i], 1.1582 + QCONST16(.25f, DB_SHIFT)), -QCONST16(2.0f, DB_SHIFT)); 1.1583 + if (mask > 0) 1.1584 + mask = HALF16(mask); 1.1585 + mask_avg += MULT16_16(mask, eBands[i+1]-eBands[i]); 1.1586 + count += eBands[i+1]-eBands[i]; 1.1587 + diff += MULT16_16(mask, 1+2*i-mask_end); 1.1588 + } 1.1589 + } 1.1590 + mask_avg = DIV32_16(mask_avg,count); 1.1591 + mask_avg += QCONST16(.2f, DB_SHIFT); 1.1592 + diff = diff*6/(C*(mask_end-1)*(mask_end+1)*mask_end); 1.1593 + /* Again, being conservative */ 1.1594 + diff = HALF32(diff); 1.1595 + diff = MAX32(MIN32(diff, QCONST32(.031f, DB_SHIFT)), -QCONST32(.031f, DB_SHIFT)); 1.1596 + /* Find the band that's in the middle of the coded spectrum */ 1.1597 + for (midband=0;eBands[midband+1] < eBands[mask_end]/2;midband++); 1.1598 + count_dynalloc=0; 1.1599 + for(i=0;i<mask_end;i++) 1.1600 + { 1.1601 + opus_val32 lin; 1.1602 + opus_val16 unmask; 1.1603 + lin = mask_avg + diff*(i-midband); 1.1604 + if (C==2) 1.1605 + unmask = MAX16(st->energy_mask[i], st->energy_mask[nbEBands+i]); 1.1606 + else 1.1607 + unmask = st->energy_mask[i]; 1.1608 + unmask = MIN16(unmask, QCONST16(.0f, DB_SHIFT)); 1.1609 + unmask -= lin; 1.1610 + if (unmask > QCONST16(.25f, DB_SHIFT)) 1.1611 + { 1.1612 + surround_dynalloc[i] = unmask - QCONST16(.25f, DB_SHIFT); 1.1613 + count_dynalloc++; 1.1614 + } 1.1615 + } 1.1616 + if (count_dynalloc>=3) 1.1617 + { 1.1618 + /* If we need dynalloc in many bands, it's probably because our 1.1619 + initial masking rate was too low. */ 1.1620 + mask_avg += QCONST16(.25f, DB_SHIFT); 1.1621 + if (mask_avg>0) 1.1622 + { 1.1623 + /* Something went really wrong in the original calculations, 1.1624 + disabling masking. */ 1.1625 + mask_avg = 0; 1.1626 + diff = 0; 1.1627 + for(i=0;i<mask_end;i++) 1.1628 + surround_dynalloc[i] = 0; 1.1629 + } else { 1.1630 + for(i=0;i<mask_end;i++) 1.1631 + surround_dynalloc[i] = MAX16(0, surround_dynalloc[i]-QCONST16(.25f, DB_SHIFT)); 1.1632 + } 1.1633 + } 1.1634 + mask_avg += QCONST16(.2f, DB_SHIFT); 1.1635 + /* Convert to 1/64th units used for the trim */ 1.1636 + surround_trim = 64*diff; 1.1637 + /*printf("%d %d ", mask_avg, surround_trim);*/ 1.1638 + surround_masking = mask_avg; 1.1639 + } 1.1640 + /* Temporal VBR (but not for LFE) */ 1.1641 + if (!st->lfe) 1.1642 + { 1.1643 + opus_val16 follow=-QCONST16(10.0f,DB_SHIFT); 1.1644 + opus_val32 frame_avg=0; 1.1645 + opus_val16 offset = shortBlocks?HALF16(SHL16(LM, DB_SHIFT)):0; 1.1646 + for(i=st->start;i<st->end;i++) 1.1647 + { 1.1648 + follow = MAX16(follow-QCONST16(1.f, DB_SHIFT), bandLogE[i]-offset); 1.1649 + if (C==2) 1.1650 + follow = MAX16(follow, bandLogE[i+nbEBands]-offset); 1.1651 + frame_avg += follow; 1.1652 + } 1.1653 + frame_avg /= (st->end-st->start); 1.1654 + temporal_vbr = SUB16(frame_avg,st->spec_avg); 1.1655 + temporal_vbr = MIN16(QCONST16(3.f, DB_SHIFT), MAX16(-QCONST16(1.5f, DB_SHIFT), temporal_vbr)); 1.1656 + st->spec_avg += MULT16_16_Q15(QCONST16(.02f, 15), temporal_vbr); 1.1657 + } 1.1658 + /*for (i=0;i<21;i++) 1.1659 + printf("%f ", bandLogE[i]); 1.1660 + printf("\n");*/ 1.1661 + 1.1662 + if (!secondMdct) 1.1663 + { 1.1664 + for (i=0;i<C*nbEBands;i++) 1.1665 + bandLogE2[i] = bandLogE[i]; 1.1666 + } 1.1667 + 1.1668 + /* Last chance to catch any transient we might have missed in the 1.1669 + time-domain analysis */ 1.1670 + if (LM>0 && ec_tell(enc)+3<=total_bits && !isTransient && st->complexity>=5 && !st->lfe) 1.1671 + { 1.1672 + if (patch_transient_decision(bandLogE, oldBandE, nbEBands, st->end, C)) 1.1673 + { 1.1674 + isTransient = 1; 1.1675 + shortBlocks = M; 1.1676 + compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample); 1.1677 + compute_band_energies(mode, freq, bandE, effEnd, C, M); 1.1678 + amp2Log2(mode, effEnd, st->end, bandE, bandLogE, C); 1.1679 + /* Compensate for the scaling of short vs long mdcts */ 1.1680 + for (i=0;i<C*nbEBands;i++) 1.1681 + bandLogE2[i] += HALF16(SHL16(LM, DB_SHIFT)); 1.1682 + tf_estimate = QCONST16(.2f,14); 1.1683 + } 1.1684 + } 1.1685 + 1.1686 + if (LM>0 && ec_tell(enc)+3<=total_bits) 1.1687 + ec_enc_bit_logp(enc, isTransient, 3); 1.1688 + 1.1689 + ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */ 1.1690 + 1.1691 + /* Band normalisation */ 1.1692 + normalise_bands(mode, freq, X, bandE, effEnd, C, M); 1.1693 + 1.1694 + ALLOC(tf_res, nbEBands, int); 1.1695 + /* Disable variable tf resolution for hybrid and at very low bitrate */ 1.1696 + if (effectiveBytes>=15*C && st->start==0 && st->complexity>=2 && !st->lfe) 1.1697 + { 1.1698 + int lambda; 1.1699 + if (effectiveBytes<40) 1.1700 + lambda = 12; 1.1701 + else if (effectiveBytes<60) 1.1702 + lambda = 6; 1.1703 + else if (effectiveBytes<100) 1.1704 + lambda = 4; 1.1705 + else 1.1706 + lambda = 3; 1.1707 + lambda*=2; 1.1708 + tf_select = tf_analysis(mode, effEnd, isTransient, tf_res, lambda, X, N, LM, &tf_sum, tf_estimate, tf_chan); 1.1709 + for (i=effEnd;i<st->end;i++) 1.1710 + tf_res[i] = tf_res[effEnd-1]; 1.1711 + } else { 1.1712 + tf_sum = 0; 1.1713 + for (i=0;i<st->end;i++) 1.1714 + tf_res[i] = isTransient; 1.1715 + tf_select=0; 1.1716 + } 1.1717 + 1.1718 + ALLOC(error, C*nbEBands, opus_val16); 1.1719 + quant_coarse_energy(mode, st->start, st->end, effEnd, bandLogE, 1.1720 + oldBandE, total_bits, error, enc, 1.1721 + C, LM, nbAvailableBytes, st->force_intra, 1.1722 + &st->delayedIntra, st->complexity >= 4, st->loss_rate, st->lfe); 1.1723 + 1.1724 + tf_encode(st->start, st->end, isTransient, tf_res, LM, tf_select, enc); 1.1725 + 1.1726 + if (ec_tell(enc)+4<=total_bits) 1.1727 + { 1.1728 + if (st->lfe) 1.1729 + { 1.1730 + st->tapset_decision = 0; 1.1731 + st->spread_decision = SPREAD_NORMAL; 1.1732 + } else if (shortBlocks || st->complexity < 3 || nbAvailableBytes < 10*C || st->start != 0) 1.1733 + { 1.1734 + if (st->complexity == 0) 1.1735 + st->spread_decision = SPREAD_NONE; 1.1736 + else 1.1737 + st->spread_decision = SPREAD_NORMAL; 1.1738 + } else { 1.1739 + /* Disable new spreading+tapset estimator until we can show it works 1.1740 + better than the old one. So far it seems like spreading_decision() 1.1741 + works best. */ 1.1742 +#if 0 1.1743 + if (st->analysis.valid) 1.1744 + { 1.1745 + static const opus_val16 spread_thresholds[3] = {-QCONST16(.6f, 15), -QCONST16(.2f, 15), -QCONST16(.07f, 15)}; 1.1746 + static const opus_val16 spread_histeresis[3] = {QCONST16(.15f, 15), QCONST16(.07f, 15), QCONST16(.02f, 15)}; 1.1747 + static const opus_val16 tapset_thresholds[2] = {QCONST16(.0f, 15), QCONST16(.15f, 15)}; 1.1748 + static const opus_val16 tapset_histeresis[2] = {QCONST16(.1f, 15), QCONST16(.05f, 15)}; 1.1749 + st->spread_decision = hysteresis_decision(-st->analysis.tonality, spread_thresholds, spread_histeresis, 3, st->spread_decision); 1.1750 + st->tapset_decision = hysteresis_decision(st->analysis.tonality_slope, tapset_thresholds, tapset_histeresis, 2, st->tapset_decision); 1.1751 + } else 1.1752 +#endif 1.1753 + { 1.1754 + st->spread_decision = spreading_decision(mode, X, 1.1755 + &st->tonal_average, st->spread_decision, &st->hf_average, 1.1756 + &st->tapset_decision, pf_on&&!shortBlocks, effEnd, C, M); 1.1757 + } 1.1758 + /*printf("%d %d\n", st->tapset_decision, st->spread_decision);*/ 1.1759 + /*printf("%f %d %f %d\n\n", st->analysis.tonality, st->spread_decision, st->analysis.tonality_slope, st->tapset_decision);*/ 1.1760 + } 1.1761 + ec_enc_icdf(enc, st->spread_decision, spread_icdf, 5); 1.1762 + } 1.1763 + 1.1764 + ALLOC(offsets, nbEBands, int); 1.1765 + 1.1766 + maxDepth = dynalloc_analysis(bandLogE, bandLogE2, nbEBands, st->start, st->end, C, offsets, 1.1767 + st->lsb_depth, mode->logN, isTransient, st->vbr, st->constrained_vbr, 1.1768 + eBands, LM, effectiveBytes, &tot_boost, st->lfe, surround_dynalloc); 1.1769 + /* For LFE, everything interesting is in the first band */ 1.1770 + if (st->lfe) 1.1771 + offsets[0] = IMIN(8, effectiveBytes/3); 1.1772 + ALLOC(cap, nbEBands, int); 1.1773 + init_caps(mode,cap,LM,C); 1.1774 + 1.1775 + dynalloc_logp = 6; 1.1776 + total_bits<<=BITRES; 1.1777 + total_boost = 0; 1.1778 + tell = ec_tell_frac(enc); 1.1779 + for (i=st->start;i<st->end;i++) 1.1780 + { 1.1781 + int width, quanta; 1.1782 + int dynalloc_loop_logp; 1.1783 + int boost; 1.1784 + int j; 1.1785 + width = C*(eBands[i+1]-eBands[i])<<LM; 1.1786 + /* quanta is 6 bits, but no more than 1 bit/sample 1.1787 + and no less than 1/8 bit/sample */ 1.1788 + quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width)); 1.1789 + dynalloc_loop_logp = dynalloc_logp; 1.1790 + boost = 0; 1.1791 + for (j = 0; tell+(dynalloc_loop_logp<<BITRES) < total_bits-total_boost 1.1792 + && boost < cap[i]; j++) 1.1793 + { 1.1794 + int flag; 1.1795 + flag = j<offsets[i]; 1.1796 + ec_enc_bit_logp(enc, flag, dynalloc_loop_logp); 1.1797 + tell = ec_tell_frac(enc); 1.1798 + if (!flag) 1.1799 + break; 1.1800 + boost += quanta; 1.1801 + total_boost += quanta; 1.1802 + dynalloc_loop_logp = 1; 1.1803 + } 1.1804 + /* Making dynalloc more likely */ 1.1805 + if (j) 1.1806 + dynalloc_logp = IMAX(2, dynalloc_logp-1); 1.1807 + offsets[i] = boost; 1.1808 + } 1.1809 + 1.1810 + if (C==2) 1.1811 + { 1.1812 + static const opus_val16 intensity_thresholds[21]= 1.1813 + /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 off*/ 1.1814 + { 1, 2, 3, 4, 5, 6, 7, 8,16,24,36,44,50,56,62,67,72,79,88,106,134}; 1.1815 + static const opus_val16 intensity_histeresis[21]= 1.1816 + { 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 5, 6, 8, 8}; 1.1817 + 1.1818 + /* Always use MS for 2.5 ms frames until we can do a better analysis */ 1.1819 + if (LM!=0) 1.1820 + dual_stereo = stereo_analysis(mode, X, LM, N); 1.1821 + 1.1822 + st->intensity = hysteresis_decision((opus_val16)(equiv_rate/1000), 1.1823 + intensity_thresholds, intensity_histeresis, 21, st->intensity); 1.1824 + st->intensity = IMIN(st->end,IMAX(st->start, st->intensity)); 1.1825 + } 1.1826 + 1.1827 + alloc_trim = 5; 1.1828 + if (tell+(6<<BITRES) <= total_bits - total_boost) 1.1829 + { 1.1830 + if (st->lfe) 1.1831 + alloc_trim = 5; 1.1832 + else 1.1833 + alloc_trim = alloc_trim_analysis(mode, X, bandLogE, 1.1834 + st->end, LM, C, N, &st->analysis, &st->stereo_saving, tf_estimate, st->intensity, surround_trim); 1.1835 + ec_enc_icdf(enc, alloc_trim, trim_icdf, 7); 1.1836 + tell = ec_tell_frac(enc); 1.1837 + } 1.1838 + 1.1839 + /* Variable bitrate */ 1.1840 + if (vbr_rate>0) 1.1841 + { 1.1842 + opus_val16 alpha; 1.1843 + opus_int32 delta; 1.1844 + /* The target rate in 8th bits per frame */ 1.1845 + opus_int32 target, base_target; 1.1846 + opus_int32 min_allowed; 1.1847 + int lm_diff = mode->maxLM - LM; 1.1848 + 1.1849 + /* Don't attempt to use more than 510 kb/s, even for frames smaller than 20 ms. 1.1850 + The CELT allocator will just not be able to use more than that anyway. */ 1.1851 + nbCompressedBytes = IMIN(nbCompressedBytes,1275>>(3-LM)); 1.1852 + base_target = vbr_rate - ((40*C+20)<<BITRES); 1.1853 + 1.1854 + if (st->constrained_vbr) 1.1855 + base_target += (st->vbr_offset>>lm_diff); 1.1856 + 1.1857 + target = compute_vbr(mode, &st->analysis, base_target, LM, equiv_rate, 1.1858 + st->lastCodedBands, C, st->intensity, st->constrained_vbr, 1.1859 + st->stereo_saving, tot_boost, tf_estimate, pitch_change, maxDepth, 1.1860 + st->variable_duration, st->lfe, st->energy_mask!=NULL, surround_masking, 1.1861 + temporal_vbr); 1.1862 + 1.1863 + /* The current offset is removed from the target and the space used 1.1864 + so far is added*/ 1.1865 + target=target+tell; 1.1866 + /* In VBR mode the frame size must not be reduced so much that it would 1.1867 + result in the encoder running out of bits. 1.1868 + The margin of 2 bytes ensures that none of the bust-prevention logic 1.1869 + in the decoder will have triggered so far. */ 1.1870 + min_allowed = ((tell+total_boost+(1<<(BITRES+3))-1)>>(BITRES+3)) + 2 - nbFilledBytes; 1.1871 + 1.1872 + nbAvailableBytes = (target+(1<<(BITRES+2)))>>(BITRES+3); 1.1873 + nbAvailableBytes = IMAX(min_allowed,nbAvailableBytes); 1.1874 + nbAvailableBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes) - nbFilledBytes; 1.1875 + 1.1876 + /* By how much did we "miss" the target on that frame */ 1.1877 + delta = target - vbr_rate; 1.1878 + 1.1879 + target=nbAvailableBytes<<(BITRES+3); 1.1880 + 1.1881 + /*If the frame is silent we don't adjust our drift, otherwise 1.1882 + the encoder will shoot to very high rates after hitting a 1.1883 + span of silence, but we do allow the bitres to refill. 1.1884 + This means that we'll undershoot our target in CVBR/VBR modes 1.1885 + on files with lots of silence. */ 1.1886 + if(silence) 1.1887 + { 1.1888 + nbAvailableBytes = 2; 1.1889 + target = 2*8<<BITRES; 1.1890 + delta = 0; 1.1891 + } 1.1892 + 1.1893 + if (st->vbr_count < 970) 1.1894 + { 1.1895 + st->vbr_count++; 1.1896 + alpha = celt_rcp(SHL32(EXTEND32(st->vbr_count+20),16)); 1.1897 + } else 1.1898 + alpha = QCONST16(.001f,15); 1.1899 + /* How many bits have we used in excess of what we're allowed */ 1.1900 + if (st->constrained_vbr) 1.1901 + st->vbr_reservoir += target - vbr_rate; 1.1902 + /*printf ("%d\n", st->vbr_reservoir);*/ 1.1903 + 1.1904 + /* Compute the offset we need to apply in order to reach the target */ 1.1905 + if (st->constrained_vbr) 1.1906 + { 1.1907 + st->vbr_drift += (opus_int32)MULT16_32_Q15(alpha,(delta*(1<<lm_diff))-st->vbr_offset-st->vbr_drift); 1.1908 + st->vbr_offset = -st->vbr_drift; 1.1909 + } 1.1910 + /*printf ("%d\n", st->vbr_drift);*/ 1.1911 + 1.1912 + if (st->constrained_vbr && st->vbr_reservoir < 0) 1.1913 + { 1.1914 + /* We're under the min value -- increase rate */ 1.1915 + int adjust = (-st->vbr_reservoir)/(8<<BITRES); 1.1916 + /* Unless we're just coding silence */ 1.1917 + nbAvailableBytes += silence?0:adjust; 1.1918 + st->vbr_reservoir = 0; 1.1919 + /*printf ("+%d\n", adjust);*/ 1.1920 + } 1.1921 + nbCompressedBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes); 1.1922 + /*printf("%d\n", nbCompressedBytes*50*8);*/ 1.1923 + /* This moves the raw bits to take into account the new compressed size */ 1.1924 + ec_enc_shrink(enc, nbCompressedBytes); 1.1925 + } 1.1926 + 1.1927 + /* Bit allocation */ 1.1928 + ALLOC(fine_quant, nbEBands, int); 1.1929 + ALLOC(pulses, nbEBands, int); 1.1930 + ALLOC(fine_priority, nbEBands, int); 1.1931 + 1.1932 + /* bits = packet size - where we are - safety*/ 1.1933 + bits = (((opus_int32)nbCompressedBytes*8)<<BITRES) - ec_tell_frac(enc) - 1; 1.1934 + anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0; 1.1935 + bits -= anti_collapse_rsv; 1.1936 + signalBandwidth = st->end-1; 1.1937 +#ifndef DISABLE_FLOAT_API 1.1938 + if (st->analysis.valid) 1.1939 + { 1.1940 + int min_bandwidth; 1.1941 + if (equiv_rate < (opus_int32)32000*C) 1.1942 + min_bandwidth = 13; 1.1943 + else if (equiv_rate < (opus_int32)48000*C) 1.1944 + min_bandwidth = 16; 1.1945 + else if (equiv_rate < (opus_int32)60000*C) 1.1946 + min_bandwidth = 18; 1.1947 + else if (equiv_rate < (opus_int32)80000*C) 1.1948 + min_bandwidth = 19; 1.1949 + else 1.1950 + min_bandwidth = 20; 1.1951 + signalBandwidth = IMAX(st->analysis.bandwidth, min_bandwidth); 1.1952 + } 1.1953 +#endif 1.1954 + if (st->lfe) 1.1955 + signalBandwidth = 1; 1.1956 + codedBands = compute_allocation(mode, st->start, st->end, offsets, cap, 1.1957 + alloc_trim, &st->intensity, &dual_stereo, bits, &balance, pulses, 1.1958 + fine_quant, fine_priority, C, LM, enc, 1, st->lastCodedBands, signalBandwidth); 1.1959 + if (st->lastCodedBands) 1.1960 + st->lastCodedBands = IMIN(st->lastCodedBands+1,IMAX(st->lastCodedBands-1,codedBands)); 1.1961 + else 1.1962 + st->lastCodedBands = codedBands; 1.1963 + 1.1964 + quant_fine_energy(mode, st->start, st->end, oldBandE, error, fine_quant, enc, C); 1.1965 + 1.1966 + /* Residual quantisation */ 1.1967 + ALLOC(collapse_masks, C*nbEBands, unsigned char); 1.1968 + quant_all_bands(1, mode, st->start, st->end, X, C==2 ? X+N : NULL, collapse_masks, 1.1969 + bandE, pulses, shortBlocks, st->spread_decision, dual_stereo, st->intensity, tf_res, 1.1970 + nbCompressedBytes*(8<<BITRES)-anti_collapse_rsv, balance, enc, LM, codedBands, &st->rng); 1.1971 + 1.1972 + if (anti_collapse_rsv > 0) 1.1973 + { 1.1974 + anti_collapse_on = st->consec_transient<2; 1.1975 +#ifdef FUZZING 1.1976 + anti_collapse_on = rand()&0x1; 1.1977 +#endif 1.1978 + ec_enc_bits(enc, anti_collapse_on, 1); 1.1979 + } 1.1980 + quant_energy_finalise(mode, st->start, st->end, oldBandE, error, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, C); 1.1981 + 1.1982 + if (silence) 1.1983 + { 1.1984 + for (i=0;i<C*nbEBands;i++) 1.1985 + oldBandE[i] = -QCONST16(28.f,DB_SHIFT); 1.1986 + } 1.1987 + 1.1988 +#ifdef RESYNTH 1.1989 + /* Re-synthesis of the coded audio if required */ 1.1990 + { 1.1991 + celt_sig *out_mem[2]; 1.1992 + 1.1993 + if (anti_collapse_on) 1.1994 + { 1.1995 + anti_collapse(mode, X, collapse_masks, LM, C, N, 1.1996 + st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng); 1.1997 + } 1.1998 + 1.1999 + if (silence) 1.2000 + { 1.2001 + for (i=0;i<C*N;i++) 1.2002 + freq[i] = 0; 1.2003 + } else { 1.2004 + /* Synthesis */ 1.2005 + denormalise_bands(mode, X, freq, oldBandE, st->start, effEnd, C, M); 1.2006 + } 1.2007 + 1.2008 + c=0; do { 1.2009 + OPUS_MOVE(st->syn_mem[c], st->syn_mem[c]+N, 2*MAX_PERIOD-N+overlap/2); 1.2010 + } while (++c<CC); 1.2011 + 1.2012 + if (CC==2&&C==1) 1.2013 + { 1.2014 + for (i=0;i<N;i++) 1.2015 + freq[N+i] = freq[i]; 1.2016 + } 1.2017 + 1.2018 + c=0; do { 1.2019 + out_mem[c] = st->syn_mem[c]+2*MAX_PERIOD-N; 1.2020 + } while (++c<CC); 1.2021 + 1.2022 + compute_inv_mdcts(mode, shortBlocks, freq, out_mem, CC, LM); 1.2023 + 1.2024 + c=0; do { 1.2025 + st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD); 1.2026 + st->prefilter_period_old=IMAX(st->prefilter_period_old, COMBFILTER_MINPERIOD); 1.2027 + comb_filter(out_mem[c], out_mem[c], st->prefilter_period_old, st->prefilter_period, mode->shortMdctSize, 1.2028 + st->prefilter_gain_old, st->prefilter_gain, st->prefilter_tapset_old, st->prefilter_tapset, 1.2029 + mode->window, st->overlap); 1.2030 + if (LM!=0) 1.2031 + comb_filter(out_mem[c]+mode->shortMdctSize, out_mem[c]+mode->shortMdctSize, st->prefilter_period, pitch_index, N-mode->shortMdctSize, 1.2032 + st->prefilter_gain, gain1, st->prefilter_tapset, prefilter_tapset, 1.2033 + mode->window, overlap); 1.2034 + } while (++c<CC); 1.2035 + 1.2036 + /* We reuse freq[] as scratch space for the de-emphasis */ 1.2037 + deemphasis(out_mem, (opus_val16*)pcm, N, CC, st->upsample, mode->preemph, st->preemph_memD, freq); 1.2038 + st->prefilter_period_old = st->prefilter_period; 1.2039 + st->prefilter_gain_old = st->prefilter_gain; 1.2040 + st->prefilter_tapset_old = st->prefilter_tapset; 1.2041 + } 1.2042 +#endif 1.2043 + 1.2044 + st->prefilter_period = pitch_index; 1.2045 + st->prefilter_gain = gain1; 1.2046 + st->prefilter_tapset = prefilter_tapset; 1.2047 +#ifdef RESYNTH 1.2048 + if (LM!=0) 1.2049 + { 1.2050 + st->prefilter_period_old = st->prefilter_period; 1.2051 + st->prefilter_gain_old = st->prefilter_gain; 1.2052 + st->prefilter_tapset_old = st->prefilter_tapset; 1.2053 + } 1.2054 +#endif 1.2055 + 1.2056 + if (CC==2&&C==1) { 1.2057 + for (i=0;i<nbEBands;i++) 1.2058 + oldBandE[nbEBands+i]=oldBandE[i]; 1.2059 + } 1.2060 + 1.2061 + if (!isTransient) 1.2062 + { 1.2063 + for (i=0;i<CC*nbEBands;i++) 1.2064 + oldLogE2[i] = oldLogE[i]; 1.2065 + for (i=0;i<CC*nbEBands;i++) 1.2066 + oldLogE[i] = oldBandE[i]; 1.2067 + } else { 1.2068 + for (i=0;i<CC*nbEBands;i++) 1.2069 + oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]); 1.2070 + } 1.2071 + /* In case start or end were to change */ 1.2072 + c=0; do 1.2073 + { 1.2074 + for (i=0;i<st->start;i++) 1.2075 + { 1.2076 + oldBandE[c*nbEBands+i]=0; 1.2077 + oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT); 1.2078 + } 1.2079 + for (i=st->end;i<nbEBands;i++) 1.2080 + { 1.2081 + oldBandE[c*nbEBands+i]=0; 1.2082 + oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT); 1.2083 + } 1.2084 + } while (++c<CC); 1.2085 + 1.2086 + if (isTransient || transient_got_disabled) 1.2087 + st->consec_transient++; 1.2088 + else 1.2089 + st->consec_transient=0; 1.2090 + st->rng = enc->rng; 1.2091 + 1.2092 + /* If there's any room left (can only happen for very high rates), 1.2093 + it's already filled with zeros */ 1.2094 + ec_enc_done(enc); 1.2095 + 1.2096 +#ifdef CUSTOM_MODES 1.2097 + if (st->signalling) 1.2098 + nbCompressedBytes++; 1.2099 +#endif 1.2100 + 1.2101 + RESTORE_STACK; 1.2102 + if (ec_get_error(enc)) 1.2103 + return OPUS_INTERNAL_ERROR; 1.2104 + else 1.2105 + return nbCompressedBytes; 1.2106 +} 1.2107 + 1.2108 + 1.2109 +#ifdef CUSTOM_MODES 1.2110 + 1.2111 +#ifdef FIXED_POINT 1.2112 +int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes) 1.2113 +{ 1.2114 + return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL); 1.2115 +} 1.2116 + 1.2117 +#ifndef DISABLE_FLOAT_API 1.2118 +int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes) 1.2119 +{ 1.2120 + int j, ret, C, N; 1.2121 + VARDECL(opus_int16, in); 1.2122 + ALLOC_STACK; 1.2123 + 1.2124 + if (pcm==NULL) 1.2125 + return OPUS_BAD_ARG; 1.2126 + 1.2127 + C = st->channels; 1.2128 + N = frame_size; 1.2129 + ALLOC(in, C*N, opus_int16); 1.2130 + 1.2131 + for (j=0;j<C*N;j++) 1.2132 + in[j] = FLOAT2INT16(pcm[j]); 1.2133 + 1.2134 + ret=celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL); 1.2135 +#ifdef RESYNTH 1.2136 + for (j=0;j<C*N;j++) 1.2137 + ((float*)pcm)[j]=in[j]*(1.f/32768.f); 1.2138 +#endif 1.2139 + RESTORE_STACK; 1.2140 + return ret; 1.2141 +} 1.2142 +#endif /* DISABLE_FLOAT_API */ 1.2143 +#else 1.2144 + 1.2145 +int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes) 1.2146 +{ 1.2147 + int j, ret, C, N; 1.2148 + VARDECL(celt_sig, in); 1.2149 + ALLOC_STACK; 1.2150 + 1.2151 + if (pcm==NULL) 1.2152 + return OPUS_BAD_ARG; 1.2153 + 1.2154 + C=st->channels; 1.2155 + N=frame_size; 1.2156 + ALLOC(in, C*N, celt_sig); 1.2157 + for (j=0;j<C*N;j++) { 1.2158 + in[j] = SCALEOUT(pcm[j]); 1.2159 + } 1.2160 + 1.2161 + ret = celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL); 1.2162 +#ifdef RESYNTH 1.2163 + for (j=0;j<C*N;j++) 1.2164 + ((opus_int16*)pcm)[j] = FLOAT2INT16(in[j]); 1.2165 +#endif 1.2166 + RESTORE_STACK; 1.2167 + return ret; 1.2168 +} 1.2169 + 1.2170 +int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes) 1.2171 +{ 1.2172 + return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL); 1.2173 +} 1.2174 + 1.2175 +#endif 1.2176 + 1.2177 +#endif /* CUSTOM_MODES */ 1.2178 + 1.2179 +int opus_custom_encoder_ctl(CELTEncoder * OPUS_RESTRICT st, int request, ...) 1.2180 +{ 1.2181 + va_list ap; 1.2182 + 1.2183 + va_start(ap, request); 1.2184 + switch (request) 1.2185 + { 1.2186 + case OPUS_SET_COMPLEXITY_REQUEST: 1.2187 + { 1.2188 + int value = va_arg(ap, opus_int32); 1.2189 + if (value<0 || value>10) 1.2190 + goto bad_arg; 1.2191 + st->complexity = value; 1.2192 + } 1.2193 + break; 1.2194 + case CELT_SET_START_BAND_REQUEST: 1.2195 + { 1.2196 + opus_int32 value = va_arg(ap, opus_int32); 1.2197 + if (value<0 || value>=st->mode->nbEBands) 1.2198 + goto bad_arg; 1.2199 + st->start = value; 1.2200 + } 1.2201 + break; 1.2202 + case CELT_SET_END_BAND_REQUEST: 1.2203 + { 1.2204 + opus_int32 value = va_arg(ap, opus_int32); 1.2205 + if (value<1 || value>st->mode->nbEBands) 1.2206 + goto bad_arg; 1.2207 + st->end = value; 1.2208 + } 1.2209 + break; 1.2210 + case CELT_SET_PREDICTION_REQUEST: 1.2211 + { 1.2212 + int value = va_arg(ap, opus_int32); 1.2213 + if (value<0 || value>2) 1.2214 + goto bad_arg; 1.2215 + st->disable_pf = value<=1; 1.2216 + st->force_intra = value==0; 1.2217 + } 1.2218 + break; 1.2219 + case OPUS_SET_PACKET_LOSS_PERC_REQUEST: 1.2220 + { 1.2221 + int value = va_arg(ap, opus_int32); 1.2222 + if (value<0 || value>100) 1.2223 + goto bad_arg; 1.2224 + st->loss_rate = value; 1.2225 + } 1.2226 + break; 1.2227 + case OPUS_SET_VBR_CONSTRAINT_REQUEST: 1.2228 + { 1.2229 + opus_int32 value = va_arg(ap, opus_int32); 1.2230 + st->constrained_vbr = value; 1.2231 + } 1.2232 + break; 1.2233 + case OPUS_SET_VBR_REQUEST: 1.2234 + { 1.2235 + opus_int32 value = va_arg(ap, opus_int32); 1.2236 + st->vbr = value; 1.2237 + } 1.2238 + break; 1.2239 + case OPUS_SET_BITRATE_REQUEST: 1.2240 + { 1.2241 + opus_int32 value = va_arg(ap, opus_int32); 1.2242 + if (value<=500 && value!=OPUS_BITRATE_MAX) 1.2243 + goto bad_arg; 1.2244 + value = IMIN(value, 260000*st->channels); 1.2245 + st->bitrate = value; 1.2246 + } 1.2247 + break; 1.2248 + case CELT_SET_CHANNELS_REQUEST: 1.2249 + { 1.2250 + opus_int32 value = va_arg(ap, opus_int32); 1.2251 + if (value<1 || value>2) 1.2252 + goto bad_arg; 1.2253 + st->stream_channels = value; 1.2254 + } 1.2255 + break; 1.2256 + case OPUS_SET_LSB_DEPTH_REQUEST: 1.2257 + { 1.2258 + opus_int32 value = va_arg(ap, opus_int32); 1.2259 + if (value<8 || value>24) 1.2260 + goto bad_arg; 1.2261 + st->lsb_depth=value; 1.2262 + } 1.2263 + break; 1.2264 + case OPUS_GET_LSB_DEPTH_REQUEST: 1.2265 + { 1.2266 + opus_int32 *value = va_arg(ap, opus_int32*); 1.2267 + *value=st->lsb_depth; 1.2268 + } 1.2269 + break; 1.2270 + case OPUS_SET_EXPERT_FRAME_DURATION_REQUEST: 1.2271 + { 1.2272 + opus_int32 value = va_arg(ap, opus_int32); 1.2273 + st->variable_duration = value; 1.2274 + } 1.2275 + break; 1.2276 + case OPUS_RESET_STATE: 1.2277 + { 1.2278 + int i; 1.2279 + opus_val16 *oldBandE, *oldLogE, *oldLogE2; 1.2280 + oldBandE = (opus_val16*)(st->in_mem+st->channels*(st->overlap+COMBFILTER_MAXPERIOD)); 1.2281 + oldLogE = oldBandE + st->channels*st->mode->nbEBands; 1.2282 + oldLogE2 = oldLogE + st->channels*st->mode->nbEBands; 1.2283 + OPUS_CLEAR((char*)&st->ENCODER_RESET_START, 1.2284 + opus_custom_encoder_get_size(st->mode, st->channels)- 1.2285 + ((char*)&st->ENCODER_RESET_START - (char*)st)); 1.2286 + for (i=0;i<st->channels*st->mode->nbEBands;i++) 1.2287 + oldLogE[i]=oldLogE2[i]=-QCONST16(28.f,DB_SHIFT); 1.2288 + st->vbr_offset = 0; 1.2289 + st->delayedIntra = 1; 1.2290 + st->spread_decision = SPREAD_NORMAL; 1.2291 + st->tonal_average = 256; 1.2292 + st->hf_average = 0; 1.2293 + st->tapset_decision = 0; 1.2294 + } 1.2295 + break; 1.2296 +#ifdef CUSTOM_MODES 1.2297 + case CELT_SET_INPUT_CLIPPING_REQUEST: 1.2298 + { 1.2299 + opus_int32 value = va_arg(ap, opus_int32); 1.2300 + st->clip = value; 1.2301 + } 1.2302 + break; 1.2303 +#endif 1.2304 + case CELT_SET_SIGNALLING_REQUEST: 1.2305 + { 1.2306 + opus_int32 value = va_arg(ap, opus_int32); 1.2307 + st->signalling = value; 1.2308 + } 1.2309 + break; 1.2310 + case CELT_SET_ANALYSIS_REQUEST: 1.2311 + { 1.2312 + AnalysisInfo *info = va_arg(ap, AnalysisInfo *); 1.2313 + if (info) 1.2314 + OPUS_COPY(&st->analysis, info, 1); 1.2315 + } 1.2316 + break; 1.2317 + case CELT_GET_MODE_REQUEST: 1.2318 + { 1.2319 + const CELTMode ** value = va_arg(ap, const CELTMode**); 1.2320 + if (value==0) 1.2321 + goto bad_arg; 1.2322 + *value=st->mode; 1.2323 + } 1.2324 + break; 1.2325 + case OPUS_GET_FINAL_RANGE_REQUEST: 1.2326 + { 1.2327 + opus_uint32 * value = va_arg(ap, opus_uint32 *); 1.2328 + if (value==0) 1.2329 + goto bad_arg; 1.2330 + *value=st->rng; 1.2331 + } 1.2332 + break; 1.2333 + case OPUS_SET_LFE_REQUEST: 1.2334 + { 1.2335 + opus_int32 value = va_arg(ap, opus_int32); 1.2336 + st->lfe = value; 1.2337 + } 1.2338 + break; 1.2339 + case OPUS_SET_ENERGY_MASK_REQUEST: 1.2340 + { 1.2341 + opus_val16 *value = va_arg(ap, opus_val16*); 1.2342 + st->energy_mask = value; 1.2343 + } 1.2344 + break; 1.2345 + default: 1.2346 + goto bad_request; 1.2347 + } 1.2348 + va_end(ap); 1.2349 + return OPUS_OK; 1.2350 +bad_arg: 1.2351 + va_end(ap); 1.2352 + return OPUS_BAD_ARG; 1.2353 +bad_request: 1.2354 + va_end(ap); 1.2355 + return OPUS_UNIMPLEMENTED; 1.2356 +}