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 */
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
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.
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 FOUNDATION OR
21 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.
36 #include "os_support.h"
44 #include "quant_bands.h"
46 #include "stack_alloc.h"
48 #include "float_cast.h"
54 #define OPUS_VERSION "unknown"
58 #define OPUS_CUSTOM_NOSTATIC
60 #define OPUS_CUSTOM_NOSTATIC static inline
63 static const unsigned char trim_icdf[11] = {126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0};
64 /* Probs: NONE: 21.875%, LIGHT: 6.25%, NORMAL: 65.625%, AGGRESSIVE: 6.25% */
65 static const unsigned char spread_icdf[4] = {25, 23, 2, 0};
67 static const unsigned char tapset_icdf[3]={2,1,0};
70 static const unsigned char toOpusTable[20] = {
71 0xE0, 0xE8, 0xF0, 0xF8,
72 0xC0, 0xC8, 0xD0, 0xD8,
73 0xA0, 0xA8, 0xB0, 0xB8,
74 0x00, 0x00, 0x00, 0x00,
75 0x80, 0x88, 0x90, 0x98,
78 static const unsigned char fromOpusTable[16] = {
79 0x80, 0x88, 0x90, 0x98,
80 0x40, 0x48, 0x50, 0x58,
81 0x20, 0x28, 0x30, 0x38,
82 0x00, 0x08, 0x10, 0x18
85 static inline int toOpus(unsigned char c)
89 ret = toOpusTable[c>>3];
96 static inline int fromOpus(unsigned char c)
101 return fromOpusTable[(c>>3)-16] | (c&0x7);
103 #endif /*CUSTOM_MODES*/
105 #define COMBFILTER_MAXPERIOD 1024
106 #define COMBFILTER_MINPERIOD 15
108 static int resampling_factor(opus_int32 rate)
142 struct OpusCustomEncoder {
143 const OpusCustomMode *mode; /**< Mode used by the encoder */
158 int constrained_vbr; /* If zero, VBR can do whatever it likes with the rate */
161 /* Everything beyond this point gets cleared on a reset */
162 #define ENCODER_RESET_START rng
166 opus_val32 delayedIntra;
172 int prefilter_period;
173 opus_val16 prefilter_gain;
174 int prefilter_tapset;
176 int prefilter_period_old;
177 opus_val16 prefilter_gain_old;
178 int prefilter_tapset_old;
180 int consec_transient;
182 opus_val32 preemph_memE[2];
183 opus_val32 preemph_memD[2];
185 /* VBR-related parameters */
186 opus_int32 vbr_reservoir;
187 opus_int32 vbr_drift;
188 opus_int32 vbr_offset;
189 opus_int32 vbr_count;
192 celt_sig syn_mem[2][2*MAX_PERIOD];
195 celt_sig in_mem[1]; /* Size = channels*mode->overlap */
196 /* celt_sig prefilter_mem[], Size = channels*COMBFILTER_PERIOD */
197 /* celt_sig overlap_mem[], Size = channels*mode->overlap */
198 /* opus_val16 oldEBands[], Size = 2*channels*mode->nbEBands */
201 int celt_encoder_get_size(int channels)
203 CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
204 return opus_custom_encoder_get_size(mode, channels);
207 OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_get_size(const CELTMode *mode, int channels)
209 int size = sizeof(struct CELTEncoder)
210 + (2*channels*mode->overlap-1)*sizeof(celt_sig)
211 + channels*COMBFILTER_MAXPERIOD*sizeof(celt_sig)
212 + 3*channels*mode->nbEBands*sizeof(opus_val16);
217 CELTEncoder *opus_custom_encoder_create(const CELTMode *mode, int channels, int *error)
220 CELTEncoder *st = (CELTEncoder *)opus_alloc(opus_custom_encoder_get_size(mode, channels));
221 /* init will handle the NULL case */
222 ret = opus_custom_encoder_init(st, mode, channels);
225 opus_custom_encoder_destroy(st);
232 #endif /* CUSTOM_MODES */
234 int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels)
237 ret = opus_custom_encoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
240 st->upsample = resampling_factor(sampling_rate);
244 OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_init(CELTEncoder *st, const CELTMode *mode, int channels)
246 if (channels < 0 || channels > 2)
249 if (st==NULL || mode==NULL)
250 return OPUS_ALLOC_FAIL;
252 OPUS_CLEAR((char*)st, opus_custom_encoder_get_size(mode, channels));
255 st->overlap = mode->overlap;
256 st->stream_channels = st->channels = channels;
260 st->end = st->mode->effEBands;
263 st->constrained_vbr = 1;
266 st->bitrate = OPUS_BITRATE_MAX;
270 st->delayedIntra = 1;
271 st->tonal_average = 256;
272 st->spread_decision = SPREAD_NORMAL;
274 st->tapset_decision = 0;
281 void opus_custom_encoder_destroy(CELTEncoder *st)
285 #endif /* CUSTOM_MODES */
287 static inline opus_val16 SIG2WORD16(celt_sig x)
290 x = PSHR32(x, SIG_SHIFT);
291 x = MAX32(x, -32768);
295 return (opus_val16)x;
299 static int transient_analysis(const opus_val32 * restrict in, int len, int C,
303 VARDECL(opus_val16, tmp);
304 opus_val32 mem0=0,mem1=0;
305 int is_transient = 0;
308 VARDECL(opus_val16, bins);
310 ALLOC(tmp, len, opus_val16);
314 ALLOC(bins, N, opus_val16);
318 tmp[i] = SHR32(in[i],SIG_SHIFT);
321 tmp[i] = SHR32(ADD32(in[i],in[i+len]), SIG_SHIFT+1);
324 /* High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) */
331 mem0 = mem1 + y - SHL32(x,1);
332 mem1 = x - SHR32(y,1);
334 mem0 = mem1 + y - 2*x;
337 tmp[i] = EXTRACT16(SHR(y,2));
339 /* First few samples are bad because we don't propagate the memory */
346 opus_val16 max_abs=0;
347 for (j=0;j<block;j++)
348 max_abs = MAX16(max_abs, ABS16(tmp[i*block+j]));
355 opus_val16 t1, t2, t3;
357 t1 = MULT16_16_Q15(QCONST16(.15f, 15), bins[i]);
358 t2 = MULT16_16_Q15(QCONST16(.4f, 15), bins[i]);
359 t3 = MULT16_16_Q15(QCONST16(.15f, 15), bins[i]);
384 is_transient = rand()&0x1;
389 /** Apply window and compute the MDCT for all sub-frames and
390 all channels in a frame */
391 static void compute_mdcts(const CELTMode *mode, int shortBlocks, celt_sig * restrict in, celt_sig * restrict out, int _C, int LM)
393 const int C = CHANNELS(_C);
394 if (C==1 && !shortBlocks)
396 const int overlap = OVERLAP(mode);
397 clt_mdct_forward(&mode->mdct, in, out, mode->window, overlap, mode->maxLM-LM, 1);
399 const int overlap = OVERLAP(mode);
400 int N = mode->shortMdctSize<<LM;
405 N = mode->shortMdctSize;
411 /* Interleaving the sub-frames while doing the MDCTs */
412 clt_mdct_forward(&mode->mdct, in+c*(B*N+overlap)+b*N, &out[b+c*N*B], mode->window, overlap, shortBlocks ? mode->maxLM : mode->maxLM-LM, B);
418 /** Compute the IMDCT and apply window for all sub-frames and
419 all channels in a frame */
420 static void compute_inv_mdcts(const CELTMode *mode, int shortBlocks, celt_sig *X,
421 celt_sig * restrict out_mem[],
422 celt_sig * restrict overlap_mem[], int _C, int LM)
425 const int C = CHANNELS(_C);
426 const int N = mode->shortMdctSize<<LM;
427 const int overlap = OVERLAP(mode);
428 VARDECL(opus_val32, x);
431 ALLOC(x, N+overlap, opus_val32);
440 N2 = mode->shortMdctSize;
443 /* Prevents problems from the imdct doing the overlap-add */
444 OPUS_CLEAR(x, overlap);
448 /* IMDCT on the interleaved the sub-frames */
449 clt_mdct_backward(&mode->mdct, &X[b+c*N2*B], x+N2*b, mode->window, overlap, shortBlocks ? mode->maxLM : mode->maxLM-LM, B);
452 for (j=0;j<overlap;j++)
453 out_mem[c][j] = x[j] + overlap_mem[c][j];
455 out_mem[c][j] = x[j];
456 for (j=0;j<overlap;j++)
457 overlap_mem[c][j] = x[N+j];
462 static void deemphasis(celt_sig *in[], opus_val16 *pcm, int N, int _C, int downsample, const opus_val16 *coef, celt_sig *mem)
464 const int C = CHANNELS(_C);
469 celt_sig * restrict x;
470 opus_val16 * restrict y;
476 celt_sig tmp = *x + m;
477 m = MULT16_32_Q15(coef[0], tmp)
478 - MULT16_32_Q15(coef[1], *x);
479 tmp = SHL32(MULT16_32_Q15(coef[3], tmp), 2);
481 /* Technically the store could be moved outside of the if because
482 the stores we don't want will just be overwritten */
483 if (++count==downsample)
485 *y = SCALEOUT(SIG2WORD16(tmp));
494 static void comb_filter(opus_val32 *y, opus_val32 *x, int T0, int T1, int N,
495 opus_val16 g0, opus_val16 g1, int tapset0, int tapset1,
496 const opus_val16 *window, int overlap)
499 /* printf ("%d %d %f %f\n", T0, T1, g0, g1); */
500 opus_val16 g00, g01, g02, g10, g11, g12;
501 static const opus_val16 gains[3][3] = {
502 {QCONST16(0.3066406250f, 15), QCONST16(0.2170410156f, 15), QCONST16(0.1296386719f, 15)},
503 {QCONST16(0.4638671875f, 15), QCONST16(0.2680664062f, 15), QCONST16(0.f, 15)},
504 {QCONST16(0.7998046875f, 15), QCONST16(0.1000976562f, 15), QCONST16(0.f, 15)}};
505 g00 = MULT16_16_Q15(g0, gains[tapset0][0]);
506 g01 = MULT16_16_Q15(g0, gains[tapset0][1]);
507 g02 = MULT16_16_Q15(g0, gains[tapset0][2]);
508 g10 = MULT16_16_Q15(g1, gains[tapset1][0]);
509 g11 = MULT16_16_Q15(g1, gains[tapset1][1]);
510 g12 = MULT16_16_Q15(g1, gains[tapset1][2]);
511 for (i=0;i<overlap;i++)
514 f = MULT16_16_Q15(window[i],window[i]);
516 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g00),x[i-T0])
517 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g01),x[i-T0-1])
518 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g01),x[i-T0+1])
519 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g02),x[i-T0-2])
520 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g02),x[i-T0+2])
521 + MULT16_32_Q15(MULT16_16_Q15(f,g10),x[i-T1])
522 + MULT16_32_Q15(MULT16_16_Q15(f,g11),x[i-T1-1])
523 + MULT16_32_Q15(MULT16_16_Q15(f,g11),x[i-T1+1])
524 + MULT16_32_Q15(MULT16_16_Q15(f,g12),x[i-T1-2])
525 + MULT16_32_Q15(MULT16_16_Q15(f,g12),x[i-T1+2]);
528 for (i=overlap;i<N;i++)
530 + MULT16_32_Q15(g10,x[i-T1])
531 + MULT16_32_Q15(g11,x[i-T1-1])
532 + MULT16_32_Q15(g11,x[i-T1+1])
533 + MULT16_32_Q15(g12,x[i-T1-2])
534 + MULT16_32_Q15(g12,x[i-T1+2]);
537 static const signed char tf_select_table[4][8] = {
538 {0, -1, 0, -1, 0,-1, 0,-1},
539 {0, -1, 0, -2, 1, 0, 1,-1},
540 {0, -2, 0, -3, 2, 0, 1,-1},
541 {0, -2, 0, -3, 3, 0, 1,-1},
544 static opus_val32 l1_metric(const celt_norm *tmp, int N, int LM, int width)
547 static const opus_val16 sqrtM_1[4] = {Q15ONE, QCONST16(.70710678f,15), QCONST16(0.5f,15), QCONST16(0.35355339f,15)};
551 for (i=0;i<1<<LM;i++)
554 for (j=0;j<N>>LM;j++)
555 L2 = MAC16_16(L2, tmp[(j<<LM)+i], tmp[(j<<LM)+i]);
558 L1 = MULT16_32_Q15(sqrtM_1[LM], L1);
560 bias = QCONST16(.12f,15)*LM;
562 bias = QCONST16(.05f,15)*LM;
564 bias = QCONST16(.02f,15)*LM;
565 L1 = MAC16_32_Q15(L1, bias, L1);
569 static int tf_analysis(const CELTMode *m, int len, int C, int isTransient,
570 int *tf_res, int nbCompressedBytes, celt_norm *X, int N0, int LM,
574 VARDECL(int, metric);
579 VARDECL(celt_norm, tmp);
584 if (nbCompressedBytes<15*C)
588 tf_res[i] = isTransient;
591 if (nbCompressedBytes<40)
593 else if (nbCompressedBytes<60)
595 else if (nbCompressedBytes<100)
600 ALLOC(metric, len, int);
601 ALLOC(tmp, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
602 ALLOC(path0, len, int);
603 ALLOC(path1, len, int);
609 opus_val32 L1, best_L1;
611 N = (m->eBands[i+1]-m->eBands[i])<<LM;
613 tmp[j] = X[j+(m->eBands[i]<<LM)];
614 /* Just add the right channel if we're in stereo */
617 tmp[j] = ADD16(tmp[j],X[N0+j+(m->eBands[i]<<LM)]);
618 L1 = l1_metric(tmp, N, isTransient ? LM : 0, N>>LM);
620 /*printf ("%f ", L1);*/
631 haar1(tmp, N>>(LM-k), 1<<(LM-k));
633 haar1(tmp, N>>k, 1<<k);
635 L1 = l1_metric(tmp, N, B, N>>LM);
643 /*printf ("%d ", isTransient ? LM-best_level : best_level);*/
645 metric[i] = best_level;
647 metric[i] = -best_level;
648 *tf_sum += metric[i];
651 /* NOTE: Future optimized implementations could detect extreme transients and set
652 tf_select = 1 but so far we have not found a reliable way of making this useful */
656 cost1 = isTransient ? 0 : lambda;
657 /* Viterbi forward pass */
664 from1 = cost1 + lambda;
674 from0 = cost0 + lambda;
684 cost0 = curr0 + abs(metric[i]-tf_select_table[LM][4*isTransient+2*tf_select+0]);
685 cost1 = curr1 + abs(metric[i]-tf_select_table[LM][4*isTransient+2*tf_select+1]);
687 tf_res[len-1] = cost0 < cost1 ? 0 : 1;
688 /* Viterbi backward pass to check the decisions */
689 for (i=len-2;i>=0;i--)
691 if (tf_res[i+1] == 1)
692 tf_res[i] = path1[i+1];
694 tf_res[i] = path0[i+1];
698 tf_select = rand()&0x1;
699 tf_res[0] = rand()&0x1;
701 tf_res[i] = tf_res[i-1] ^ ((rand()&0xF) == 0);
706 static void tf_encode(int start, int end, int isTransient, int *tf_res, int LM, int tf_select, ec_enc *enc)
714 budget = enc->storage*8;
716 logp = isTransient ? 2 : 4;
717 /* Reserve space to code the tf_select decision. */
718 tf_select_rsv = LM>0 && tell+logp+1 <= budget;
719 budget -= tf_select_rsv;
720 curr = tf_changed = 0;
721 for (i=start;i<end;i++)
723 if (tell+logp<=budget)
725 ec_enc_bit_logp(enc, tf_res[i] ^ curr, logp);
732 logp = isTransient ? 4 : 5;
734 /* Only code tf_select if it would actually make a difference. */
736 tf_select_table[LM][4*isTransient+0+tf_changed]!=
737 tf_select_table[LM][4*isTransient+2+tf_changed])
738 ec_enc_bit_logp(enc, tf_select, 1);
741 for (i=start;i<end;i++)
742 tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
743 /*printf("%d %d ", isTransient, tf_select); for(i=0;i<end;i++)printf("%d ", tf_res[i]);printf("\n");*/
746 static void tf_decode(int start, int end, int isTransient, int *tf_res, int LM, ec_dec *dec)
748 int i, curr, tf_select;
755 budget = dec->storage*8;
757 logp = isTransient ? 2 : 4;
758 tf_select_rsv = LM>0 && tell+logp+1<=budget;
759 budget -= tf_select_rsv;
760 tf_changed = curr = 0;
761 for (i=start;i<end;i++)
763 if (tell+logp<=budget)
765 curr ^= ec_dec_bit_logp(dec, logp);
770 logp = isTransient ? 4 : 5;
774 tf_select_table[LM][4*isTransient+0+tf_changed] !=
775 tf_select_table[LM][4*isTransient+2+tf_changed])
777 tf_select = ec_dec_bit_logp(dec, 1);
779 for (i=start;i<end;i++)
781 tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
785 static void init_caps(const CELTMode *m,int *cap,int LM,int C)
788 for (i=0;i<m->nbEBands;i++)
791 N=(m->eBands[i+1]-m->eBands[i])<<LM;
792 cap[i] = (m->cache.caps[m->nbEBands*(2*LM+C-1)+i]+64)*C*N>>2;
796 static int alloc_trim_analysis(const CELTMode *m, const celt_norm *X,
797 const opus_val16 *bandLogE, int end, int LM, int C, int N0)
805 opus_val16 sum = 0; /* Q10 */
806 /* Compute inter-channel correlation for low frequencies */
810 opus_val32 partial = 0;
811 for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
812 partial = MAC16_16(partial, X[j], X[N0+j]);
813 sum = ADD16(sum, EXTRACT16(SHR32(partial, 18)));
815 sum = MULT16_16_Q15(QCONST16(1.f/8, 15), sum);
816 /*printf ("%f\n", sum);*/
817 if (sum > QCONST16(.995f,10))
819 else if (sum > QCONST16(.92f,10))
821 else if (sum > QCONST16(.85f,10))
823 else if (sum > QCONST16(.8f,10))
827 /* Estimate spectral tilt */
829 for (i=0;i<end-1;i++)
831 diff += bandLogE[i+c*m->nbEBands]*(opus_int32)(2+2*i-m->nbEBands);
834 /* We divide by two here to avoid making the tilt larger for stereo as a
835 result of a bug in the loop above */
837 /*printf("%f\n", diff);*/
838 if (diff > QCONST16(2.f, DB_SHIFT))
840 if (diff > QCONST16(8.f, DB_SHIFT))
842 if (diff < -QCONST16(4.f, DB_SHIFT))
844 if (diff < -QCONST16(10.f, DB_SHIFT))
852 trim_index = rand()%11;
857 static int stereo_analysis(const CELTMode *m, const celt_norm *X,
862 opus_val32 sumLR = EPSILON, sumMS = EPSILON;
864 /* Use the L1 norm to model the entropy of the L/R signal vs the M/S signal */
868 for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
870 opus_val16 L, R, M, S;
875 sumLR += EXTEND32(ABS16(L)) + EXTEND32(ABS16(R));
876 sumMS += EXTEND32(ABS16(M)) + EXTEND32(ABS16(S));
879 sumMS = MULT16_32_Q15(QCONST16(0.707107f, 15), sumMS);
881 /* We don't need thetas for lower bands with LM<=1 */
884 return MULT16_32_Q15((m->eBands[13]<<(LM+1))+thetas, sumMS)
885 > MULT16_32_Q15(m->eBands[13]<<(LM+1), sumLR);
888 int celt_encode_with_ec(CELTEncoder * restrict st, const opus_val16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes, ec_enc *enc)
893 VARDECL(celt_sig, in);
894 VARDECL(celt_sig, freq);
895 VARDECL(celt_norm, X);
896 VARDECL(celt_ener, bandE);
897 VARDECL(opus_val16, bandLogE);
898 VARDECL(int, fine_quant);
899 VARDECL(opus_val16, error);
900 VARDECL(int, pulses);
902 VARDECL(int, offsets);
903 VARDECL(int, fine_priority);
904 VARDECL(int, tf_res);
905 VARDECL(unsigned char, collapse_masks);
906 celt_sig *prefilter_mem;
907 opus_val16 *oldBandE, *oldLogE, *oldLogE2;
910 const int CC = CHANNELS(st->channels);
911 const int C = CHANNELS(st->stream_channels);
914 int nbFilledBytes, nbAvailableBytes;
919 int pitch_index=COMBFILTER_MINPERIOD;
920 opus_val16 gain1 = 0;
924 opus_val16 pf_threshold;
927 opus_int32 total_bits;
928 opus_int32 total_boost;
931 int prefilter_tapset=0;
933 int anti_collapse_rsv;
934 int anti_collapse_on=0;
938 if (nbCompressedBytes<2 || pcm==NULL)
941 frame_size *= st->upsample;
942 for (LM=0;LM<=st->mode->maxLM;LM++)
943 if (st->mode->shortMdctSize<<LM==frame_size)
945 if (LM>st->mode->maxLM)
948 N = M*st->mode->shortMdctSize;
950 prefilter_mem = st->in_mem+CC*(st->overlap);
951 oldBandE = (opus_val16*)(st->in_mem+CC*(2*st->overlap+COMBFILTER_MAXPERIOD));
952 oldLogE = oldBandE + CC*st->mode->nbEBands;
953 oldLogE2 = oldLogE + CC*st->mode->nbEBands;
961 nbFilledBytes=(tell+4)>>3;
965 if (st->signalling && enc==NULL)
967 int tmp = (st->mode->effEBands-st->end)>>1;
968 st->end = IMAX(1, st->mode->effEBands-tmp);
969 compressed[0] = tmp<<5;
970 compressed[0] |= LM<<3;
971 compressed[0] |= (C==2)<<2;
972 /* Convert "standard mode" to Opus header */
973 if (st->mode->Fs==48000 && st->mode->shortMdctSize==120)
975 int c0 = toOpus(compressed[0]);
984 celt_assert(st->signalling==0);
987 /* Can't produce more than 1275 output bytes */
988 nbCompressedBytes = IMIN(nbCompressedBytes,1275);
989 nbAvailableBytes = nbCompressedBytes - nbFilledBytes;
991 if (st->vbr && st->bitrate!=OPUS_BITRATE_MAX)
993 opus_int32 den=st->mode->Fs>>BITRES;
994 vbr_rate=(st->bitrate*frame_size+(den>>1))/den;
997 vbr_rate -= 8<<BITRES;
999 effectiveBytes = vbr_rate>>(3+BITRES);
1003 tmp = st->bitrate*frame_size;
1006 if (st->bitrate!=OPUS_BITRATE_MAX)
1007 nbCompressedBytes = IMAX(2, IMIN(nbCompressedBytes,
1008 (tmp+4*st->mode->Fs)/(8*st->mode->Fs)-!!st->signalling));
1009 effectiveBytes = nbCompressedBytes;
1014 ec_enc_init(&_enc, compressed, nbCompressedBytes);
1020 /* Computes the max bit-rate allowed in VBR mode to avoid violating the
1021 target rate and buffering.
1022 We must do this up front so that bust-prevention logic triggers
1023 correctly if we don't have enough bits. */
1024 if (st->constrained_vbr)
1026 opus_int32 vbr_bound;
1027 opus_int32 max_allowed;
1028 /* We could use any multiple of vbr_rate as bound (depending on the
1030 This is clamped to ensure we use at least two bytes if the encoder
1031 was entirely empty, but to allow 0 in hybrid mode. */
1032 vbr_bound = vbr_rate;
1033 max_allowed = IMIN(IMAX(tell==1?2:0,
1034 (vbr_rate+vbr_bound-st->vbr_reservoir)>>(BITRES+3)),
1036 if(max_allowed < nbAvailableBytes)
1038 nbCompressedBytes = nbFilledBytes+max_allowed;
1039 nbAvailableBytes = max_allowed;
1040 ec_enc_shrink(enc, nbCompressedBytes);
1044 total_bits = nbCompressedBytes*8;
1047 if (effEnd > st->mode->effEBands)
1048 effEnd = st->mode->effEBands;
1050 ALLOC(in, CC*(N+st->overlap), celt_sig);
1052 /* Find pitch period and gain */
1054 VARDECL(celt_sig, _pre);
1057 ALLOC(_pre, CC*(N+COMBFILTER_MAXPERIOD), celt_sig);
1060 pre[1] = _pre + (N+COMBFILTER_MAXPERIOD);
1065 const opus_val16 * restrict pcmp = pcm+c;
1066 celt_sig * restrict inp = in+c*(N+st->overlap)+st->overlap;
1077 x = MAX32(-65536.f, MIN32(65536.f,x));
1079 if (++count==st->upsample)
1086 /* Apply pre-emphasis */
1087 tmp = MULT16_16(st->mode->preemph[2], x);
1088 *inp = tmp + st->preemph_memE[c];
1089 st->preemph_memE[c] = MULT16_32_Q15(st->mode->preemph[1], *inp)
1090 - MULT16_32_Q15(st->mode->preemph[0], tmp);
1091 silence = silence && *inp == 0;
1094 OPUS_COPY(pre[c], prefilter_mem+c*COMBFILTER_MAXPERIOD, COMBFILTER_MAXPERIOD);
1095 OPUS_COPY(pre[c]+COMBFILTER_MAXPERIOD, in+c*(N+st->overlap)+st->overlap, N);
1099 if ((rand()&0x3F)==0)
1103 ec_enc_bit_logp(enc, silence, 15);
1108 /*In VBR mode there is no need to send more than the minimum. */
1111 effectiveBytes=nbCompressedBytes=IMIN(nbCompressedBytes, nbFilledBytes+2);
1112 total_bits=nbCompressedBytes*8;
1114 ec_enc_shrink(enc, nbCompressedBytes);
1116 /* Pretend we've filled all the remaining bits with zeros
1117 (that's what the initialiser did anyway) */
1118 tell = nbCompressedBytes*8;
1119 enc->nbits_total+=tell-ec_tell(enc);
1121 if (nbAvailableBytes>12*C && st->start==0 && !silence && !st->disable_pf && st->complexity >= 5)
1123 VARDECL(opus_val16, pitch_buf);
1124 ALLOC(pitch_buf, (COMBFILTER_MAXPERIOD+N)>>1, opus_val16);
1126 pitch_downsample(pre, pitch_buf, COMBFILTER_MAXPERIOD+N, CC);
1127 pitch_search(pitch_buf+(COMBFILTER_MAXPERIOD>>1), pitch_buf, N,
1128 COMBFILTER_MAXPERIOD-COMBFILTER_MINPERIOD, &pitch_index);
1129 pitch_index = COMBFILTER_MAXPERIOD-pitch_index;
1131 gain1 = remove_doubling(pitch_buf, COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD,
1132 N, &pitch_index, st->prefilter_period, st->prefilter_gain);
1133 if (pitch_index > COMBFILTER_MAXPERIOD-2)
1134 pitch_index = COMBFILTER_MAXPERIOD-2;
1135 gain1 = MULT16_16_Q15(QCONST16(.7f,15),gain1);
1136 if (st->loss_rate>2)
1137 gain1 = HALF32(gain1);
1138 if (st->loss_rate>4)
1139 gain1 = HALF32(gain1);
1140 if (st->loss_rate>8)
1142 prefilter_tapset = st->tapset_decision;
1147 /* Gain threshold for enabling the prefilter/postfilter */
1148 pf_threshold = QCONST16(.2f,15);
1150 /* Adjusting the threshold based on rate and continuity */
1151 if (abs(pitch_index-st->prefilter_period)*10>pitch_index)
1152 pf_threshold += QCONST16(.2f,15);
1153 if (nbAvailableBytes<25)
1154 pf_threshold += QCONST16(.1f,15);
1155 if (nbAvailableBytes<35)
1156 pf_threshold += QCONST16(.1f,15);
1157 if (st->prefilter_gain > QCONST16(.4f,15))
1158 pf_threshold -= QCONST16(.1f,15);
1159 if (st->prefilter_gain > QCONST16(.55f,15))
1160 pf_threshold -= QCONST16(.1f,15);
1162 /* Hard threshold at 0.2 */
1163 pf_threshold = MAX16(pf_threshold, QCONST16(.2f,15));
1164 if (gain1<pf_threshold)
1166 if(st->start==0 && tell+16<=total_bits)
1167 ec_enc_bit_logp(enc, 0, 1);
1171 /*This block is not gated by a total bits check only because
1172 of the nbAvailableBytes check above.*/
1176 if (ABS16(gain1-st->prefilter_gain)<QCONST16(.1f,15))
1177 gain1=st->prefilter_gain;
1180 qg = ((gain1+1536)>>10)/3-1;
1182 qg = (int)floor(.5f+gain1*32/3)-1;
1184 qg = IMAX(0, IMIN(7, qg));
1185 ec_enc_bit_logp(enc, 1, 1);
1187 octave = EC_ILOG(pitch_index)-5;
1188 ec_enc_uint(enc, octave, 6);
1189 ec_enc_bits(enc, pitch_index-(16<<octave), 4+octave);
1191 ec_enc_bits(enc, qg, 3);
1192 if (ec_tell(enc)+2<=total_bits)
1193 ec_enc_icdf(enc, prefilter_tapset, tapset_icdf, 2);
1195 prefilter_tapset = 0;
1196 gain1 = QCONST16(0.09375f,15)*(qg+1);
1199 /*printf("%d %f\n", pitch_index, gain1);*/
1202 int offset = st->mode->shortMdctSize-st->mode->overlap;
1203 st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
1204 OPUS_COPY(in+c*(N+st->overlap), st->in_mem+c*(st->overlap), st->overlap);
1206 comb_filter(in+c*(N+st->overlap)+st->overlap, pre[c]+COMBFILTER_MAXPERIOD,
1207 st->prefilter_period, st->prefilter_period, offset, -st->prefilter_gain, -st->prefilter_gain,
1208 st->prefilter_tapset, st->prefilter_tapset, NULL, 0);
1210 comb_filter(in+c*(N+st->overlap)+st->overlap+offset, pre[c]+COMBFILTER_MAXPERIOD+offset,
1211 st->prefilter_period, pitch_index, N-offset, -st->prefilter_gain, -gain1,
1212 st->prefilter_tapset, prefilter_tapset, st->mode->window, st->mode->overlap);
1213 OPUS_COPY(st->in_mem+c*(st->overlap), in+c*(N+st->overlap)+N, st->overlap);
1215 if (N>COMBFILTER_MAXPERIOD)
1217 OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD, pre[c]+N, COMBFILTER_MAXPERIOD);
1219 OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD, prefilter_mem+c*COMBFILTER_MAXPERIOD+N, COMBFILTER_MAXPERIOD-N);
1220 OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD+COMBFILTER_MAXPERIOD-N, pre[c]+COMBFILTER_MAXPERIOD, N);
1229 if (LM>0 && ec_tell(enc)+3<=total_bits)
1231 if (st->complexity > 1)
1233 isTransient = transient_analysis(in, N+st->overlap, CC,
1238 ec_enc_bit_logp(enc, isTransient, 3);
1241 ALLOC(freq, CC*N, celt_sig); /**< Interleaved signal MDCTs */
1242 ALLOC(bandE,st->mode->nbEBands*CC, celt_ener);
1243 ALLOC(bandLogE,st->mode->nbEBands*CC, opus_val16);
1245 compute_mdcts(st->mode, shortBlocks, in, freq, CC, LM);
1250 freq[i] = ADD32(HALF32(freq[i]), HALF32(freq[N+i]));
1252 if (st->upsample != 1)
1256 int bound = N/st->upsample;
1257 for (i=0;i<bound;i++)
1258 freq[c*N+i] *= st->upsample;
1263 ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
1265 compute_band_energies(st->mode, freq, bandE, effEnd, C, M);
1267 amp2Log2(st->mode, effEnd, st->end, bandE, bandLogE, C);
1269 /* Band normalisation */
1270 normalise_bands(st->mode, freq, X, bandE, effEnd, C, M);
1272 ALLOC(tf_res, st->mode->nbEBands, int);
1273 tf_select = tf_analysis(st->mode, effEnd, C, isTransient, tf_res, effectiveBytes, X, N, LM, &tf_sum);
1274 for (i=effEnd;i<st->end;i++)
1275 tf_res[i] = tf_res[effEnd-1];
1277 ALLOC(error, C*st->mode->nbEBands, opus_val16);
1278 quant_coarse_energy(st->mode, st->start, st->end, effEnd, bandLogE,
1279 oldBandE, total_bits, error, enc,
1280 C, LM, nbAvailableBytes, st->force_intra,
1281 &st->delayedIntra, st->complexity >= 4, st->loss_rate);
1283 tf_encode(st->start, st->end, isTransient, tf_res, LM, tf_select, enc);
1285 st->spread_decision = SPREAD_NORMAL;
1286 if (ec_tell(enc)+4<=total_bits)
1288 if (shortBlocks || st->complexity < 3 || nbAvailableBytes < 10*C)
1290 if (st->complexity == 0)
1291 st->spread_decision = SPREAD_NONE;
1293 st->spread_decision = spreading_decision(st->mode, X,
1294 &st->tonal_average, st->spread_decision, &st->hf_average,
1295 &st->tapset_decision, pf_on&&!shortBlocks, effEnd, C, M);
1297 ec_enc_icdf(enc, st->spread_decision, spread_icdf, 5);
1300 ALLOC(cap, st->mode->nbEBands, int);
1301 ALLOC(offsets, st->mode->nbEBands, int);
1303 init_caps(st->mode,cap,LM,C);
1304 for (i=0;i<st->mode->nbEBands;i++)
1306 /* Dynamic allocation code */
1307 /* Make sure that dynamic allocation can't make us bust the budget */
1308 if (effectiveBytes > 50 && LM>=1)
1319 for (i=st->start+1;i<st->end-1;i++)
1322 d2 = 2*bandLogE[i]-bandLogE[i-1]-bandLogE[i+1];
1324 d2 = HALF32(d2 + 2*bandLogE[i+st->mode->nbEBands]-
1325 bandLogE[i-1+st->mode->nbEBands]-bandLogE[i+1+st->mode->nbEBands]);
1331 offsets[i] += 1+(rand()&0x3);
1334 if (d2 > SHL16(t1,DB_SHIFT))
1336 if (d2 > SHL16(t2,DB_SHIFT))
1342 total_bits<<=BITRES;
1344 tell = ec_tell_frac(enc);
1345 for (i=st->start;i<st->end;i++)
1348 int dynalloc_loop_logp;
1351 width = C*(st->mode->eBands[i+1]-st->mode->eBands[i])<<LM;
1352 /* quanta is 6 bits, but no more than 1 bit/sample
1353 and no less than 1/8 bit/sample */
1354 quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
1355 dynalloc_loop_logp = dynalloc_logp;
1357 for (j = 0; tell+(dynalloc_loop_logp<<BITRES) < total_bits-total_boost
1358 && boost < cap[i]; j++)
1361 flag = j<offsets[i];
1362 ec_enc_bit_logp(enc, flag, dynalloc_loop_logp);
1363 tell = ec_tell_frac(enc);
1367 total_boost += quanta;
1368 dynalloc_loop_logp = 1;
1370 /* Making dynalloc more likely */
1372 dynalloc_logp = IMAX(2, dynalloc_logp-1);
1376 if (tell+(6<<BITRES) <= total_bits - total_boost)
1378 alloc_trim = alloc_trim_analysis(st->mode, X, bandLogE,
1380 ec_enc_icdf(enc, alloc_trim, trim_icdf, 7);
1381 tell = ec_tell_frac(enc);
1384 /* Variable bitrate */
1389 /* The target rate in 8th bits per frame */
1391 opus_int32 min_allowed;
1392 int lm_diff = st->mode->maxLM - LM;
1394 target = vbr_rate + (st->vbr_offset>>lm_diff) - ((40*C+20)<<BITRES);
1396 /* Shortblocks get a large boost in bitrate, but since they
1397 are uncommon long blocks are not greatly affected */
1398 if (shortBlocks || tf_sum < -2*(st->end-st->start))
1399 target = 7*target/4;
1400 else if (tf_sum < -(st->end-st->start))
1401 target = 3*target/2;
1403 target-=(target+14)/28;
1405 /* The current offset is removed from the target and the space used
1409 /* In VBR mode the frame size must not be reduced so much that it would
1410 result in the encoder running out of bits.
1411 The margin of 2 bytes ensures that none of the bust-prevention logic
1412 in the decoder will have triggered so far. */
1413 min_allowed = ((tell+total_boost+(1<<(BITRES+3))-1)>>(BITRES+3)) + 2 - nbFilledBytes;
1415 nbAvailableBytes = (target+(1<<(BITRES+2)))>>(BITRES+3);
1416 nbAvailableBytes = IMAX(min_allowed,nbAvailableBytes);
1417 nbAvailableBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes) - nbFilledBytes;
1419 /* By how much did we "miss" the target on that frame */
1420 delta = target - vbr_rate;
1422 target=nbAvailableBytes<<(BITRES+3);
1424 /*If the frame is silent we don't adjust our drift, otherwise
1425 the encoder will shoot to very high rates after hitting a
1426 span of silence, but we do allow the bitres to refill.
1427 This means that we'll undershoot our target in CVBR/VBR modes
1428 on files with lots of silence. */
1431 nbAvailableBytes = 2;
1432 target = 2*8<<BITRES;
1436 if (st->vbr_count < 970)
1439 alpha = celt_rcp(SHL32(EXTEND32(st->vbr_count+20),16));
1441 alpha = QCONST16(.001f,15);
1442 /* How many bits have we used in excess of what we're allowed */
1443 if (st->constrained_vbr)
1444 st->vbr_reservoir += target - vbr_rate;
1445 /*printf ("%d\n", st->vbr_reservoir);*/
1447 /* Compute the offset we need to apply in order to reach the target */
1448 st->vbr_drift += (opus_int32)MULT16_32_Q15(alpha,(delta*(1<<lm_diff))-st->vbr_offset-st->vbr_drift);
1449 st->vbr_offset = -st->vbr_drift;
1450 /*printf ("%d\n", st->vbr_drift);*/
1452 if (st->constrained_vbr && st->vbr_reservoir < 0)
1454 /* We're under the min value -- increase rate */
1455 int adjust = (-st->vbr_reservoir)/(8<<BITRES);
1456 /* Unless we're just coding silence */
1457 nbAvailableBytes += silence?0:adjust;
1458 st->vbr_reservoir = 0;
1459 /*printf ("+%d\n", adjust);*/
1461 nbCompressedBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes);
1462 /* This moves the raw bits to take into account the new compressed size */
1463 ec_enc_shrink(enc, nbCompressedBytes);
1469 /* Always use MS for 2.5 ms frames until we can do a better analysis */
1471 dual_stereo = stereo_analysis(st->mode, X, LM, N);
1473 /* Account for coarse energy */
1474 effectiveRate = (8*effectiveBytes - 80)>>LM;
1476 /* effectiveRate in kb/s */
1477 effectiveRate = 2*effectiveRate/5;
1478 if (effectiveRate<35)
1480 else if (effectiveRate<50)
1482 else if (effectiveRate<68)
1484 else if (effectiveRate<84)
1486 else if (effectiveRate<102)
1488 else if (effectiveRate<130)
1492 intensity = IMIN(st->end,IMAX(st->start, intensity));
1495 /* Bit allocation */
1496 ALLOC(fine_quant, st->mode->nbEBands, int);
1497 ALLOC(pulses, st->mode->nbEBands, int);
1498 ALLOC(fine_priority, st->mode->nbEBands, int);
1500 /* bits = packet size - where we are - safety*/
1501 bits = (((opus_int32)nbCompressedBytes*8)<<BITRES) - ec_tell_frac(enc) - 1;
1502 anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
1503 bits -= anti_collapse_rsv;
1504 codedBands = compute_allocation(st->mode, st->start, st->end, offsets, cap,
1505 alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
1506 fine_quant, fine_priority, C, LM, enc, 1, st->lastCodedBands);
1507 st->lastCodedBands = codedBands;
1509 quant_fine_energy(st->mode, st->start, st->end, oldBandE, error, fine_quant, enc, C);
1511 #ifdef MEASURE_NORM_MSE
1516 X0[i+c*N] = X[i+c*N];
1518 for (i=0;i<C*st->mode->nbEBands;i++)
1519 bandE0[i] = bandE[i];
1522 /* Residual quantisation */
1523 ALLOC(collapse_masks, C*st->mode->nbEBands, unsigned char);
1524 quant_all_bands(1, st->mode, st->start, st->end, X, C==2 ? X+N : NULL, collapse_masks,
1525 bandE, pulses, shortBlocks, st->spread_decision, dual_stereo, intensity, tf_res,
1526 nbCompressedBytes*(8<<BITRES)-anti_collapse_rsv, balance, enc, LM, codedBands, &st->rng);
1528 if (anti_collapse_rsv > 0)
1530 anti_collapse_on = st->consec_transient<2;
1532 anti_collapse_on = rand()&0x1;
1534 ec_enc_bits(enc, anti_collapse_on, 1);
1536 quant_energy_finalise(st->mode, st->start, st->end, oldBandE, error, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, C);
1540 for (i=0;i<C*st->mode->nbEBands;i++)
1541 oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
1545 /* Re-synthesis of the coded audio if required */
1547 celt_sig *out_mem[2];
1548 celt_sig *overlap_mem[2];
1550 log2Amp(st->mode, st->start, st->end, bandE, oldBandE, C);
1553 for (i=0;i<C*st->mode->nbEBands;i++)
1557 #ifdef MEASURE_NORM_MSE
1558 measure_norm_mse(st->mode, X, X0, bandE, bandE0, M, N, C);
1560 if (anti_collapse_on)
1562 anti_collapse(st->mode, X, collapse_masks, LM, C, CC, N,
1563 st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
1567 denormalise_bands(st->mode, X, freq, bandE, effEnd, C, M);
1569 OPUS_MOVE(st->syn_mem[0], st->syn_mem[0]+N, MAX_PERIOD);
1571 OPUS_MOVE(st->syn_mem[1], st->syn_mem[1]+N, MAX_PERIOD);
1574 for (i=0;i<M*st->mode->eBands[st->start];i++)
1578 for (i=M*st->mode->eBands[st->end];i<N;i++)
1585 freq[N+i] = freq[i];
1588 out_mem[0] = st->syn_mem[0]+MAX_PERIOD;
1590 out_mem[1] = st->syn_mem[1]+MAX_PERIOD;
1592 overlap_mem[0] = prefilter_mem+CC*COMBFILTER_MAXPERIOD;
1594 overlap_mem[1] = overlap_mem[0] + st->overlap;
1596 compute_inv_mdcts(st->mode, shortBlocks, freq, out_mem, overlap_mem, CC, LM);
1599 st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
1600 st->prefilter_period_old=IMAX(st->prefilter_period_old, COMBFILTER_MINPERIOD);
1601 comb_filter(out_mem[c], out_mem[c], st->prefilter_period_old, st->prefilter_period, st->mode->shortMdctSize,
1602 st->prefilter_gain_old, st->prefilter_gain, st->prefilter_tapset_old, st->prefilter_tapset,
1603 st->mode->window, st->overlap);
1605 comb_filter(out_mem[c]+st->mode->shortMdctSize, out_mem[c]+st->mode->shortMdctSize, st->prefilter_period, pitch_index, N-st->mode->shortMdctSize,
1606 st->prefilter_gain, gain1, st->prefilter_tapset, prefilter_tapset,
1607 st->mode->window, st->mode->overlap);
1610 deemphasis(out_mem, (opus_val16*)pcm, N, CC, st->upsample, st->mode->preemph, st->preemph_memD);
1611 st->prefilter_period_old = st->prefilter_period;
1612 st->prefilter_gain_old = st->prefilter_gain;
1613 st->prefilter_tapset_old = st->prefilter_tapset;
1617 st->prefilter_period = pitch_index;
1618 st->prefilter_gain = gain1;
1619 st->prefilter_tapset = prefilter_tapset;
1623 st->prefilter_period_old = st->prefilter_period;
1624 st->prefilter_gain_old = st->prefilter_gain;
1625 st->prefilter_tapset_old = st->prefilter_tapset;
1630 for (i=0;i<st->mode->nbEBands;i++)
1631 oldBandE[st->mode->nbEBands+i]=oldBandE[i];
1634 /* In case start or end were to change */
1637 for (i=0;i<st->start;i++)
1638 oldBandE[c*st->mode->nbEBands+i]=0;
1639 for (i=st->end;i<st->mode->nbEBands;i++)
1640 oldBandE[c*st->mode->nbEBands+i]=0;
1644 for (i=0;i<CC*st->mode->nbEBands;i++)
1645 oldLogE2[i] = oldLogE[i];
1646 for (i=0;i<CC*st->mode->nbEBands;i++)
1647 oldLogE[i] = oldBandE[i];
1649 for (i=0;i<CC*st->mode->nbEBands;i++)
1650 oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
1653 st->consec_transient++;
1655 st->consec_transient=0;
1658 /* If there's any room left (can only happen for very high rates),
1659 it's already filled with zeros */
1664 nbCompressedBytes++;
1668 if (ec_get_error(enc))
1669 return OPUS_INTERNAL_ERROR;
1671 return nbCompressedBytes;
1678 int opus_custom_encode(CELTEncoder * restrict st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
1680 return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
1683 #ifndef DISABLE_FLOAT_API
1684 int opus_custom_encode_float(CELTEncoder * restrict st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
1687 VARDECL(opus_int16, in);
1691 return OPUS_BAD_ARG;
1693 C = CHANNELS(st->channels);
1695 ALLOC(in, C*N, opus_int16);
1698 in[j] = FLOAT2INT16(pcm[j]);
1700 ret=celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
1703 ((float*)pcm)[j]=in[j]*(1.f/32768.f);
1708 #endif /* DISABLE_FLOAT_API */
1711 int opus_custom_encode(CELTEncoder * restrict st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
1714 VARDECL(celt_sig, in);
1718 return OPUS_BAD_ARG;
1720 C=CHANNELS(st->channels);
1722 ALLOC(in, C*N, celt_sig);
1723 for (j=0;j<C*N;j++) {
1724 in[j] = SCALEOUT(pcm[j]);
1727 ret = celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
1730 ((opus_int16*)pcm)[j] = FLOAT2INT16(in[j]);
1736 int opus_custom_encode_float(CELTEncoder * restrict st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
1738 return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
1743 #endif /* CUSTOM_MODES */
1745 int opus_custom_encoder_ctl(CELTEncoder * restrict st, int request, ...)
1749 va_start(ap, request);
1752 case OPUS_SET_COMPLEXITY_REQUEST:
1754 int value = va_arg(ap, opus_int32);
1755 if (value<0 || value>10)
1757 st->complexity = value;
1760 case CELT_SET_START_BAND_REQUEST:
1762 opus_int32 value = va_arg(ap, opus_int32);
1763 if (value<0 || value>=st->mode->nbEBands)
1768 case CELT_SET_END_BAND_REQUEST:
1770 opus_int32 value = va_arg(ap, opus_int32);
1771 if (value<1 || value>st->mode->nbEBands)
1776 case CELT_SET_PREDICTION_REQUEST:
1778 int value = va_arg(ap, opus_int32);
1779 if (value<0 || value>2)
1781 st->disable_pf = value<=1;
1782 st->force_intra = value==0;
1785 case OPUS_SET_PACKET_LOSS_PERC_REQUEST:
1787 int value = va_arg(ap, opus_int32);
1788 if (value<0 || value>100)
1790 st->loss_rate = value;
1793 case OPUS_SET_VBR_CONSTRAINT_REQUEST:
1795 opus_int32 value = va_arg(ap, opus_int32);
1796 st->constrained_vbr = value;
1799 case OPUS_SET_VBR_REQUEST:
1801 opus_int32 value = va_arg(ap, opus_int32);
1805 case OPUS_SET_BITRATE_REQUEST:
1807 opus_int32 value = va_arg(ap, opus_int32);
1808 if (value<=500 && value!=OPUS_BITRATE_MAX)
1810 value = IMIN(value, 260000*st->channels);
1811 st->bitrate = value;
1814 case CELT_SET_CHANNELS_REQUEST:
1816 opus_int32 value = va_arg(ap, opus_int32);
1817 if (value<1 || value>2)
1819 st->stream_channels = value;
1822 case OPUS_RESET_STATE:
1824 OPUS_CLEAR((char*)&st->ENCODER_RESET_START,
1825 opus_custom_encoder_get_size(st->mode, st->channels)-
1826 ((char*)&st->ENCODER_RESET_START - (char*)st));
1828 st->delayedIntra = 1;
1829 st->spread_decision = SPREAD_NORMAL;
1830 st->tonal_average = 256;
1834 case CELT_SET_INPUT_CLIPPING_REQUEST:
1836 opus_int32 value = va_arg(ap, opus_int32);
1841 case CELT_SET_SIGNALLING_REQUEST:
1843 opus_int32 value = va_arg(ap, opus_int32);
1844 st->signalling = value;
1847 case CELT_GET_MODE_REQUEST:
1849 const CELTMode ** value = va_arg(ap, const CELTMode**);
1855 case OPUS_GET_FINAL_RANGE_REQUEST:
1857 opus_uint32 * value = va_arg(ap, opus_uint32 *);
1870 return OPUS_BAD_ARG;
1873 return OPUS_UNIMPLEMENTED;
1876 /**********************************************************************/
1880 /**********************************************************************/
1881 #define DECODE_BUFFER_SIZE 2048
1884 @brief Decoder state
1886 struct OpusCustomDecoder {
1887 const OpusCustomMode *mode;
1890 int stream_channels;
1896 /* Everything beyond this point gets cleared on a reset */
1897 #define DECODER_RESET_START rng
1901 int last_pitch_index;
1903 int postfilter_period;
1904 int postfilter_period_old;
1905 opus_val16 postfilter_gain;
1906 opus_val16 postfilter_gain_old;
1907 int postfilter_tapset;
1908 int postfilter_tapset_old;
1910 celt_sig preemph_memD[2];
1912 celt_sig _decode_mem[1]; /* Size = channels*(DECODE_BUFFER_SIZE+mode->overlap) */
1913 /* opus_val16 lpc[], Size = channels*LPC_ORDER */
1914 /* opus_val16 oldEBands[], Size = 2*mode->nbEBands */
1915 /* opus_val16 oldLogE[], Size = 2*mode->nbEBands */
1916 /* opus_val16 oldLogE2[], Size = 2*mode->nbEBands */
1917 /* opus_val16 backgroundLogE[], Size = 2*mode->nbEBands */
1920 int celt_decoder_get_size(int channels)
1922 const CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
1923 return opus_custom_decoder_get_size(mode, channels);
1926 OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_get_size(const CELTMode *mode, int channels)
1928 int size = sizeof(struct CELTDecoder)
1929 + (channels*(DECODE_BUFFER_SIZE+mode->overlap)-1)*sizeof(celt_sig)
1930 + channels*LPC_ORDER*sizeof(opus_val16)
1931 + 4*2*mode->nbEBands*sizeof(opus_val16);
1936 CELTDecoder *opus_custom_decoder_create(const CELTMode *mode, int channels, int *error)
1939 CELTDecoder *st = (CELTDecoder *)opus_alloc(opus_custom_decoder_get_size(mode, channels));
1940 ret = opus_custom_decoder_init(st, mode, channels);
1943 opus_custom_decoder_destroy(st);
1950 #endif /* CUSTOM_MODES */
1952 int celt_decoder_init(CELTDecoder *st, opus_int32 sampling_rate, int channels)
1955 ret = opus_custom_decoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
1958 st->downsample = resampling_factor(sampling_rate);
1959 if (st->downsample==0)
1960 return OPUS_BAD_ARG;
1965 OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_init(CELTDecoder *st, const CELTMode *mode, int channels)
1967 if (channels < 0 || channels > 2)
1968 return OPUS_BAD_ARG;
1971 return OPUS_ALLOC_FAIL;
1973 OPUS_CLEAR((char*)st, opus_custom_decoder_get_size(mode, channels));
1976 st->overlap = mode->overlap;
1977 st->stream_channels = st->channels = channels;
1981 st->end = st->mode->effEBands;
1990 void opus_custom_decoder_destroy(CELTDecoder *st)
1994 #endif /* CUSTOM_MODES */
1996 static void celt_decode_lost(CELTDecoder * restrict st, opus_val16 * restrict pcm, int N, int LM)
2000 int overlap = st->mode->overlap;
2001 opus_val16 fade = Q15ONE;
2003 const int C = CHANNELS(st->channels);
2005 celt_sig *out_mem[2];
2006 celt_sig *decode_mem[2];
2007 celt_sig *overlap_mem[2];
2009 opus_val32 *out_syn[2];
2010 opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
2014 decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+st->overlap);
2015 out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
2016 overlap_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE;
2018 lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*C);
2019 oldBandE = lpc+C*LPC_ORDER;
2020 oldLogE = oldBandE + 2*st->mode->nbEBands;
2021 oldLogE2 = oldLogE + 2*st->mode->nbEBands;
2022 backgroundLogE = oldLogE2 + 2*st->mode->nbEBands;
2024 out_syn[0] = out_mem[0]+MAX_PERIOD-N;
2026 out_syn[1] = out_mem[1]+MAX_PERIOD-N;
2028 len = N+st->mode->overlap;
2030 if (st->loss_count >= 5 || st->start!=0)
2032 /* Noise-based PLC/CNG */
2033 VARDECL(celt_sig, freq);
2034 VARDECL(celt_norm, X);
2035 VARDECL(celt_ener, bandE);
2040 if (effEnd > st->mode->effEBands)
2041 effEnd = st->mode->effEBands;
2043 ALLOC(freq, C*N, celt_sig); /**< Interleaved signal MDCTs */
2044 ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
2045 ALLOC(bandE, st->mode->nbEBands*C, celt_ener);
2047 if (st->loss_count >= 5)
2048 log2Amp(st->mode, st->start, st->end, bandE, backgroundLogE, C);
2051 opus_val16 decay = st->loss_count==0 ? QCONST16(1.5f, DB_SHIFT) : QCONST16(.5f, DB_SHIFT);
2054 for (i=st->start;i<st->end;i++)
2055 oldBandE[c*st->mode->nbEBands+i] -= decay;
2057 log2Amp(st->mode, st->start, st->end, bandE, oldBandE, C);
2062 for (i=0;i<(st->mode->eBands[st->start]<<LM);i++)
2064 for (i=st->start;i<st->mode->effEBands;i++)
2069 boffs = N*c+(st->mode->eBands[i]<<LM);
2070 blen = (st->mode->eBands[i+1]-st->mode->eBands[i])<<LM;
2071 for (j=0;j<blen;j++)
2073 seed = celt_lcg_rand(seed);
2074 X[boffs+j] = (celt_norm)((opus_int32)seed>>20);
2076 renormalise_vector(X+boffs, blen, Q15ONE);
2078 for (i=(st->mode->eBands[st->end]<<LM);i<N;i++)
2083 denormalise_bands(st->mode, X, freq, bandE, st->mode->effEBands, C, 1<<LM);
2086 for (i=0;i<st->mode->eBands[st->start]<<LM;i++)
2090 int bound = st->mode->eBands[effEnd]<<LM;
2091 if (st->downsample!=1)
2092 bound = IMIN(bound, N/st->downsample);
2093 for (i=bound;i<N;i++)
2096 compute_inv_mdcts(st->mode, 0, freq, out_syn, overlap_mem, C, LM);
2098 /* Pitch-based PLC */
2099 if (st->loss_count == 0)
2101 opus_val16 pitch_buf[DECODE_BUFFER_SIZE>>1];
2102 /* Corresponds to a min pitch of 67 Hz. It's possible to save CPU in this
2103 search by using only part of the decode buffer */
2105 pitch_downsample(decode_mem, pitch_buf, DECODE_BUFFER_SIZE, C);
2106 /* Max pitch is 100 samples (480 Hz) */
2107 pitch_search(pitch_buf+((poffset)>>1), pitch_buf, DECODE_BUFFER_SIZE-poffset,
2108 poffset-100, &pitch_index);
2109 pitch_index = poffset-pitch_index;
2110 st->last_pitch_index = pitch_index;
2112 pitch_index = st->last_pitch_index;
2113 fade = QCONST16(.8f,15);
2117 VARDECL(opus_val32, e);
2118 opus_val16 exc[MAX_PERIOD];
2119 opus_val32 ac[LPC_ORDER+1];
2120 opus_val16 decay = 1;
2122 opus_val16 mem[LPC_ORDER]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2124 ALLOC(e, MAX_PERIOD+2*st->mode->overlap, opus_val32);
2126 offset = MAX_PERIOD-pitch_index;
2127 for (i=0;i<MAX_PERIOD;i++)
2128 exc[i] = ROUND16(out_mem[c][i], SIG_SHIFT);
2130 if (st->loss_count == 0)
2132 _celt_autocorr(exc, ac, st->mode->window, st->mode->overlap,
2133 LPC_ORDER, MAX_PERIOD);
2135 /* Noise floor -40 dB */
2137 ac[0] += SHR32(ac[0],13);
2142 for (i=1;i<=LPC_ORDER;i++)
2144 /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
2146 ac[i] -= MULT16_32_Q15(2*i*i, ac[i]);
2148 ac[i] -= ac[i]*(.008f*i)*(.008f*i);
2152 _celt_lpc(lpc+c*LPC_ORDER, ac, LPC_ORDER);
2154 for (i=0;i<LPC_ORDER;i++)
2155 mem[i] = ROUND16(out_mem[c][MAX_PERIOD-1-i], SIG_SHIFT);
2156 celt_fir(exc, lpc+c*LPC_ORDER, exc, MAX_PERIOD, LPC_ORDER, mem);
2157 /*for (i=0;i<MAX_PERIOD;i++)printf("%d ", exc[i]); printf("\n");*/
2158 /* Check if the waveform is decaying (and if so how fast) */
2160 opus_val32 E1=1, E2=1;
2162 if (pitch_index <= MAX_PERIOD/2)
2163 period = pitch_index;
2165 period = MAX_PERIOD/2;
2166 for (i=0;i<period;i++)
2168 E1 += SHR32(MULT16_16(exc[MAX_PERIOD-period+i],exc[MAX_PERIOD-period+i]),8);
2169 E2 += SHR32(MULT16_16(exc[MAX_PERIOD-2*period+i],exc[MAX_PERIOD-2*period+i]),8);
2173 decay = celt_sqrt(frac_div32(SHR(E1,1),E2));
2176 /* Copy excitation, taking decay into account */
2177 for (i=0;i<len+st->mode->overlap;i++)
2180 if (offset+i >= MAX_PERIOD)
2182 offset -= pitch_index;
2183 decay = MULT16_16_Q15(decay, decay);
2185 e[i] = SHL32(EXTEND32(MULT16_16_Q15(decay, exc[offset+i])), SIG_SHIFT);
2186 tmp = ROUND16(out_mem[c][offset+i],SIG_SHIFT);
2187 S1 += SHR32(MULT16_16(tmp,tmp),8);
2189 for (i=0;i<LPC_ORDER;i++)
2190 mem[i] = ROUND16(out_mem[c][MAX_PERIOD-1-i], SIG_SHIFT);
2191 for (i=0;i<len+st->mode->overlap;i++)
2192 e[i] = MULT16_32_Q15(fade, e[i]);
2193 celt_iir(e, lpc+c*LPC_ORDER, e, len+st->mode->overlap, LPC_ORDER, mem);
2197 for (i=0;i<len+overlap;i++)
2199 opus_val16 tmp = ROUND16(e[i],SIG_SHIFT);
2200 S2 += SHR32(MULT16_16(tmp,tmp),8);
2202 /* This checks for an "explosion" in the synthesis */
2204 if (!(S1 > SHR32(S2,2)))
2206 /* Float test is written this way to catch NaNs at the same time */
2207 if (!(S1 > 0.2f*S2))
2210 for (i=0;i<len+overlap;i++)
2214 opus_val16 ratio = celt_sqrt(frac_div32(SHR32(S1,1)+1,S2+1));
2215 for (i=0;i<len+overlap;i++)
2216 e[i] = MULT16_32_Q15(ratio, e[i]);
2220 /* Apply post-filter to the MDCT overlap of the previous frame */
2221 comb_filter(out_mem[c]+MAX_PERIOD, out_mem[c]+MAX_PERIOD, st->postfilter_period, st->postfilter_period, st->overlap,
2222 st->postfilter_gain, st->postfilter_gain, st->postfilter_tapset, st->postfilter_tapset,
2225 for (i=0;i<MAX_PERIOD+st->mode->overlap-N;i++)
2226 out_mem[c][i] = out_mem[c][N+i];
2228 /* Apply TDAC to the concealed audio so that it blends with the
2229 previous and next frames */
2230 for (i=0;i<overlap/2;i++)
2233 tmp = MULT16_32_Q15(st->mode->window[i], e[N+overlap-1-i]) +
2234 MULT16_32_Q15(st->mode->window[overlap-i-1], e[N+i ]);
2235 out_mem[c][MAX_PERIOD+i] = MULT16_32_Q15(st->mode->window[overlap-i-1], tmp);
2236 out_mem[c][MAX_PERIOD+overlap-i-1] = MULT16_32_Q15(st->mode->window[i], tmp);
2239 out_mem[c][MAX_PERIOD-N+i] = e[i];
2241 /* Apply pre-filter to the MDCT overlap for the next frame (post-filter will be applied then) */
2242 comb_filter(e, out_mem[c]+MAX_PERIOD, st->postfilter_period, st->postfilter_period, st->overlap,
2243 -st->postfilter_gain, -st->postfilter_gain, st->postfilter_tapset, st->postfilter_tapset,
2245 for (i=0;i<overlap;i++)
2246 out_mem[c][MAX_PERIOD+i] = e[i];
2250 deemphasis(out_syn, pcm, N, C, st->downsample, st->mode->preemph, st->preemph_memD);
2257 int celt_decode_with_ec(CELTDecoder * restrict st, const unsigned char *data, int len, opus_val16 * restrict pcm, int frame_size, ec_dec *dec)
2260 int spread_decision;
2263 VARDECL(celt_sig, freq);
2264 VARDECL(celt_norm, X);
2265 VARDECL(celt_ener, bandE);
2266 VARDECL(int, fine_quant);
2267 VARDECL(int, pulses);
2269 VARDECL(int, offsets);
2270 VARDECL(int, fine_priority);
2271 VARDECL(int, tf_res);
2272 VARDECL(unsigned char, collapse_masks);
2273 celt_sig *out_mem[2];
2274 celt_sig *decode_mem[2];
2275 celt_sig *overlap_mem[2];
2276 celt_sig *out_syn[2];
2278 opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
2283 const int CC = CHANNELS(st->channels);
2288 int postfilter_pitch;
2289 opus_val16 postfilter_gain;
2292 opus_int32 total_bits;
2296 int postfilter_tapset;
2297 int anti_collapse_rsv;
2298 int anti_collapse_on=0;
2300 int C = CHANNELS(st->stream_channels);
2303 frame_size *= st->downsample;
2306 decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+st->overlap);
2307 out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
2308 overlap_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE;
2310 lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*CC);
2311 oldBandE = lpc+CC*LPC_ORDER;
2312 oldLogE = oldBandE + 2*st->mode->nbEBands;
2313 oldLogE2 = oldLogE + 2*st->mode->nbEBands;
2314 backgroundLogE = oldLogE2 + 2*st->mode->nbEBands;
2317 if (st->signalling && data!=NULL)
2320 /* Convert "standard mode" to Opus header */
2321 if (st->mode->Fs==48000 && st->mode->shortMdctSize==120)
2323 data0 = fromOpus(data0);
2325 return OPUS_INVALID_PACKET;
2327 st->end = IMAX(1, st->mode->effEBands-2*(data0>>5));
2328 LM = (data0>>3)&0x3;
2329 C = 1 + ((data0>>2)&0x1);
2332 if (LM>st->mode->maxLM)
2333 return OPUS_INVALID_PACKET;
2334 if (frame_size < st->mode->shortMdctSize<<LM)
2335 return OPUS_BUFFER_TOO_SMALL;
2337 frame_size = st->mode->shortMdctSize<<LM;
2342 for (LM=0;LM<=st->mode->maxLM;LM++)
2343 if (st->mode->shortMdctSize<<LM==frame_size)
2345 if (LM>st->mode->maxLM)
2346 return OPUS_BAD_ARG;
2350 if (len<0 || len>1275 || pcm==NULL)
2351 return OPUS_BAD_ARG;
2353 N = M*st->mode->shortMdctSize;
2356 if (effEnd > st->mode->effEBands)
2357 effEnd = st->mode->effEBands;
2359 ALLOC(freq, IMAX(CC,C)*N, celt_sig); /**< Interleaved signal MDCTs */
2360 ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
2361 ALLOC(bandE, st->mode->nbEBands*C, celt_ener);
2363 for (i=0;i<M*st->mode->eBands[st->start];i++)
2367 for (i=M*st->mode->eBands[effEnd];i<N;i++)
2371 if (data == NULL || len<=1)
2373 celt_decode_lost(st, pcm, N, LM);
2375 return frame_size/st->downsample;
2380 ec_dec_init(&_dec,(unsigned char*)data,len);
2386 for (i=0;i<st->mode->nbEBands;i++)
2387 oldBandE[i]=MAX16(oldBandE[i],oldBandE[st->mode->nbEBands+i]);
2391 tell = ec_tell(dec);
2393 if (tell >= total_bits)
2396 silence = ec_dec_bit_logp(dec, 15);
2401 /* Pretend we've read all the remaining bits */
2403 dec->nbits_total+=tell-ec_tell(dec);
2406 postfilter_gain = 0;
2407 postfilter_pitch = 0;
2408 postfilter_tapset = 0;
2409 if (st->start==0 && tell+16 <= total_bits)
2411 if(ec_dec_bit_logp(dec, 1))
2414 octave = ec_dec_uint(dec, 6);
2415 postfilter_pitch = (16<<octave)+ec_dec_bits(dec, 4+octave)-1;
2416 qg = ec_dec_bits(dec, 3);
2417 if (ec_tell(dec)+2<=total_bits)
2418 postfilter_tapset = ec_dec_icdf(dec, tapset_icdf, 2);
2419 postfilter_gain = QCONST16(.09375f,15)*(qg+1);
2421 tell = ec_tell(dec);
2424 if (LM > 0 && tell+3 <= total_bits)
2426 isTransient = ec_dec_bit_logp(dec, 3);
2427 tell = ec_tell(dec);
2437 /* Decode the global flags (first symbols in the stream) */
2438 intra_ener = tell+3<=total_bits ? ec_dec_bit_logp(dec, 3) : 0;
2439 /* Get band energies */
2440 unquant_coarse_energy(st->mode, st->start, st->end, oldBandE,
2441 intra_ener, dec, C, LM);
2443 ALLOC(tf_res, st->mode->nbEBands, int);
2444 tf_decode(st->start, st->end, isTransient, tf_res, LM, dec);
2446 tell = ec_tell(dec);
2447 spread_decision = SPREAD_NORMAL;
2448 if (tell+4 <= total_bits)
2449 spread_decision = ec_dec_icdf(dec, spread_icdf, 5);
2451 ALLOC(pulses, st->mode->nbEBands, int);
2452 ALLOC(cap, st->mode->nbEBands, int);
2453 ALLOC(offsets, st->mode->nbEBands, int);
2454 ALLOC(fine_priority, st->mode->nbEBands, int);
2456 init_caps(st->mode,cap,LM,C);
2459 total_bits<<=BITRES;
2460 tell = ec_tell_frac(dec);
2461 for (i=st->start;i<st->end;i++)
2464 int dynalloc_loop_logp;
2466 width = C*(st->mode->eBands[i+1]-st->mode->eBands[i])<<LM;
2467 /* quanta is 6 bits, but no more than 1 bit/sample
2468 and no less than 1/8 bit/sample */
2469 quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
2470 dynalloc_loop_logp = dynalloc_logp;
2472 while (tell+(dynalloc_loop_logp<<BITRES) < total_bits && boost < cap[i])
2475 flag = ec_dec_bit_logp(dec, dynalloc_loop_logp);
2476 tell = ec_tell_frac(dec);
2480 total_bits -= quanta;
2481 dynalloc_loop_logp = 1;
2484 /* Making dynalloc more likely */
2486 dynalloc_logp = IMAX(2, dynalloc_logp-1);
2489 ALLOC(fine_quant, st->mode->nbEBands, int);
2490 alloc_trim = tell+(6<<BITRES) <= total_bits ?
2491 ec_dec_icdf(dec, trim_icdf, 7) : 5;
2493 bits = (((opus_int32)len*8)<<BITRES) - ec_tell_frac(dec) - 1;
2494 anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
2495 bits -= anti_collapse_rsv;
2496 codedBands = compute_allocation(st->mode, st->start, st->end, offsets, cap,
2497 alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
2498 fine_quant, fine_priority, C, LM, dec, 0, 0);
2500 unquant_fine_energy(st->mode, st->start, st->end, oldBandE, fine_quant, dec, C);
2502 /* Decode fixed codebook */
2503 ALLOC(collapse_masks, C*st->mode->nbEBands, unsigned char);
2504 quant_all_bands(0, st->mode, st->start, st->end, X, C==2 ? X+N : NULL, collapse_masks,
2505 NULL, pulses, shortBlocks, spread_decision, dual_stereo, intensity, tf_res,
2506 len*(8<<BITRES)-anti_collapse_rsv, balance, dec, LM, codedBands, &st->rng);
2508 if (anti_collapse_rsv > 0)
2510 anti_collapse_on = ec_dec_bits(dec, 1);
2513 unquant_energy_finalise(st->mode, st->start, st->end, oldBandE,
2514 fine_quant, fine_priority, len*8-ec_tell(dec), dec, C);
2516 if (anti_collapse_on)
2517 anti_collapse(st->mode, X, collapse_masks, LM, C, CC, N,
2518 st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
2520 log2Amp(st->mode, st->start, st->end, bandE, oldBandE, C);
2524 for (i=0;i<C*st->mode->nbEBands;i++)
2527 oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
2531 denormalise_bands(st->mode, X, freq, bandE, effEnd, C, M);
2533 OPUS_MOVE(decode_mem[0], decode_mem[0]+N, DECODE_BUFFER_SIZE-N);
2535 OPUS_MOVE(decode_mem[1], decode_mem[1]+N, DECODE_BUFFER_SIZE-N);
2538 for (i=0;i<M*st->mode->eBands[st->start];i++)
2542 int bound = M*st->mode->eBands[effEnd];
2543 if (st->downsample!=1)
2544 bound = IMIN(bound, N/st->downsample);
2545 for (i=bound;i<N;i++)
2549 out_syn[0] = out_mem[0]+MAX_PERIOD-N;
2551 out_syn[1] = out_mem[1]+MAX_PERIOD-N;
2556 freq[N+i] = freq[i];
2561 freq[i] = HALF32(ADD32(freq[i],freq[N+i]));
2564 /* Compute inverse MDCTs */
2565 compute_inv_mdcts(st->mode, shortBlocks, freq, out_syn, overlap_mem, CC, LM);
2568 st->postfilter_period=IMAX(st->postfilter_period, COMBFILTER_MINPERIOD);
2569 st->postfilter_period_old=IMAX(st->postfilter_period_old, COMBFILTER_MINPERIOD);
2570 comb_filter(out_syn[c], out_syn[c], st->postfilter_period_old, st->postfilter_period, st->mode->shortMdctSize,
2571 st->postfilter_gain_old, st->postfilter_gain, st->postfilter_tapset_old, st->postfilter_tapset,
2572 st->mode->window, st->overlap);
2574 comb_filter(out_syn[c]+st->mode->shortMdctSize, out_syn[c]+st->mode->shortMdctSize, st->postfilter_period, postfilter_pitch, N-st->mode->shortMdctSize,
2575 st->postfilter_gain, postfilter_gain, st->postfilter_tapset, postfilter_tapset,
2576 st->mode->window, st->mode->overlap);
2579 st->postfilter_period_old = st->postfilter_period;
2580 st->postfilter_gain_old = st->postfilter_gain;
2581 st->postfilter_tapset_old = st->postfilter_tapset;
2582 st->postfilter_period = postfilter_pitch;
2583 st->postfilter_gain = postfilter_gain;
2584 st->postfilter_tapset = postfilter_tapset;
2587 st->postfilter_period_old = st->postfilter_period;
2588 st->postfilter_gain_old = st->postfilter_gain;
2589 st->postfilter_tapset_old = st->postfilter_tapset;
2593 for (i=0;i<st->mode->nbEBands;i++)
2594 oldBandE[st->mode->nbEBands+i]=oldBandE[i];
2597 /* In case start or end were to change */
2600 for (i=0;i<st->start;i++)
2601 oldBandE[c*st->mode->nbEBands+i]=0;
2602 for (i=st->end;i<st->mode->nbEBands;i++)
2603 oldBandE[c*st->mode->nbEBands+i]=0;
2607 for (i=0;i<2*st->mode->nbEBands;i++)
2608 oldLogE2[i] = oldLogE[i];
2609 for (i=0;i<2*st->mode->nbEBands;i++)
2610 oldLogE[i] = oldBandE[i];
2611 for (i=0;i<2*st->mode->nbEBands;i++)
2612 backgroundLogE[i] = MIN16(backgroundLogE[i] + M*QCONST16(0.001f,DB_SHIFT), oldBandE[i]);
2614 for (i=0;i<2*st->mode->nbEBands;i++)
2615 oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
2619 deemphasis(out_syn, pcm, N, CC, st->downsample, st->mode->preemph, st->preemph_memD);
2622 if (ec_tell(dec) > 8*len)
2623 return OPUS_INTERNAL_ERROR;
2624 if(ec_get_error(dec))
2626 return frame_size/st->downsample;
2633 int opus_custom_decode(CELTDecoder * restrict st, const unsigned char *data, int len, opus_int16 * restrict pcm, int frame_size)
2635 return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL);
2638 #ifndef DISABLE_FLOAT_API
2639 int opus_custom_decode_float(CELTDecoder * restrict st, const unsigned char *data, int len, float * restrict pcm, int frame_size)
2642 VARDECL(opus_int16, out);
2646 return OPUS_BAD_ARG;
2648 C = CHANNELS(st->channels);
2651 ALLOC(out, C*N, opus_int16);
2652 ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL);
2654 for (j=0;j<C*ret;j++)
2655 pcm[j]=out[j]*(1.f/32768.f);
2660 #endif /* DISABLE_FLOAT_API */
2664 int opus_custom_decode_float(CELTDecoder * restrict st, const unsigned char *data, int len, float * restrict pcm, int frame_size)
2666 return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL);
2669 int opus_custom_decode(CELTDecoder * restrict st, const unsigned char *data, int len, opus_int16 * restrict pcm, int frame_size)
2672 VARDECL(celt_sig, out);
2676 return OPUS_BAD_ARG;
2678 C = CHANNELS(st->channels);
2680 ALLOC(out, C*N, celt_sig);
2682 ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL);
2685 for (j=0;j<C*ret;j++)
2686 pcm[j] = FLOAT2INT16 (out[j]);
2693 #endif /* CUSTOM_MODES */
2695 int opus_custom_decoder_ctl(CELTDecoder * restrict st, int request, ...)
2699 va_start(ap, request);
2702 case CELT_SET_START_BAND_REQUEST:
2704 opus_int32 value = va_arg(ap, opus_int32);
2705 if (value<0 || value>=st->mode->nbEBands)
2710 case CELT_SET_END_BAND_REQUEST:
2712 opus_int32 value = va_arg(ap, opus_int32);
2713 if (value<1 || value>st->mode->nbEBands)
2718 case CELT_SET_CHANNELS_REQUEST:
2720 opus_int32 value = va_arg(ap, opus_int32);
2721 if (value<1 || value>2)
2723 st->stream_channels = value;
2726 case CELT_GET_AND_CLEAR_ERROR_REQUEST:
2728 int *value = va_arg(ap, opus_int32*);
2735 case OPUS_GET_LOOKAHEAD_REQUEST:
2737 int *value = va_arg(ap, opus_int32*);
2740 *value = st->overlap/st->downsample;
2743 case OPUS_RESET_STATE:
2745 OPUS_CLEAR((char*)&st->DECODER_RESET_START,
2746 opus_custom_decoder_get_size(st->mode, st->channels)-
2747 ((char*)&st->DECODER_RESET_START - (char*)st));
2750 case OPUS_GET_PITCH_REQUEST:
2752 int *value = va_arg(ap, opus_int32*);
2755 *value = st->postfilter_period;
2759 case CELT_GET_MODE_REQUEST:
2761 const CELTMode ** value = va_arg(ap, const CELTMode**);
2767 case CELT_SET_SIGNALLING_REQUEST:
2769 opus_int32 value = va_arg(ap, opus_int32);
2770 st->signalling = value;
2773 case OPUS_GET_FINAL_RANGE_REQUEST:
2775 opus_uint32 * value = va_arg(ap, opus_uint32 *);
2789 return OPUS_BAD_ARG;
2792 return OPUS_UNIMPLEMENTED;
2797 const char *opus_strerror(int error)
2799 static const char *error_strings[8] = {
2805 "request not implemented",
2807 "memory allocation failed"
2809 if (error > 0 || error < -7)
2810 return "unknown error";
2812 return error_strings[-error];
2815 const char *opus_get_version_string(void)
2817 return "libopus " OPUS_VERSION