blob: 4303f04fbd5b8a6d7284a77db53b5f76be7c1fd0 [file] [log] [blame]
Jean-Marc Valin69062102012-11-08 09:42:27 -05001/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2010 Xiph.Org Foundation
3 Copyright (c) 2008 Gregory Maxwell
4 Written by Jean-Marc Valin and Gregory Maxwell */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30#ifdef HAVE_CONFIG_H
31#include "config.h"
32#endif
33
34#define CELT_C
35#define DECODER
36
37#include "os_support.h"
38#include "mdct.h"
39#include <math.h>
40#include "celt.h"
41#include "pitch.h"
42#include "bands.h"
43#include "modes.h"
44#include "entcode.h"
45#include "quant_bands.h"
46#include "rate.h"
47#include "stack_alloc.h"
48#include "mathops.h"
49#include "float_cast.h"
50#include <stdarg.h>
51#include "celt_lpc.h"
52#include "vq.h"
53
54/**********************************************************************/
55/* */
56/* DECODER */
57/* */
58/**********************************************************************/
59#define DECODE_BUFFER_SIZE 2048
60
61/** Decoder state
62 @brief Decoder state
63 */
64struct OpusCustomDecoder {
65 const OpusCustomMode *mode;
66 int overlap;
67 int channels;
68 int stream_channels;
69
70 int downsample;
71 int start, end;
72 int signalling;
73
74 /* Everything beyond this point gets cleared on a reset */
75#define DECODER_RESET_START rng
76
77 opus_uint32 rng;
78 int error;
79 int last_pitch_index;
80 int loss_count;
81 int postfilter_period;
82 int postfilter_period_old;
83 opus_val16 postfilter_gain;
84 opus_val16 postfilter_gain_old;
85 int postfilter_tapset;
86 int postfilter_tapset_old;
87
88 celt_sig preemph_memD[2];
89
90 celt_sig _decode_mem[1]; /* Size = channels*(DECODE_BUFFER_SIZE+mode->overlap) */
91 /* opus_val16 lpc[], Size = channels*LPC_ORDER */
92 /* opus_val16 oldEBands[], Size = 2*mode->nbEBands */
93 /* opus_val16 oldLogE[], Size = 2*mode->nbEBands */
94 /* opus_val16 oldLogE2[], Size = 2*mode->nbEBands */
95 /* opus_val16 backgroundLogE[], Size = 2*mode->nbEBands */
96};
97
98int celt_decoder_get_size(int channels)
99{
100 const CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
101 return opus_custom_decoder_get_size(mode, channels);
102}
103
104OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_get_size(const CELTMode *mode, int channels)
105{
106 int size = sizeof(struct CELTDecoder)
107 + (channels*(DECODE_BUFFER_SIZE+mode->overlap)-1)*sizeof(celt_sig)
108 + channels*LPC_ORDER*sizeof(opus_val16)
109 + 4*2*mode->nbEBands*sizeof(opus_val16);
110 return size;
111}
112
113#ifdef CUSTOM_MODES
114CELTDecoder *opus_custom_decoder_create(const CELTMode *mode, int channels, int *error)
115{
116 int ret;
117 CELTDecoder *st = (CELTDecoder *)opus_alloc(opus_custom_decoder_get_size(mode, channels));
118 ret = opus_custom_decoder_init(st, mode, channels);
119 if (ret != OPUS_OK)
120 {
121 opus_custom_decoder_destroy(st);
122 st = NULL;
123 }
124 if (error)
125 *error = ret;
126 return st;
127}
128#endif /* CUSTOM_MODES */
129
130int celt_decoder_init(CELTDecoder *st, opus_int32 sampling_rate, int channels)
131{
132 int ret;
133 ret = opus_custom_decoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
134 if (ret != OPUS_OK)
135 return ret;
136 st->downsample = resampling_factor(sampling_rate);
137 if (st->downsample==0)
138 return OPUS_BAD_ARG;
139 else
140 return OPUS_OK;
141}
142
143OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_init(CELTDecoder *st, const CELTMode *mode, int channels)
144{
145 if (channels < 0 || channels > 2)
146 return OPUS_BAD_ARG;
147
148 if (st==NULL)
149 return OPUS_ALLOC_FAIL;
150
151 OPUS_CLEAR((char*)st, opus_custom_decoder_get_size(mode, channels));
152
153 st->mode = mode;
154 st->overlap = mode->overlap;
155 st->stream_channels = st->channels = channels;
156
157 st->downsample = 1;
158 st->start = 0;
159 st->end = st->mode->effEBands;
160 st->signalling = 1;
161
162 st->loss_count = 0;
163
164 opus_custom_decoder_ctl(st, OPUS_RESET_STATE);
165
166 return OPUS_OK;
167}
168
169#ifdef CUSTOM_MODES
170void opus_custom_decoder_destroy(CELTDecoder *st)
171{
172 opus_free(st);
173}
174#endif /* CUSTOM_MODES */
175
176static inline opus_val16 SIG2WORD16(celt_sig x)
177{
178#ifdef FIXED_POINT
179 x = PSHR32(x, SIG_SHIFT);
180 x = MAX32(x, -32768);
181 x = MIN32(x, 32767);
182 return EXTRACT16(x);
183#else
184 return (opus_val16)x;
185#endif
186}
187
188#ifndef RESYNTH
189static
190#endif
191void deemphasis(celt_sig *in[], opus_val16 *pcm, int N, int C, int downsample, const opus_val16 *coef, celt_sig *mem, celt_sig * OPUS_RESTRICT scratch)
192{
193 int c;
194 int Nd;
195 opus_val16 coef0, coef1;
196
197 coef0 = coef[0];
198 coef1 = coef[1];
199 Nd = N/downsample;
200 c=0; do {
201 int j;
202 celt_sig * OPUS_RESTRICT x;
203 opus_val16 * OPUS_RESTRICT y;
204 celt_sig m = mem[c];
205 x =in[c];
206 y = pcm+c;
207 /* Shortcut for the standard (non-custom modes) case */
208 if (coef1 == 0)
209 {
210 for (j=0;j<N;j++)
211 {
212 celt_sig tmp = x[j] + m;
213 m = MULT16_32_Q15(coef0, tmp);
214 scratch[j] = tmp;
215 }
216 } else {
217 opus_val16 coef3 = coef[3];
218 for (j=0;j<N;j++)
219 {
220 celt_sig tmp = x[j] + m;
221 m = MULT16_32_Q15(coef0, tmp)
222 - MULT16_32_Q15(coef1, x[j]);
223 tmp = SHL32(MULT16_32_Q15(coef3, tmp), 2);
224 scratch[j] = tmp;
225 }
226 }
227 mem[c] = m;
228
229 /* Perform down-sampling */
230 for (j=0;j<Nd;j++)
231 y[j*C] = SCALEOUT(SIG2WORD16(scratch[j*downsample]));
232 } while (++c<C);
233}
234
235/** Compute the IMDCT and apply window for all sub-frames and
236 all channels in a frame */
237#ifndef RESYNTH
238static
239#endif
240void compute_inv_mdcts(const CELTMode *mode, int shortBlocks, celt_sig *X,
241 celt_sig * OPUS_RESTRICT out_mem[], int C, int LM)
242{
243 int b, c;
244 int B;
245 int N;
246 int shift;
247 const int overlap = OVERLAP(mode);
248
249 if (shortBlocks)
250 {
251 B = shortBlocks;
252 N = mode->shortMdctSize;
253 shift = mode->maxLM;
254 } else {
255 B = 1;
256 N = mode->shortMdctSize<<LM;
257 shift = mode->maxLM-LM;
258 }
259 c=0; do {
260 /* IMDCT on the interleaved the sub-frames, overlap-add is performed by the IMDCT */
261 for (b=0;b<B;b++)
262 clt_mdct_backward(&mode->mdct, &X[b+c*N*B], out_mem[c]+N*b, mode->window, overlap, shift, B);
263 } while (++c<C);
264}
265
266static void tf_decode(int start, int end, int isTransient, int *tf_res, int LM, ec_dec *dec)
267{
268 int i, curr, tf_select;
269 int tf_select_rsv;
270 int tf_changed;
271 int logp;
272 opus_uint32 budget;
273 opus_uint32 tell;
274
275 budget = dec->storage*8;
276 tell = ec_tell(dec);
277 logp = isTransient ? 2 : 4;
278 tf_select_rsv = LM>0 && tell+logp+1<=budget;
279 budget -= tf_select_rsv;
280 tf_changed = curr = 0;
281 for (i=start;i<end;i++)
282 {
283 if (tell+logp<=budget)
284 {
285 curr ^= ec_dec_bit_logp(dec, logp);
286 tell = ec_tell(dec);
287 tf_changed |= curr;
288 }
289 tf_res[i] = curr;
290 logp = isTransient ? 4 : 5;
291 }
292 tf_select = 0;
293 if (tf_select_rsv &&
294 tf_select_table[LM][4*isTransient+0+tf_changed] !=
295 tf_select_table[LM][4*isTransient+2+tf_changed])
296 {
297 tf_select = ec_dec_bit_logp(dec, 1);
298 }
299 for (i=start;i<end;i++)
300 {
301 tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
302 }
303}
304
305
306static void celt_decode_lost(CELTDecoder * OPUS_RESTRICT st, opus_val16 * OPUS_RESTRICT pcm, int N, int LM)
307{
308 int c;
309 int pitch_index;
310 opus_val16 fade = Q15ONE;
311 int i, len;
312 const int C = st->channels;
313 int offset;
314 celt_sig *out_mem[2];
315 celt_sig *decode_mem[2];
316 opus_val16 *lpc;
317 opus_val32 *out_syn[2];
318 opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
319 const OpusCustomMode *mode;
320 int nbEBands;
321 int overlap;
322 const opus_int16 *eBands;
323 VARDECL(celt_sig, scratch);
324 SAVE_STACK;
325
326 mode = st->mode;
327 nbEBands = mode->nbEBands;
328 overlap = mode->overlap;
329 eBands = mode->eBands;
330
331 c=0; do {
332 decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+st->overlap);
333 out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
334 } while (++c<C);
335 lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*C);
336 oldBandE = lpc+C*LPC_ORDER;
337 oldLogE = oldBandE + 2*nbEBands;
338 oldLogE2 = oldLogE + 2*nbEBands;
339 backgroundLogE = oldLogE2 + 2*nbEBands;
340
341 c=0; do {
342 out_syn[c] = out_mem[c]+MAX_PERIOD-N;
343 } while (++c<C);
344
345 len = N+overlap;
346
347 if (st->loss_count >= 5 || st->start!=0)
348 {
349 /* Noise-based PLC/CNG */
350 VARDECL(celt_sig, freq);
351 VARDECL(celt_norm, X);
352 VARDECL(celt_ener, bandE);
353 opus_uint32 seed;
354 int effEnd;
355
356 effEnd = st->end;
357 if (effEnd > mode->effEBands)
358 effEnd = mode->effEBands;
359
360 ALLOC(freq, C*N, celt_sig); /**< Interleaved signal MDCTs */
361 ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
362 ALLOC(bandE, nbEBands*C, celt_ener);
363
364 if (st->loss_count >= 5)
365 log2Amp(mode, st->start, st->end, bandE, backgroundLogE, C);
366 else {
367 /* Energy decay */
368 opus_val16 decay = st->loss_count==0 ? QCONST16(1.5f, DB_SHIFT) : QCONST16(.5f, DB_SHIFT);
369 c=0; do
370 {
371 for (i=st->start;i<st->end;i++)
372 oldBandE[c*nbEBands+i] -= decay;
373 } while (++c<C);
374 log2Amp(mode, st->start, st->end, bandE, oldBandE, C);
375 }
376 seed = st->rng;
377 for (c=0;c<C;c++)
378 {
379 for (i=st->start;i<mode->effEBands;i++)
380 {
381 int j;
382 int boffs;
383 int blen;
384 boffs = N*c+(eBands[i]<<LM);
385 blen = (eBands[i+1]-eBands[i])<<LM;
386 for (j=0;j<blen;j++)
387 {
388 seed = celt_lcg_rand(seed);
389 X[boffs+j] = (celt_norm)((opus_int32)seed>>20);
390 }
391 renormalise_vector(X+boffs, blen, Q15ONE);
392 }
393 }
394 st->rng = seed;
395
396 denormalise_bands(mode, X, freq, bandE, st->start, mode->effEBands, C, 1<<LM);
397
398 c=0; do
399 for (i=0;i<eBands[st->start]<<LM;i++)
400 freq[c*N+i] = 0;
401 while (++c<C);
402 c=0; do {
403 int bound = eBands[effEnd]<<LM;
404 if (st->downsample!=1)
405 bound = IMIN(bound, N/st->downsample);
406 for (i=bound;i<N;i++)
407 freq[c*N+i] = 0;
408 } while (++c<C);
409 c=0; do {
410 OPUS_MOVE(decode_mem[c], decode_mem[c]+N, DECODE_BUFFER_SIZE-N+overlap);
411 } while (++c<C);
412 compute_inv_mdcts(mode, 0, freq, out_syn, C, LM);
413 } else {
414 /* Pitch-based PLC */
415 VARDECL(opus_val32, e);
416
417 if (st->loss_count == 0)
418 {
419 opus_val16 pitch_buf[DECODE_BUFFER_SIZE>>1];
420 /* Corresponds to a min pitch of 67 Hz. It's possible to save CPU in this
421 search by using only part of the decode buffer */
422 int poffset = 720;
423 pitch_downsample(decode_mem, pitch_buf, DECODE_BUFFER_SIZE, C);
424 /* Max pitch is 100 samples (480 Hz) */
425 pitch_search(pitch_buf+((poffset)>>1), pitch_buf, DECODE_BUFFER_SIZE-poffset,
426 poffset-100, &pitch_index);
427 pitch_index = poffset-pitch_index;
428 st->last_pitch_index = pitch_index;
429 } else {
430 pitch_index = st->last_pitch_index;
431 fade = QCONST16(.8f,15);
432 }
433
434 ALLOC(e, MAX_PERIOD+2*overlap, opus_val32);
435 c=0; do {
436 opus_val16 exc[MAX_PERIOD];
437 opus_val32 ac[LPC_ORDER+1];
438 opus_val16 decay = 1;
439 opus_val32 S1=0;
440 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};
441
442 offset = MAX_PERIOD-pitch_index;
443 for (i=0;i<MAX_PERIOD;i++)
444 exc[i] = ROUND16(out_mem[c][i], SIG_SHIFT);
445
446 if (st->loss_count == 0)
447 {
448 _celt_autocorr(exc, ac, mode->window, overlap,
449 LPC_ORDER, MAX_PERIOD);
450
451 /* Noise floor -40 dB */
452#ifdef FIXED_POINT
453 ac[0] += SHR32(ac[0],13);
454#else
455 ac[0] *= 1.0001f;
456#endif
457 /* Lag windowing */
458 for (i=1;i<=LPC_ORDER;i++)
459 {
460 /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
461#ifdef FIXED_POINT
462 ac[i] -= MULT16_32_Q15(2*i*i, ac[i]);
463#else
464 ac[i] -= ac[i]*(.008f*i)*(.008f*i);
465#endif
466 }
467
468 _celt_lpc(lpc+c*LPC_ORDER, ac, LPC_ORDER);
469 }
470 for (i=0;i<LPC_ORDER;i++)
471 mem[i] = ROUND16(out_mem[c][MAX_PERIOD-1-i], SIG_SHIFT);
472 celt_fir(exc, lpc+c*LPC_ORDER, exc, MAX_PERIOD, LPC_ORDER, mem);
473 /*for (i=0;i<MAX_PERIOD;i++)printf("%d ", exc[i]); printf("\n");*/
474 /* Check if the waveform is decaying (and if so how fast) */
475 {
476 opus_val32 E1=1, E2=1;
477 int period;
478 if (pitch_index <= MAX_PERIOD/2)
479 period = pitch_index;
480 else
481 period = MAX_PERIOD/2;
482 for (i=0;i<period;i++)
483 {
484 E1 += SHR32(MULT16_16(exc[MAX_PERIOD-period+i],exc[MAX_PERIOD-period+i]),8);
485 E2 += SHR32(MULT16_16(exc[MAX_PERIOD-2*period+i],exc[MAX_PERIOD-2*period+i]),8);
486 }
487 if (E1 > E2)
488 E1 = E2;
489 decay = celt_sqrt(frac_div32(SHR32(E1,1),E2));
490 }
491
492 /* Copy excitation, taking decay into account */
493 for (i=0;i<len+overlap;i++)
494 {
495 opus_val16 tmp;
496 if (offset+i >= MAX_PERIOD)
497 {
498 offset -= pitch_index;
499 decay = MULT16_16_Q15(decay, decay);
500 }
501 e[i] = SHL32(EXTEND32(MULT16_16_Q15(decay, exc[offset+i])), SIG_SHIFT);
502 tmp = ROUND16(out_mem[c][offset+i],SIG_SHIFT);
503 S1 += SHR32(MULT16_16(tmp,tmp),8);
504 }
505 for (i=0;i<LPC_ORDER;i++)
506 mem[i] = ROUND16(out_mem[c][MAX_PERIOD-1-i], SIG_SHIFT);
507 for (i=0;i<len+overlap;i++)
508 e[i] = MULT16_32_Q15(fade, e[i]);
509 celt_iir(e, lpc+c*LPC_ORDER, e, len+overlap, LPC_ORDER, mem);
510
511 {
512 opus_val32 S2=0;
513 for (i=0;i<len+overlap;i++)
514 {
515 opus_val16 tmp = ROUND16(e[i],SIG_SHIFT);
516 S2 += SHR32(MULT16_16(tmp,tmp),8);
517 }
518 /* This checks for an "explosion" in the synthesis */
519#ifdef FIXED_POINT
520 if (!(S1 > SHR32(S2,2)))
521#else
522 /* Float test is written this way to catch NaNs at the same time */
523 if (!(S1 > 0.2f*S2))
524#endif
525 {
526 for (i=0;i<len+overlap;i++)
527 e[i] = 0;
528 } else if (S1 < S2)
529 {
530 opus_val16 ratio = celt_sqrt(frac_div32(SHR32(S1,1)+1,S2+1));
531 for (i=0;i<len+overlap;i++)
532 e[i] = MULT16_32_Q15(ratio, e[i]);
533 }
534 }
535
536 /* Apply post-filter to the MDCT overlap of the previous frame */
537 comb_filter(out_mem[c]+MAX_PERIOD, out_mem[c]+MAX_PERIOD, st->postfilter_period, st->postfilter_period, st->overlap,
538 st->postfilter_gain, st->postfilter_gain, st->postfilter_tapset, st->postfilter_tapset,
539 NULL, 0);
540
541 for (i=0;i<MAX_PERIOD+overlap-N;i++)
542 out_mem[c][i] = out_mem[c][N+i];
543
544 /* Apply TDAC to the concealed audio so that it blends with the
545 previous and next frames */
546 for (i=0;i<overlap/2;i++)
547 {
548 opus_val32 tmp;
549 tmp = MULT16_32_Q15(mode->window[i], e[N+overlap-1-i]) +
550 MULT16_32_Q15(mode->window[overlap-i-1], e[N+i ]);
551 out_mem[c][MAX_PERIOD+i] = MULT16_32_Q15(mode->window[overlap-i-1], tmp);
552 out_mem[c][MAX_PERIOD+overlap-i-1] = MULT16_32_Q15(mode->window[i], tmp);
553 }
554 for (i=0;i<N;i++)
555 out_mem[c][MAX_PERIOD-N+i] = e[i];
556
557 /* Apply pre-filter to the MDCT overlap for the next frame (post-filter will be applied then) */
558 comb_filter(e, out_mem[c]+MAX_PERIOD, st->postfilter_period, st->postfilter_period, st->overlap,
559 -st->postfilter_gain, -st->postfilter_gain, st->postfilter_tapset, st->postfilter_tapset,
560 NULL, 0);
561 for (i=0;i<overlap;i++)
562 out_mem[c][MAX_PERIOD+i] = e[i];
563 } while (++c<C);
564 }
565
566 ALLOC(scratch, N, celt_sig);
567 deemphasis(out_syn, pcm, N, C, st->downsample, mode->preemph, st->preemph_memD, scratch);
568
569 st->loss_count++;
570
571 RESTORE_STACK;
572}
573
574int celt_decode_with_ec(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_val16 * OPUS_RESTRICT pcm, int frame_size, ec_dec *dec)
575{
576 int c, i, N;
577 int spread_decision;
578 opus_int32 bits;
579 ec_dec _dec;
580 VARDECL(celt_sig, freq);
581 VARDECL(celt_norm, X);
582 VARDECL(celt_ener, bandE);
583 VARDECL(int, fine_quant);
584 VARDECL(int, pulses);
585 VARDECL(int, cap);
586 VARDECL(int, offsets);
587 VARDECL(int, fine_priority);
588 VARDECL(int, tf_res);
589 VARDECL(unsigned char, collapse_masks);
590 celt_sig *out_mem[2];
591 celt_sig *decode_mem[2];
592 celt_sig *out_syn[2];
593 opus_val16 *lpc;
594 opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
595
596 int shortBlocks;
597 int isTransient;
598 int intra_ener;
599 const int CC = st->channels;
600 int LM, M;
601 int effEnd;
602 int codedBands;
603 int alloc_trim;
604 int postfilter_pitch;
605 opus_val16 postfilter_gain;
606 int intensity=0;
607 int dual_stereo=0;
608 opus_int32 total_bits;
609 opus_int32 balance;
610 opus_int32 tell;
611 int dynalloc_logp;
612 int postfilter_tapset;
613 int anti_collapse_rsv;
614 int anti_collapse_on=0;
615 int silence;
616 int C = st->stream_channels;
617 const OpusCustomMode *mode;
618 int nbEBands;
619 int overlap;
620 const opus_int16 *eBands;
621 ALLOC_STACK;
622
623 mode = st->mode;
624 nbEBands = mode->nbEBands;
625 overlap = mode->overlap;
626 eBands = mode->eBands;
627 frame_size *= st->downsample;
628
629 c=0; do {
630 decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+overlap);
631 out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
632 } while (++c<CC);
633 lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+overlap)*CC);
634 oldBandE = lpc+CC*LPC_ORDER;
635 oldLogE = oldBandE + 2*nbEBands;
636 oldLogE2 = oldLogE + 2*nbEBands;
637 backgroundLogE = oldLogE2 + 2*nbEBands;
638
639#ifdef CUSTOM_MODES
640 if (st->signalling && data!=NULL)
641 {
642 int data0=data[0];
643 /* Convert "standard mode" to Opus header */
644 if (mode->Fs==48000 && mode->shortMdctSize==120)
645 {
646 data0 = fromOpus(data0);
647 if (data0<0)
648 return OPUS_INVALID_PACKET;
649 }
650 st->end = IMAX(1, mode->effEBands-2*(data0>>5));
651 LM = (data0>>3)&0x3;
652 C = 1 + ((data0>>2)&0x1);
653 data++;
654 len--;
655 if (LM>mode->maxLM)
656 return OPUS_INVALID_PACKET;
657 if (frame_size < mode->shortMdctSize<<LM)
658 return OPUS_BUFFER_TOO_SMALL;
659 else
660 frame_size = mode->shortMdctSize<<LM;
661 } else {
662#else
663 {
664#endif
665 for (LM=0;LM<=mode->maxLM;LM++)
666 if (mode->shortMdctSize<<LM==frame_size)
667 break;
668 if (LM>mode->maxLM)
669 return OPUS_BAD_ARG;
670 }
671 M=1<<LM;
672
673 if (len<0 || len>1275 || pcm==NULL)
674 return OPUS_BAD_ARG;
675
676 N = M*mode->shortMdctSize;
677
678 effEnd = st->end;
679 if (effEnd > mode->effEBands)
680 effEnd = mode->effEBands;
681
682 if (data == NULL || len<=1)
683 {
684 celt_decode_lost(st, pcm, N, LM);
685 RESTORE_STACK;
686 return frame_size/st->downsample;
687 }
688
689 if (dec == NULL)
690 {
691 ec_dec_init(&_dec,(unsigned char*)data,len);
692 dec = &_dec;
693 }
694
695 if (C==1)
696 {
697 for (i=0;i<nbEBands;i++)
698 oldBandE[i]=MAX16(oldBandE[i],oldBandE[nbEBands+i]);
699 }
700
701 total_bits = len*8;
702 tell = ec_tell(dec);
703
704 if (tell >= total_bits)
705 silence = 1;
706 else if (tell==1)
707 silence = ec_dec_bit_logp(dec, 15);
708 else
709 silence = 0;
710 if (silence)
711 {
712 /* Pretend we've read all the remaining bits */
713 tell = len*8;
714 dec->nbits_total+=tell-ec_tell(dec);
715 }
716
717 postfilter_gain = 0;
718 postfilter_pitch = 0;
719 postfilter_tapset = 0;
720 if (st->start==0 && tell+16 <= total_bits)
721 {
722 if(ec_dec_bit_logp(dec, 1))
723 {
724 int qg, octave;
725 octave = ec_dec_uint(dec, 6);
726 postfilter_pitch = (16<<octave)+ec_dec_bits(dec, 4+octave)-1;
727 qg = ec_dec_bits(dec, 3);
728 if (ec_tell(dec)+2<=total_bits)
729 postfilter_tapset = ec_dec_icdf(dec, tapset_icdf, 2);
730 postfilter_gain = QCONST16(.09375f,15)*(qg+1);
731 }
732 tell = ec_tell(dec);
733 }
734
735 if (LM > 0 && tell+3 <= total_bits)
736 {
737 isTransient = ec_dec_bit_logp(dec, 3);
738 tell = ec_tell(dec);
739 }
740 else
741 isTransient = 0;
742
743 if (isTransient)
744 shortBlocks = M;
745 else
746 shortBlocks = 0;
747
748 /* Decode the global flags (first symbols in the stream) */
749 intra_ener = tell+3<=total_bits ? ec_dec_bit_logp(dec, 3) : 0;
750 /* Get band energies */
751 unquant_coarse_energy(mode, st->start, st->end, oldBandE,
752 intra_ener, dec, C, LM);
753
754 ALLOC(tf_res, nbEBands, int);
755 tf_decode(st->start, st->end, isTransient, tf_res, LM, dec);
756
757 tell = ec_tell(dec);
758 spread_decision = SPREAD_NORMAL;
759 if (tell+4 <= total_bits)
760 spread_decision = ec_dec_icdf(dec, spread_icdf, 5);
761
762 ALLOC(cap, nbEBands, int);
763
764 init_caps(mode,cap,LM,C);
765
766 ALLOC(offsets, nbEBands, int);
767
768 dynalloc_logp = 6;
769 total_bits<<=BITRES;
770 tell = ec_tell_frac(dec);
771 for (i=st->start;i<st->end;i++)
772 {
773 int width, quanta;
774 int dynalloc_loop_logp;
775 int boost;
776 width = C*(eBands[i+1]-eBands[i])<<LM;
777 /* quanta is 6 bits, but no more than 1 bit/sample
778 and no less than 1/8 bit/sample */
779 quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
780 dynalloc_loop_logp = dynalloc_logp;
781 boost = 0;
782 while (tell+(dynalloc_loop_logp<<BITRES) < total_bits && boost < cap[i])
783 {
784 int flag;
785 flag = ec_dec_bit_logp(dec, dynalloc_loop_logp);
786 tell = ec_tell_frac(dec);
787 if (!flag)
788 break;
789 boost += quanta;
790 total_bits -= quanta;
791 dynalloc_loop_logp = 1;
792 }
793 offsets[i] = boost;
794 /* Making dynalloc more likely */
795 if (boost>0)
796 dynalloc_logp = IMAX(2, dynalloc_logp-1);
797 }
798
799 ALLOC(fine_quant, nbEBands, int);
800 alloc_trim = tell+(6<<BITRES) <= total_bits ?
801 ec_dec_icdf(dec, trim_icdf, 7) : 5;
802
803 bits = (((opus_int32)len*8)<<BITRES) - ec_tell_frac(dec) - 1;
804 anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
805 bits -= anti_collapse_rsv;
806
807 ALLOC(pulses, nbEBands, int);
808 ALLOC(fine_priority, nbEBands, int);
809
810 codedBands = compute_allocation(mode, st->start, st->end, offsets, cap,
811 alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
812 fine_quant, fine_priority, C, LM, dec, 0, 0);
813
814 unquant_fine_energy(mode, st->start, st->end, oldBandE, fine_quant, dec, C);
815
816 /* Decode fixed codebook */
817 ALLOC(collapse_masks, C*nbEBands, unsigned char);
818 ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
819
820 quant_all_bands(0, mode, st->start, st->end, X, C==2 ? X+N : NULL, collapse_masks,
821 NULL, pulses, shortBlocks, spread_decision, dual_stereo, intensity, tf_res,
822 len*(8<<BITRES)-anti_collapse_rsv, balance, dec, LM, codedBands, &st->rng);
823
824 if (anti_collapse_rsv > 0)
825 {
826 anti_collapse_on = ec_dec_bits(dec, 1);
827 }
828
829 unquant_energy_finalise(mode, st->start, st->end, oldBandE,
830 fine_quant, fine_priority, len*8-ec_tell(dec), dec, C);
831
832 if (anti_collapse_on)
833 anti_collapse(mode, X, collapse_masks, LM, C, N,
834 st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
835
836 ALLOC(bandE, nbEBands*C, celt_ener);
837
838 log2Amp(mode, st->start, st->end, bandE, oldBandE, C);
839
840 if (silence)
841 {
842 for (i=0;i<C*nbEBands;i++)
843 {
844 bandE[i] = 0;
845 oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
846 }
847 }
848 ALLOC(freq, IMAX(CC,C)*N, celt_sig); /**< Interleaved signal MDCTs */
849 /* Synthesis */
850 denormalise_bands(mode, X, freq, bandE, st->start, effEnd, C, M);
851
852 c=0; do {
853 OPUS_MOVE(decode_mem[c], decode_mem[c]+N, DECODE_BUFFER_SIZE-N+overlap);
854 } while (++c<CC);
855
856 c=0; do
857 for (i=0;i<M*eBands[st->start];i++)
858 freq[c*N+i] = 0;
859 while (++c<C);
860 c=0; do {
861 int bound = M*eBands[effEnd];
862 if (st->downsample!=1)
863 bound = IMIN(bound, N/st->downsample);
864 for (i=bound;i<N;i++)
865 freq[c*N+i] = 0;
866 } while (++c<C);
867
868 c=0; do {
869 out_syn[c] = out_mem[c]+MAX_PERIOD-N;
870 } while (++c<CC);
871
872 if (CC==2&&C==1)
873 {
874 for (i=0;i<N;i++)
875 freq[N+i] = freq[i];
876 }
877 if (CC==1&&C==2)
878 {
879 for (i=0;i<N;i++)
880 freq[i] = HALF32(ADD32(freq[i],freq[N+i]));
881 }
882
883 /* Compute inverse MDCTs */
884 compute_inv_mdcts(mode, shortBlocks, freq, out_syn, CC, LM);
885
886 c=0; do {
887 st->postfilter_period=IMAX(st->postfilter_period, COMBFILTER_MINPERIOD);
888 st->postfilter_period_old=IMAX(st->postfilter_period_old, COMBFILTER_MINPERIOD);
889 comb_filter(out_syn[c], out_syn[c], st->postfilter_period_old, st->postfilter_period, mode->shortMdctSize,
890 st->postfilter_gain_old, st->postfilter_gain, st->postfilter_tapset_old, st->postfilter_tapset,
891 mode->window, overlap);
892 if (LM!=0)
893 comb_filter(out_syn[c]+mode->shortMdctSize, out_syn[c]+mode->shortMdctSize, st->postfilter_period, postfilter_pitch, N-mode->shortMdctSize,
894 st->postfilter_gain, postfilter_gain, st->postfilter_tapset, postfilter_tapset,
895 mode->window, overlap);
896
897 } while (++c<CC);
898 st->postfilter_period_old = st->postfilter_period;
899 st->postfilter_gain_old = st->postfilter_gain;
900 st->postfilter_tapset_old = st->postfilter_tapset;
901 st->postfilter_period = postfilter_pitch;
902 st->postfilter_gain = postfilter_gain;
903 st->postfilter_tapset = postfilter_tapset;
904 if (LM!=0)
905 {
906 st->postfilter_period_old = st->postfilter_period;
907 st->postfilter_gain_old = st->postfilter_gain;
908 st->postfilter_tapset_old = st->postfilter_tapset;
909 }
910
911 if (C==1) {
912 for (i=0;i<nbEBands;i++)
913 oldBandE[nbEBands+i]=oldBandE[i];
914 }
915
916 /* In case start or end were to change */
917 if (!isTransient)
918 {
919 for (i=0;i<2*nbEBands;i++)
920 oldLogE2[i] = oldLogE[i];
921 for (i=0;i<2*nbEBands;i++)
922 oldLogE[i] = oldBandE[i];
923 for (i=0;i<2*nbEBands;i++)
924 backgroundLogE[i] = MIN16(backgroundLogE[i] + M*QCONST16(0.001f,DB_SHIFT), oldBandE[i]);
925 } else {
926 for (i=0;i<2*nbEBands;i++)
927 oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
928 }
929 c=0; do
930 {
931 for (i=0;i<st->start;i++)
932 {
933 oldBandE[c*nbEBands+i]=0;
934 oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
935 }
936 for (i=st->end;i<nbEBands;i++)
937 {
938 oldBandE[c*nbEBands+i]=0;
939 oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
940 }
941 } while (++c<2);
942 st->rng = dec->rng;
943
944 /* We reuse freq[] as scratch space for the de-emphasis */
945 deemphasis(out_syn, pcm, N, CC, st->downsample, mode->preemph, st->preemph_memD, freq);
946 st->loss_count = 0;
947 RESTORE_STACK;
948 if (ec_tell(dec) > 8*len)
949 return OPUS_INTERNAL_ERROR;
950 if(ec_get_error(dec))
951 st->error = 1;
952 return frame_size/st->downsample;
953}
954
955
956#ifdef CUSTOM_MODES
957
958#ifdef FIXED_POINT
959int opus_custom_decode(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int16 * OPUS_RESTRICT pcm, int frame_size)
960{
961 return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL);
962}
963
964#ifndef DISABLE_FLOAT_API
965int opus_custom_decode_float(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, float * OPUS_RESTRICT pcm, int frame_size)
966{
967 int j, ret, C, N;
968 VARDECL(opus_int16, out);
969 ALLOC_STACK;
970
971 if (pcm==NULL)
972 return OPUS_BAD_ARG;
973
974 C = st->channels;
975 N = frame_size;
976
977 ALLOC(out, C*N, opus_int16);
978 ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL);
979 if (ret>0)
980 for (j=0;j<C*ret;j++)
981 pcm[j]=out[j]*(1.f/32768.f);
982
983 RESTORE_STACK;
984 return ret;
985}
986#endif /* DISABLE_FLOAT_API */
987
988#else
989
990int opus_custom_decode_float(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, float * OPUS_RESTRICT pcm, int frame_size)
991{
992 return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL);
993}
994
995int opus_custom_decode(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int16 * OPUS_RESTRICT pcm, int frame_size)
996{
997 int j, ret, C, N;
998 VARDECL(celt_sig, out);
999 ALLOC_STACK;
1000
1001 if (pcm==NULL)
1002 return OPUS_BAD_ARG;
1003
1004 C = st->channels;
1005 N = frame_size;
1006 ALLOC(out, C*N, celt_sig);
1007
1008 ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL);
1009
1010 if (ret>0)
1011 for (j=0;j<C*ret;j++)
1012 pcm[j] = FLOAT2INT16 (out[j]);
1013
1014 RESTORE_STACK;
1015 return ret;
1016}
1017
1018#endif
1019#endif /* CUSTOM_MODES */
1020
1021int opus_custom_decoder_ctl(CELTDecoder * OPUS_RESTRICT st, int request, ...)
1022{
1023 va_list ap;
1024
1025 va_start(ap, request);
1026 switch (request)
1027 {
1028 case CELT_SET_START_BAND_REQUEST:
1029 {
1030 opus_int32 value = va_arg(ap, opus_int32);
1031 if (value<0 || value>=st->mode->nbEBands)
1032 goto bad_arg;
1033 st->start = value;
1034 }
1035 break;
1036 case CELT_SET_END_BAND_REQUEST:
1037 {
1038 opus_int32 value = va_arg(ap, opus_int32);
1039 if (value<1 || value>st->mode->nbEBands)
1040 goto bad_arg;
1041 st->end = value;
1042 }
1043 break;
1044 case CELT_SET_CHANNELS_REQUEST:
1045 {
1046 opus_int32 value = va_arg(ap, opus_int32);
1047 if (value<1 || value>2)
1048 goto bad_arg;
1049 st->stream_channels = value;
1050 }
1051 break;
1052 case CELT_GET_AND_CLEAR_ERROR_REQUEST:
1053 {
1054 opus_int32 *value = va_arg(ap, opus_int32*);
1055 if (value==NULL)
1056 goto bad_arg;
1057 *value=st->error;
1058 st->error = 0;
1059 }
1060 break;
1061 case OPUS_GET_LOOKAHEAD_REQUEST:
1062 {
1063 opus_int32 *value = va_arg(ap, opus_int32*);
1064 if (value==NULL)
1065 goto bad_arg;
1066 *value = st->overlap/st->downsample;
1067 }
1068 break;
1069 case OPUS_RESET_STATE:
1070 {
1071 int i;
1072 opus_val16 *lpc, *oldBandE, *oldLogE, *oldLogE2;
1073 lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*st->channels);
1074 oldBandE = lpc+st->channels*LPC_ORDER;
1075 oldLogE = oldBandE + 2*st->mode->nbEBands;
1076 oldLogE2 = oldLogE + 2*st->mode->nbEBands;
1077 OPUS_CLEAR((char*)&st->DECODER_RESET_START,
1078 opus_custom_decoder_get_size(st->mode, st->channels)-
1079 ((char*)&st->DECODER_RESET_START - (char*)st));
1080 for (i=0;i<2*st->mode->nbEBands;i++)
1081 oldLogE[i]=oldLogE2[i]=-QCONST16(28.f,DB_SHIFT);
1082 }
1083 break;
1084 case OPUS_GET_PITCH_REQUEST:
1085 {
1086 opus_int32 *value = va_arg(ap, opus_int32*);
1087 if (value==NULL)
1088 goto bad_arg;
1089 *value = st->postfilter_period;
1090 }
1091 break;
1092#ifdef OPUS_BUILD
1093 case CELT_GET_MODE_REQUEST:
1094 {
1095 const CELTMode ** value = va_arg(ap, const CELTMode**);
1096 if (value==0)
1097 goto bad_arg;
1098 *value=st->mode;
1099 }
1100 break;
1101 case CELT_SET_SIGNALLING_REQUEST:
1102 {
1103 opus_int32 value = va_arg(ap, opus_int32);
1104 st->signalling = value;
1105 }
1106 break;
1107 case OPUS_GET_FINAL_RANGE_REQUEST:
1108 {
1109 opus_uint32 * value = va_arg(ap, opus_uint32 *);
1110 if (value==0)
1111 goto bad_arg;
1112 *value=st->rng;
1113 }
1114 break;
1115#endif
1116 default:
1117 goto bad_request;
1118 }
1119 va_end(ap);
1120 return OPUS_OK;
1121bad_arg:
1122 va_end(ap);
1123 return OPUS_BAD_ARG;
1124bad_request:
1125 va_end(ap);
1126 return OPUS_UNIMPLEMENTED;
1127}