Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / webrtc / modules / audio_coding / codecs / isac / main / source / isac.c
1 /*
2  *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 /*
12  * isac.c
13  *
14  * This C file contains the functions for the ISAC API
15  *
16  */
17
18 #include "webrtc/modules/audio_coding/codecs/isac/main/interface/isac.h"
19
20 #include <math.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
26 #include "webrtc/modules/audio_coding/codecs/isac/main/source/bandwidth_estimator.h"
27 #include "webrtc/modules/audio_coding/codecs/isac/main/source/codec.h"
28 #include "webrtc/modules/audio_coding/codecs/isac/main/source/crc.h"
29 #include "webrtc/modules/audio_coding/codecs/isac/main/source/entropy_coding.h"
30 #include "webrtc/modules/audio_coding/codecs/isac/main/source/lpc_shape_swb16_tables.h"
31 #include "webrtc/modules/audio_coding/codecs/isac/main/source/os_specific_inline.h"
32 #include "webrtc/modules/audio_coding/codecs/isac/main/source/structs.h"
33
34 #define BIT_MASK_DEC_INIT 0x0001
35 #define BIT_MASK_ENC_INIT 0x0002
36
37 #define LEN_CHECK_SUM_WORD8     4
38 #define MAX_NUM_LAYERS         10
39
40
41 /****************************************************************************
42  * UpdatePayloadSizeLimit(...)
43  *
44  * Call this function to update the limit on the payload size. The limit on
45  * payload size might change i) if a user ''directly changes the limit by
46  * calling xxx_setMaxPayloadSize() or xxx_setMaxRate(), or ii) indirectly
47  * when bandwidth is changing. The latter might be the result of bandwidth
48  * adaptation, or direct change of the bottleneck in instantaneous mode.
49  *
50  * This function takes the current overall limit on payload, and translates it
51  * to the limits on lower and upper-band. If the codec is in wideband mode,
52  * then the overall limit and the limit on the lower-band is the same.
53  * Otherwise, a fraction of the limit should be allocated to lower-band
54  * leaving some room for the upper-band bit-stream. That is why an update
55  * of limit is required every time that the bandwidth is changing.
56  *
57  */
58 static void UpdatePayloadSizeLimit(ISACMainStruct* instISAC) {
59   int16_t lim30MsPayloadBytes = WEBRTC_SPL_MIN(
60                           (instISAC->maxPayloadSizeBytes),
61                           (instISAC->maxRateBytesPer30Ms));
62   int16_t lim60MsPayloadBytes = WEBRTC_SPL_MIN(
63                           (instISAC->maxPayloadSizeBytes),
64                           (instISAC->maxRateBytesPer30Ms << 1));
65
66   /* The only time that iSAC will have 60 ms
67    * frame-size is when operating in wideband, so
68    * there is no upper-band bit-stream. */
69
70   if (instISAC->bandwidthKHz == isac8kHz) {
71     /* At 8 kHz there is no upper-band bit-stream,
72      * therefore, the lower-band limit is the overall limit. */
73     instISAC->instLB.ISACencLB_obj.payloadLimitBytes60 =
74       lim60MsPayloadBytes;
75     instISAC->instLB.ISACencLB_obj.payloadLimitBytes30 =
76       lim30MsPayloadBytes;
77   } else {
78     /* When in super-wideband, we only have 30 ms frames.
79      * Do a rate allocation for the given limit. */
80     if (lim30MsPayloadBytes > 250) {
81       /* 4/5 to lower-band the rest for upper-band. */
82       instISAC->instLB.ISACencLB_obj.payloadLimitBytes30 =
83         (lim30MsPayloadBytes << 2) / 5;
84     } else if (lim30MsPayloadBytes > 200) {
85       /* For the interval of 200 to 250 the share of
86        * upper-band linearly grows from 20 to 50. */
87       instISAC->instLB.ISACencLB_obj.payloadLimitBytes30 =
88         (lim30MsPayloadBytes << 1) / 5 + 100;
89     } else {
90       /* Allocate only 20 for upper-band. */
91       instISAC->instLB.ISACencLB_obj.payloadLimitBytes30 =
92         lim30MsPayloadBytes - 20;
93     }
94     instISAC->instUB.ISACencUB_obj.maxPayloadSizeBytes =
95       lim30MsPayloadBytes;
96   }
97 }
98
99
100 /****************************************************************************
101  * UpdateBottleneck(...)
102  *
103  * This function updates the bottleneck only if the codec is operating in
104  * channel-adaptive mode. Furthermore, as the update of bottleneck might
105  * result in an update of bandwidth, therefore, the bottlenech should be
106  * updated just right before the first 10ms of a frame is pushed into encoder.
107  *
108  */
109 static void UpdateBottleneck(ISACMainStruct* instISAC) {
110   /* Read the bottleneck from bandwidth estimator for the
111    * first 10 ms audio. This way, if there is a change
112    * in bandwidth, upper and lower-band will be in sync. */
113   if ((instISAC->codingMode == 0) &&
114       (instISAC->instLB.ISACencLB_obj.buffer_index == 0) &&
115       (instISAC->instLB.ISACencLB_obj.frame_nb == 0)) {
116     int32_t bottleneck;
117     WebRtcIsac_GetUplinkBandwidth(&(instISAC->bwestimator_obj),
118                                   &bottleneck);
119
120     /* Adding hysteresis when increasing signal bandwidth. */
121     if ((instISAC->bandwidthKHz == isac8kHz)
122         && (bottleneck > 37000)
123         && (bottleneck < 41000)) {
124       bottleneck = 37000;
125     }
126
127     /* Switching from 12 kHz to 16 kHz is not allowed at this revision.
128      * If we let this happen, we have to take care of buffer_index and
129      * the last LPC vector. */
130     if ((instISAC->bandwidthKHz != isac16kHz) &&
131         (bottleneck > 46000)) {
132       bottleneck = 46000;
133     }
134
135     /* We might need a rate allocation. */
136     if (instISAC->encoderSamplingRateKHz == kIsacWideband) {
137       /* Wideband is the only choice we have here. */
138       instISAC->instLB.ISACencLB_obj.bottleneck =
139         (bottleneck > 32000) ? 32000 : bottleneck;
140       instISAC->bandwidthKHz = isac8kHz;
141     } else {
142       /* Do the rate-allocation and get the new bandwidth. */
143       enum ISACBandwidth bandwidth;
144       WebRtcIsac_RateAllocation(bottleneck,
145                                 &(instISAC->instLB.ISACencLB_obj.bottleneck),
146                                 &(instISAC->instUB.ISACencUB_obj.bottleneck),
147                                 &bandwidth);
148       if (bandwidth != isac8kHz) {
149         instISAC->instLB.ISACencLB_obj.new_framelength = 480;
150       }
151       if (bandwidth != instISAC->bandwidthKHz) {
152         /* Bandwidth is changing. */
153         instISAC->bandwidthKHz = bandwidth;
154         UpdatePayloadSizeLimit(instISAC);
155         if (bandwidth == isac12kHz) {
156           instISAC->instLB.ISACencLB_obj.buffer_index = 0;
157         }
158         /* Currently we don't let the bandwidth to switch to 16 kHz
159          * if in adaptive mode. If we let this happen, we have to take
160          * care of buffer_index and the last LPC vector. */
161       }
162     }
163   }
164 }
165
166
167 /****************************************************************************
168  * GetSendBandwidthInfo(...)
169  *
170  * This is called to get the bandwidth info. This info is the bandwidth and
171  * the jitter of 'there-to-here' channel, estimated 'here.' These info
172  * is signaled in an in-band fashion to the other side.
173  *
174  * The call to the bandwidth estimator triggers a recursive averaging which
175  * has to be synchronized between encoder & decoder, therefore, the call to
176  * BWE should be once per packet. As the BWE info is inserted into bit-stream
177  * We need a valid info right before the encodeLB function is going to
178  * generate a bit-stream. That is when lower-band buffer has already 20ms
179  * of audio, and the 3rd block of 10ms is going to be injected into encoder.
180  *
181  * Inputs:
182  *         - instISAC          : iSAC instance.
183  *
184  * Outputs:
185  *         - bandwidthIndex    : an index which has to be encoded in
186  *                               lower-band bit-stream, indicating the
187  *                               bandwidth of there-to-here channel.
188  *         - jitterInfo        : this indicates if the jitter is high
189  *                               or low and it is encoded in upper-band
190  *                               bit-stream.
191  *
192  */
193 static void GetSendBandwidthInfo(ISACMainStruct* instISAC,
194                                  int16_t* bandwidthIndex,
195                                  int16_t* jitterInfo) {
196   if ((instISAC->instLB.ISACencLB_obj.buffer_index ==
197       (FRAMESAMPLES_10ms << 1)) &&
198       (instISAC->instLB.ISACencLB_obj.frame_nb == 0)) {
199     /* Bandwidth estimation and coding. */
200     WebRtcIsac_GetDownlinkBwJitIndexImpl(&(instISAC->bwestimator_obj),
201                                          bandwidthIndex, jitterInfo,
202                                          instISAC->decoderSamplingRateKHz);
203   }
204 }
205
206
207 /****************************************************************************
208  * WebRtcIsac_AssignSize(...)
209  *
210  * This function returns the size of the ISAC instance, so that the instance
211  * can be created out side iSAC.
212  *
213  * Output:
214  *        - sizeinbytes       : number of bytes needed to allocate for the
215  *                              instance.
216  *
217  * Return value               : 0 - Ok
218  *                             -1 - Error
219  */
220 int16_t WebRtcIsac_AssignSize(int* sizeInBytes) {
221   *sizeInBytes = sizeof(ISACMainStruct) * 2 / sizeof(int16_t);
222   return 0;
223 }
224
225
226 /****************************************************************************
227  * WebRtcIsac_Assign(...)
228  *
229  * This function assigns the memory already created to the ISAC instance.
230  *
231  * Input:
232  *        - ISAC_main_inst    : address of the pointer to the coder instance.
233  *        - instISAC_Addr     : the already allocated memory, where we put the
234  *                              iSAC structure.
235  *
236  * Return value               : 0 - Ok
237  *                             -1 - Error
238  */
239 int16_t WebRtcIsac_Assign(ISACStruct** ISAC_main_inst,
240                           void* instISAC_Addr) {
241   if (instISAC_Addr != NULL) {
242     ISACMainStruct* instISAC = (ISACMainStruct*)instISAC_Addr;
243     instISAC->errorCode = 0;
244     instISAC->initFlag = 0;
245
246     /* Assign the address. */
247     *ISAC_main_inst = (ISACStruct*)instISAC_Addr;
248
249     /* Default is wideband. */
250     instISAC->encoderSamplingRateKHz = kIsacWideband;
251     instISAC->decoderSamplingRateKHz = kIsacWideband;
252     instISAC->bandwidthKHz           = isac8kHz;
253     instISAC->in_sample_rate_hz = 16000;
254     return 0;
255   } else {
256     return -1;
257   }
258 }
259
260
261 /****************************************************************************
262  * WebRtcIsac_Create(...)
263  *
264  * This function creates an ISAC instance, which will contain the state
265  * information for one coding/decoding channel.
266  *
267  * Input:
268  *        - ISAC_main_inst    : address of the pointer to the coder instance.
269  *
270  * Return value               : 0 - Ok
271  *                             -1 - Error
272  */
273 int16_t WebRtcIsac_Create(ISACStruct** ISAC_main_inst) {
274   ISACMainStruct* instISAC;
275
276   if (ISAC_main_inst != NULL) {
277     instISAC = (ISACMainStruct*)malloc(sizeof(ISACMainStruct));
278     *ISAC_main_inst = (ISACStruct*)instISAC;
279     if (*ISAC_main_inst != NULL) {
280       instISAC->errorCode = 0;
281       instISAC->initFlag = 0;
282       /* Default is wideband. */
283       instISAC->bandwidthKHz = isac8kHz;
284       instISAC->encoderSamplingRateKHz = kIsacWideband;
285       instISAC->decoderSamplingRateKHz = kIsacWideband;
286       instISAC->in_sample_rate_hz = 16000;
287       return 0;
288     } else {
289       return -1;
290     }
291   } else {
292     return -1;
293   }
294 }
295
296
297 /****************************************************************************
298  * WebRtcIsac_Free(...)
299  *
300  * This function frees the ISAC instance created at the beginning.
301  *
302  * Input:
303  *        - ISAC_main_inst    : a ISAC instance.
304  *
305  * Return value               : 0 - Ok
306  *                             -1 - Error
307  */
308 int16_t WebRtcIsac_Free(ISACStruct* ISAC_main_inst) {
309   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
310   free(instISAC);
311   return 0;
312 }
313
314
315 /****************************************************************************
316  * EncoderInitLb(...) - internal function for initialization of
317  *                                Lower Band
318  * EncoderInitUb(...) - internal function for initialization of
319  *                                Upper Band
320  * WebRtcIsac_EncoderInit(...) - API function
321  *
322  * This function initializes a ISAC instance prior to the encoder calls.
323  *
324  * Input:
325  *        - ISAC_main_inst    : ISAC instance.
326  *        - CodingMode        : 0 -> Bit rate and frame length are automatically
327  *                                 adjusted to available bandwidth on
328  *                                 transmission channel, applicable just to
329  *                                 wideband mode.
330  *                              1 -> User sets a frame length and a target bit
331  *                                 rate which is taken as the maximum
332  *                                 short-term average bit rate.
333  *
334  * Return value               :  0 - Ok
335  *                              -1 - Error
336  */
337 static int16_t EncoderInitLb(ISACLBStruct* instLB,
338                              int16_t codingMode,
339                              enum IsacSamplingRate sampRate) {
340   int16_t statusInit = 0;
341   int k;
342
343   /* Init stream vector to zero */
344   for (k = 0; k < STREAM_SIZE_MAX_60; k++) {
345     instLB->ISACencLB_obj.bitstr_obj.stream[k] = 0;
346   }
347
348   if ((codingMode == 1) || (sampRate == kIsacSuperWideband)) {
349     /* 30 ms frame-size if either in super-wideband or
350      * instantaneous mode (I-mode). */
351     instLB->ISACencLB_obj.new_framelength = 480;
352   } else {
353     instLB->ISACencLB_obj.new_framelength = INITIAL_FRAMESAMPLES;
354   }
355
356   WebRtcIsac_InitMasking(&instLB->ISACencLB_obj.maskfiltstr_obj);
357   WebRtcIsac_InitPreFilterbank(&instLB->ISACencLB_obj.prefiltbankstr_obj);
358   WebRtcIsac_InitPitchFilter(&instLB->ISACencLB_obj.pitchfiltstr_obj);
359   WebRtcIsac_InitPitchAnalysis(
360     &instLB->ISACencLB_obj.pitchanalysisstr_obj);
361
362   instLB->ISACencLB_obj.buffer_index = 0;
363   instLB->ISACencLB_obj.frame_nb = 0;
364   /* Default for I-mode. */
365   instLB->ISACencLB_obj.bottleneck = 32000;
366   instLB->ISACencLB_obj.current_framesamples = 0;
367   instLB->ISACencLB_obj.s2nr = 0;
368   instLB->ISACencLB_obj.payloadLimitBytes30 = STREAM_SIZE_MAX_30;
369   instLB->ISACencLB_obj.payloadLimitBytes60 = STREAM_SIZE_MAX_60;
370   instLB->ISACencLB_obj.maxPayloadBytes = STREAM_SIZE_MAX_60;
371   instLB->ISACencLB_obj.maxRateInBytes = STREAM_SIZE_MAX_30;
372   instLB->ISACencLB_obj.enforceFrameSize = 0;
373   /* Invalid value prevents getRedPayload to
374      run before encoder is called. */
375   instLB->ISACencLB_obj.lastBWIdx            = -1;
376   return statusInit;
377 }
378
379 static int16_t EncoderInitUb(ISACUBStruct* instUB,
380                              int16_t bandwidth) {
381   int16_t statusInit = 0;
382   int k;
383
384   /* Init stream vector to zero. */
385   for (k = 0; k < STREAM_SIZE_MAX_60; k++) {
386     instUB->ISACencUB_obj.bitstr_obj.stream[k] = 0;
387   }
388
389   WebRtcIsac_InitMasking(&instUB->ISACencUB_obj.maskfiltstr_obj);
390   WebRtcIsac_InitPreFilterbank(&instUB->ISACencUB_obj.prefiltbankstr_obj);
391
392   if (bandwidth == isac16kHz) {
393     instUB->ISACencUB_obj.buffer_index = LB_TOTAL_DELAY_SAMPLES;
394   } else {
395     instUB->ISACencUB_obj.buffer_index = 0;
396   }
397   /* Default for I-mode. */
398   instUB->ISACencUB_obj.bottleneck = 32000;
399   /* These store the limits for the wideband + super-wideband bit-stream. */
400   instUB->ISACencUB_obj.maxPayloadSizeBytes = STREAM_SIZE_MAX_30 << 1;
401   /* This has to be updated after each lower-band encoding to guarantee
402    * a correct payload-limitation. */
403   instUB->ISACencUB_obj.numBytesUsed = 0;
404   memset(instUB->ISACencUB_obj.data_buffer_float, 0,
405          (MAX_FRAMESAMPLES + LB_TOTAL_DELAY_SAMPLES) * sizeof(float));
406
407   memcpy(&(instUB->ISACencUB_obj.lastLPCVec),
408          WebRtcIsac_kMeanLarUb16, sizeof(double) * UB_LPC_ORDER);
409
410   return statusInit;
411 }
412
413
414 int16_t WebRtcIsac_EncoderInit(ISACStruct* ISAC_main_inst,
415                                int16_t codingMode) {
416   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
417   int16_t status;
418
419   if ((codingMode != 0) && (codingMode != 1)) {
420     instISAC->errorCode = ISAC_DISALLOWED_CODING_MODE;
421     return -1;
422   }
423   /* Default bottleneck. */
424   instISAC->bottleneck = MAX_ISAC_BW;
425
426   if (instISAC->encoderSamplingRateKHz == kIsacWideband) {
427     instISAC->bandwidthKHz = isac8kHz;
428     instISAC->maxPayloadSizeBytes = STREAM_SIZE_MAX_60;
429     instISAC->maxRateBytesPer30Ms = STREAM_SIZE_MAX_30;
430   } else {
431     instISAC->bandwidthKHz = isac16kHz;
432     instISAC->maxPayloadSizeBytes = STREAM_SIZE_MAX;
433     instISAC->maxRateBytesPer30Ms = STREAM_SIZE_MAX;
434   }
435
436   /* Channel-adaptive = 0; Instantaneous (Channel-independent) = 1. */
437   instISAC->codingMode = codingMode;
438
439   WebRtcIsac_InitBandwidthEstimator(&instISAC->bwestimator_obj,
440                                     instISAC->encoderSamplingRateKHz,
441                                     instISAC->decoderSamplingRateKHz);
442
443   WebRtcIsac_InitRateModel(&instISAC->rate_data_obj);
444   /* Default for I-mode. */
445   instISAC->MaxDelay = 10.0;
446
447   status = EncoderInitLb(&instISAC->instLB, codingMode,
448                          instISAC->encoderSamplingRateKHz);
449   if (status < 0) {
450     instISAC->errorCode = -status;
451     return -1;
452   }
453
454   if (instISAC->encoderSamplingRateKHz == kIsacSuperWideband) {
455     /* Initialize encoder filter-bank. */
456     memset(instISAC->analysisFBState1, 0,
457            FB_STATE_SIZE_WORD32 * sizeof(int32_t));
458     memset(instISAC->analysisFBState2, 0,
459            FB_STATE_SIZE_WORD32 * sizeof(int32_t));
460
461     status = EncoderInitUb(&(instISAC->instUB),
462                            instISAC->bandwidthKHz);
463     if (status < 0) {
464       instISAC->errorCode = -status;
465       return -1;
466     }
467   }
468   memset(instISAC->state_in_resampler, 0, sizeof(instISAC->state_in_resampler));
469   /* Initialization is successful, set the flag. */
470   instISAC->initFlag |= BIT_MASK_ENC_INIT;
471   return 0;
472 }
473
474
475 /****************************************************************************
476  * WebRtcIsac_Encode(...)
477  *
478  * This function encodes 10ms frame(s) and inserts it into a package.
479  * Input speech length has to be 160 samples (10ms). The encoder buffers those
480  * 10ms frames until it reaches the chosen Framesize (480 or 960 samples
481  * corresponding to 30 or 60 ms frames), and then proceeds to the encoding.
482  *
483  * Input:
484  *        - ISAC_main_inst    : ISAC instance.
485  *        - speechIn          : input speech vector.
486  *
487  * Output:
488  *        - encoded           : the encoded data vector
489  *
490  * Return value:
491  *                            : >0 - Length (in bytes) of coded data
492  *                            :  0 - The buffer didn't reach the chosen
493  *                                  frameSize so it keeps buffering speech
494  *                                 samples.
495  *                            : -1 - Error
496  */
497 int16_t WebRtcIsac_Encode(ISACStruct* ISAC_main_inst,
498                           const int16_t* speechIn,
499                           int16_t* encoded) {
500   float inFrame[FRAMESAMPLES_10ms];
501   int16_t speechInLB[FRAMESAMPLES_10ms];
502   int16_t speechInUB[FRAMESAMPLES_10ms];
503   int16_t streamLenLB = 0;
504   int16_t streamLenUB = 0;
505   int16_t streamLen = 0;
506   int16_t k = 0;
507   uint8_t* ptrEncodedUW8 = (uint8_t*)encoded;
508   int garbageLen = 0;
509   int32_t bottleneck = 0;
510   int16_t bottleneckIdx = 0;
511   int16_t jitterInfo = 0;
512
513   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
514   ISACLBStruct* instLB = &(instISAC->instLB);
515   ISACUBStruct* instUB = &(instISAC->instUB);
516   const int16_t* speech_in_ptr = speechIn;
517   int16_t resampled_buff[FRAMESAMPLES_10ms * 2];
518
519   /* Check if encoder initiated. */
520   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) !=
521       BIT_MASK_ENC_INIT) {
522     instISAC->errorCode = ISAC_ENCODER_NOT_INITIATED;
523     return -1;
524   }
525
526   if (instISAC->in_sample_rate_hz == 48000) {
527     /* Samples in 10 ms @ 48 kHz. */
528     const int kNumInputSamples = FRAMESAMPLES_10ms * 3;
529     /* Samples 10 ms @ 32 kHz. */
530     const int kNumOutputSamples = FRAMESAMPLES_10ms * 2;
531     /* Resampler divide the input into blocks of 3 samples, i.e.
532      * kNumInputSamples / 3. */
533     const int kNumResamplerBlocks = FRAMESAMPLES_10ms;
534     int32_t buffer32[FRAMESAMPLES_10ms * 3 + SIZE_RESAMPLER_STATE];
535
536     /* Restore last samples from the past to the beginning of the buffer
537      * and store the last samples of current frame for the next resampling. */
538     for (k = 0; k < SIZE_RESAMPLER_STATE; k++) {
539       buffer32[k] = instISAC->state_in_resampler[k];
540       instISAC->state_in_resampler[k] = speechIn[kNumInputSamples -
541                                                  SIZE_RESAMPLER_STATE + k];
542     }
543     for (k = 0; k < kNumInputSamples; k++) {
544       buffer32[SIZE_RESAMPLER_STATE + k] = speechIn[k];
545     }
546     /* Resampling 3 samples to 2. Function divides the input in
547      * |kNumResamplerBlocks| number of 3-sample groups, and output is
548      * |kNumResamplerBlocks| number of 2-sample groups. */
549     WebRtcSpl_Resample48khzTo32khz(buffer32, buffer32, kNumResamplerBlocks);
550     WebRtcSpl_VectorBitShiftW32ToW16(resampled_buff, kNumOutputSamples,
551                                      buffer32, 15);
552     speech_in_ptr = resampled_buff;
553   }
554
555   if (instISAC->encoderSamplingRateKHz == kIsacSuperWideband) {
556     WebRtcSpl_AnalysisQMF(speech_in_ptr, SWBFRAMESAMPLES_10ms, speechInLB,
557                           speechInUB, instISAC->analysisFBState1,
558                           instISAC->analysisFBState2);
559
560     /* Convert from fixed to floating point. */
561     for (k = 0; k < FRAMESAMPLES_10ms; k++) {
562       inFrame[k] = (float)speechInLB[k];
563     }
564   } else {
565     for (k = 0; k < FRAMESAMPLES_10ms; k++) {
566       inFrame[k] = (float) speechIn[k];
567     }
568   }
569
570   /* Add some noise to avoid denormal numbers. */
571   inFrame[0] += (float)1.23455334e-3;
572   inFrame[1] -= (float)2.04324239e-3;
573   inFrame[2] += (float)1.90854954e-3;
574   inFrame[9] += (float)1.84854878e-3;
575
576   /* This function will update the bottleneck if required. */
577   UpdateBottleneck(instISAC);
578
579   /* Get the bandwith information which has to be sent to the other side. */
580   GetSendBandwidthInfo(instISAC, &bottleneckIdx, &jitterInfo);
581
582   /* Encode lower-band. */
583   streamLenLB = WebRtcIsac_EncodeLb(inFrame, &instLB->ISACencLB_obj,
584                                     instISAC->codingMode, bottleneckIdx);
585   if (streamLenLB < 0) {
586     return -1;
587   }
588
589   if (instISAC->encoderSamplingRateKHz == kIsacSuperWideband) {
590     instUB = &(instISAC->instUB);
591
592     /* Convert to float. */
593     for (k = 0; k < FRAMESAMPLES_10ms; k++) {
594       inFrame[k] = (float) speechInUB[k];
595     }
596
597     /* Add some noise to avoid denormal numbers. */
598     inFrame[0] += (float)1.23455334e-3;
599     inFrame[1] -= (float)2.04324239e-3;
600     inFrame[2] += (float)1.90854954e-3;
601     inFrame[9] += (float)1.84854878e-3;
602
603     /* Tell to upper-band the number of bytes used so far.
604      * This is for payload limitation. */
605     instUB->ISACencUB_obj.numBytesUsed = streamLenLB + 1 +
606                                          LEN_CHECK_SUM_WORD8;
607     /* Encode upper-band. */
608     switch (instISAC->bandwidthKHz) {
609       case isac12kHz: {
610         streamLenUB = WebRtcIsac_EncodeUb12(inFrame, &instUB->ISACencUB_obj,
611                                             jitterInfo);
612         break;
613       }
614       case isac16kHz: {
615         streamLenUB = WebRtcIsac_EncodeUb16(inFrame, &instUB->ISACencUB_obj,
616                                             jitterInfo);
617         break;
618       }
619       case isac8kHz: {
620         streamLenUB = 0;
621         break;
622       }
623     }
624
625     if ((streamLenUB < 0) && (streamLenUB != -ISAC_PAYLOAD_LARGER_THAN_LIMIT)) {
626       /* An error has happened but this is not the error due to a
627        * bit-stream larger than the limit. */
628       return -1;
629     }
630
631     if (streamLenLB == 0) {
632       return 0;
633     }
634
635     /* One byte is allocated for the length. According to older decoders
636        so the length bit-stream plus one byte for size and
637        LEN_CHECK_SUM_WORD8 for the checksum should be less than or equal
638        to 255. */
639     if ((streamLenUB > (255 - (LEN_CHECK_SUM_WORD8 + 1))) ||
640         (streamLenUB == -ISAC_PAYLOAD_LARGER_THAN_LIMIT)) {
641       /* We have got a too long bit-stream we skip the upper-band
642        * bit-stream for this frame. */
643       streamLenUB = 0;
644     }
645
646     memcpy(ptrEncodedUW8, instLB->ISACencLB_obj.bitstr_obj.stream, streamLenLB);
647     streamLen = streamLenLB;
648     if (streamLenUB > 0) {
649       ptrEncodedUW8[streamLenLB] = (uint8_t)(streamLenUB + 1 +
650                                                    LEN_CHECK_SUM_WORD8);
651       memcpy(&ptrEncodedUW8[streamLenLB + 1],
652              instUB->ISACencUB_obj.bitstr_obj.stream, streamLenUB);
653       streamLen += ptrEncodedUW8[streamLenLB];
654     } else {
655       ptrEncodedUW8[streamLenLB] = 0;
656     }
657   } else {
658     if (streamLenLB == 0) {
659       return 0;
660     }
661     memcpy(ptrEncodedUW8, instLB->ISACencLB_obj.bitstr_obj.stream,
662            streamLenLB);
663     streamLenUB = 0;
664     streamLen = streamLenLB;
665   }
666
667   /* Add Garbage if required. */
668   WebRtcIsac_GetUplinkBandwidth(&instISAC->bwestimator_obj, &bottleneck);
669   if (instISAC->codingMode == 0) {
670     int minBytes;
671     int limit;
672     uint8_t* ptrGarbage;
673
674     instISAC->MaxDelay = (double)WebRtcIsac_GetUplinkMaxDelay(
675                            &instISAC->bwestimator_obj);
676
677     /* Update rate model and get minimum number of bytes in this packet. */
678     minBytes = WebRtcIsac_GetMinBytes(
679         &(instISAC->rate_data_obj), streamLen,
680         instISAC->instLB.ISACencLB_obj.current_framesamples, bottleneck,
681         instISAC->MaxDelay, instISAC->bandwidthKHz);
682
683     /* Make sure MinBytes does not exceed packet size limit. */
684     if (instISAC->bandwidthKHz == isac8kHz) {
685       if (instLB->ISACencLB_obj.current_framesamples == FRAMESAMPLES) {
686         limit = instLB->ISACencLB_obj.payloadLimitBytes30;
687       } else {
688         limit = instLB->ISACencLB_obj.payloadLimitBytes60;
689       }
690     } else {
691       limit = instUB->ISACencUB_obj.maxPayloadSizeBytes;
692     }
693     minBytes = (minBytes > limit) ? limit : minBytes;
694
695     /* Make sure we don't allow more than 255 bytes of garbage data.
696      * We store the length of the garbage data in 8 bits in the bitstream,
697      * 255 is the max garbage length we can signal using 8 bits. */
698     if ((instISAC->bandwidthKHz == isac8kHz) ||
699         (streamLenUB == 0)) {
700       ptrGarbage = &ptrEncodedUW8[streamLenLB];
701       limit = streamLen + 255;
702     } else {
703       ptrGarbage = &ptrEncodedUW8[streamLenLB + 1 + streamLenUB];
704       limit = streamLen + (255 - ptrEncodedUW8[streamLenLB]);
705     }
706     minBytes = (minBytes > limit) ? limit : minBytes;
707
708     garbageLen = (minBytes > streamLen) ? (minBytes - streamLen) : 0;
709
710     /* Save data for creation of multiple bit-streams. */
711     /* If bit-stream too short then add garbage at the end. */
712     if (garbageLen > 0) {
713       for (k = 0; k < garbageLen; k++) {
714         ptrGarbage[k] = (uint8_t)(rand() & 0xFF);
715       }
716       /* For a correct length of the upper-band bit-stream together
717        * with the garbage. Garbage is embeded in upper-band bit-stream.
718        * That is the only way to preserve backward compatibility. */
719       if ((instISAC->bandwidthKHz == isac8kHz) ||
720           (streamLenUB == 0)) {
721         ptrEncodedUW8[streamLenLB] = (uint8_t)garbageLen;
722       } else {
723         ptrEncodedUW8[streamLenLB] += (uint8_t)garbageLen;
724         /* Write the length of the garbage at the end of the upper-band
725          *  bit-stream, if exists. This helps for sanity check. */
726         ptrEncodedUW8[streamLenLB + 1 + streamLenUB] =
727             (uint8_t)garbageLen;
728
729       }
730       streamLen += garbageLen;
731     }
732   } else {
733     /* update rate model */
734     WebRtcIsac_UpdateRateModel(
735         &instISAC->rate_data_obj, streamLen,
736         instISAC->instLB.ISACencLB_obj.current_framesamples, bottleneck);
737     garbageLen = 0;
738   }
739
740   /* Generate CRC if required. */
741   if ((instISAC->bandwidthKHz != isac8kHz) && (streamLenUB > 0)) {
742     uint32_t crc;
743
744     WebRtcIsac_GetCrc((int16_t*)(&(ptrEncodedUW8[streamLenLB + 1])),
745                       streamLenUB + garbageLen, &crc);
746 #ifndef WEBRTC_ARCH_BIG_ENDIAN
747     for (k = 0; k < LEN_CHECK_SUM_WORD8; k++) {
748       ptrEncodedUW8[streamLen - LEN_CHECK_SUM_WORD8 + k] =
749         (uint8_t)((crc >> (24 - k * 8)) & 0xFF);
750     }
751 #else
752     memcpy(&ptrEncodedUW8[streamLenLB + streamLenUB + 1], &crc,
753            LEN_CHECK_SUM_WORD8);
754 #endif
755   }
756   return streamLen;
757 }
758
759
760 /******************************************************************************
761  * WebRtcIsac_GetNewBitStream(...)
762  *
763  * This function returns encoded data, with the recieved bwe-index in the
764  * stream. If the rate is set to a value less than bottleneck of codec
765  * the new bistream will be re-encoded with the given target rate.
766  * It should always return a complete packet, i.e. only called once
767  * even for 60 msec frames.
768  *
769  * NOTE 1! This function does not write in the ISACStruct, it is not allowed.
770  * NOTE 2! Rates larger than the bottleneck of the codec will be limited
771  *         to the current bottleneck.
772  *
773  * Input:
774  *        - ISAC_main_inst    : ISAC instance.
775  *        - bweIndex          : Index of bandwidth estimate to put in new
776  *                              bitstream
777  *        - rate              : target rate of the transcoder is bits/sec.
778  *                              Valid values are the accepted rate in iSAC,
779  *                              i.e. 10000 to 56000.
780  *
781  * Output:
782  *        - encoded           : The encoded data vector
783  *
784  * Return value               : >0 - Length (in bytes) of coded data
785  *                              -1 - Error  or called in SWB mode
786  *                                 NOTE! No error code is written to
787  *                                 the struct since it is only allowed to read
788  *                                 the struct.
789  */
790 int16_t WebRtcIsac_GetNewBitStream(ISACStruct*  ISAC_main_inst,
791                                    int16_t  bweIndex,
792                                    int16_t  jitterInfo,
793                                    int32_t  rate,
794                                    int16_t* encoded,
795                                    int16_t  isRCU) {
796   Bitstr iSACBitStreamInst;   /* Local struct for bitstream handling */
797   int16_t streamLenLB;
798   int16_t streamLenUB;
799   int16_t totalStreamLen;
800   double gain2;
801   double gain1;
802   float scale;
803   enum ISACBandwidth bandwidthKHz;
804   double rateLB;
805   double rateUB;
806   int32_t currentBN;
807   uint8_t* encodedPtrUW8 = (uint8_t*)encoded;
808   uint32_t crc;
809 #ifndef WEBRTC_ARCH_BIG_ENDIAN
810   int16_t  k;
811 #endif
812   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
813
814   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) !=
815       BIT_MASK_ENC_INIT) {
816     return -1;
817   }
818
819   /* Get the bottleneck of this iSAC and limit the
820    * given rate to the current bottleneck. */
821   WebRtcIsac_GetUplinkBw(ISAC_main_inst, &currentBN);
822   if (rate > currentBN) {
823     rate = currentBN;
824   }
825
826   if (WebRtcIsac_RateAllocation(rate, &rateLB, &rateUB, &bandwidthKHz) < 0) {
827     return -1;
828   }
829
830   /* Cannot transcode from 16 kHz to 12 kHz. */
831   if ((bandwidthKHz == isac12kHz) &&
832       (instISAC->bandwidthKHz == isac16kHz)) {
833     return -1;
834   }
835
836   /* A gain [dB] for the given rate. */
837   gain1 = WebRtcIsac_GetSnr(
838       rateLB, instISAC->instLB.ISACencLB_obj.current_framesamples);
839   /* The gain [dB] of this iSAC. */
840   gain2 = WebRtcIsac_GetSnr(
841       instISAC->instLB.ISACencLB_obj.bottleneck,
842       instISAC->instLB.ISACencLB_obj.current_framesamples);
843
844   /* Scale is the ratio of two gains in normal domain. */
845   scale = (float)pow(10, (gain1 - gain2) / 20.0);
846   /* Change the scale if this is a RCU bit-stream. */
847   scale = (isRCU) ? (scale * RCU_TRANSCODING_SCALE) : scale;
848
849   streamLenLB = WebRtcIsac_EncodeStoredDataLb(
850                   &instISAC->instLB.ISACencLB_obj.SaveEnc_obj,
851                   &iSACBitStreamInst, bweIndex, scale);
852
853   if (streamLenLB < 0) {
854     return -1;
855   }
856
857   /* Convert from bytes to int16_t. */
858   memcpy(encoded, iSACBitStreamInst.stream, streamLenLB);
859
860   if (bandwidthKHz == isac8kHz) {
861     return streamLenLB;
862   }
863
864   totalStreamLen = streamLenLB;
865   /* super-wideband is always at 30ms.
866    * These gains are in dB.
867    * Gain for the given rate. */
868   gain1 = WebRtcIsac_GetSnr(rateUB, FRAMESAMPLES);
869   /* Gain of this iSAC */
870   gain2 = WebRtcIsac_GetSnr(instISAC->instUB.ISACencUB_obj.bottleneck,
871                             FRAMESAMPLES);
872
873   /* Scale is the ratio of two gains in normal domain. */
874   scale = (float)pow(10, (gain1 - gain2) / 20.0);
875
876   /* Change the scale if this is a RCU bit-stream. */
877   scale = (isRCU)? (scale * RCU_TRANSCODING_SCALE_UB) : scale;
878
879   streamLenUB = WebRtcIsac_EncodeStoredDataUb(
880                   &(instISAC->instUB.ISACencUB_obj.SaveEnc_obj),
881                   &iSACBitStreamInst, jitterInfo, scale,
882                   instISAC->bandwidthKHz);
883
884   if (streamLenUB < 0) {
885     return -1;
886   }
887
888   if (streamLenUB + 1 + LEN_CHECK_SUM_WORD8 > 255) {
889     return streamLenLB;
890   }
891
892   totalStreamLen = streamLenLB + streamLenUB + 1 + LEN_CHECK_SUM_WORD8;
893   encodedPtrUW8[streamLenLB] = streamLenUB + 1 + LEN_CHECK_SUM_WORD8;
894
895   memcpy(&encodedPtrUW8[streamLenLB + 1], iSACBitStreamInst.stream,
896          streamLenUB);
897
898   WebRtcIsac_GetCrc((int16_t*)(&(encodedPtrUW8[streamLenLB + 1])),
899                     streamLenUB, &crc);
900 #ifndef WEBRTC_ARCH_BIG_ENDIAN
901   for (k = 0; k < LEN_CHECK_SUM_WORD8; k++) {
902     encodedPtrUW8[totalStreamLen - LEN_CHECK_SUM_WORD8 + k] =
903       (uint8_t)((crc >> (24 - k * 8)) & 0xFF);
904   }
905 #else
906   memcpy(&encodedPtrUW8[streamLenLB + streamLenUB + 1], &crc,
907          LEN_CHECK_SUM_WORD8);
908 #endif
909   return totalStreamLen;
910 }
911
912
913 /****************************************************************************
914  * DecoderInitLb(...) - internal function for initialization of
915  *                                Lower Band
916  * DecoderInitUb(...) - internal function for initialization of
917  *                                Upper Band
918  * WebRtcIsac_DecoderInit(...) - API function
919  *
920  * This function initializes a ISAC instance prior to the decoder calls.
921  *
922  * Input:
923  *        - ISAC_main_inst    : ISAC instance.
924  *
925  * Return value
926  *                            :  0 - Ok
927  *                              -1 - Error
928  */
929 static int16_t DecoderInitLb(ISACLBStruct* instISAC) {
930   int i;
931   /* Initialize stream vector to zero. */
932   for (i = 0; i < STREAM_SIZE_MAX_60; i++) {
933     instISAC->ISACdecLB_obj.bitstr_obj.stream[i] = 0;
934   }
935
936   WebRtcIsac_InitMasking(&instISAC->ISACdecLB_obj.maskfiltstr_obj);
937   WebRtcIsac_InitPostFilterbank(
938     &instISAC->ISACdecLB_obj.postfiltbankstr_obj);
939   WebRtcIsac_InitPitchFilter(&instISAC->ISACdecLB_obj.pitchfiltstr_obj);
940   return 0;
941 }
942
943 static int16_t DecoderInitUb(ISACUBStruct* instISAC) {
944   int i;
945   /* Init stream vector to zero */
946   for (i = 0; i < STREAM_SIZE_MAX_60; i++) {
947     instISAC->ISACdecUB_obj.bitstr_obj.stream[i] = 0;
948   }
949
950   WebRtcIsac_InitMasking(&instISAC->ISACdecUB_obj.maskfiltstr_obj);
951   WebRtcIsac_InitPostFilterbank(
952     &instISAC->ISACdecUB_obj.postfiltbankstr_obj);
953   return (0);
954 }
955
956 int16_t WebRtcIsac_DecoderInit(ISACStruct* ISAC_main_inst) {
957   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
958
959   if (DecoderInitLb(&instISAC->instLB) < 0) {
960     return -1;
961   }
962   if (instISAC->decoderSamplingRateKHz == kIsacSuperWideband) {
963     memset(instISAC->synthesisFBState1, 0,
964            FB_STATE_SIZE_WORD32 * sizeof(int32_t));
965     memset(instISAC->synthesisFBState2, 0,
966            FB_STATE_SIZE_WORD32 * sizeof(int32_t));
967
968     if (DecoderInitUb(&(instISAC->instUB)) < 0) {
969       return -1;
970     }
971   }
972   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) != BIT_MASK_ENC_INIT) {
973     WebRtcIsac_InitBandwidthEstimator(&instISAC->bwestimator_obj,
974                                       instISAC->encoderSamplingRateKHz,
975                                       instISAC->decoderSamplingRateKHz);
976   }
977   instISAC->initFlag |= BIT_MASK_DEC_INIT;
978   instISAC->resetFlag_8kHz = 0;
979   return 0;
980 }
981
982
983 /****************************************************************************
984  * WebRtcIsac_UpdateBwEstimate(...)
985  *
986  * This function updates the estimate of the bandwidth.
987  *
988  * NOTE:
989  * The estimates of bandwidth is not valid if the sample rate of the far-end
990  * encoder is set to 48 kHz and send timestamps are increamented according to
991  * 48 kHz sampling rate.
992  *
993  * Input:
994  *        - ISAC_main_inst    : ISAC instance.
995  *        - encoded           : encoded ISAC frame(s).
996  *        - packet_size       : size of the packet.
997  *        - rtp_seq_number    : the RTP number of the packet.
998  *        - arr_ts            : the arrival time of the packet (from NetEq)
999  *                              in samples.
1000  *
1001  * Return value               :  0 - Ok
1002  *                              -1 - Error
1003  */
1004 int16_t WebRtcIsac_UpdateBwEstimate(ISACStruct* ISAC_main_inst,
1005                                     const uint16_t* encoded,
1006                                     int32_t packet_size,
1007                                     uint16_t rtp_seq_number,
1008                                     uint32_t send_ts,
1009                                     uint32_t arr_ts) {
1010   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1011   Bitstr streamdata;
1012 #ifndef WEBRTC_ARCH_BIG_ENDIAN
1013   int k;
1014 #endif
1015   int16_t err;
1016
1017   /* Check if decoder initiated. */
1018   if ((instISAC->initFlag & BIT_MASK_DEC_INIT) != BIT_MASK_DEC_INIT) {
1019     instISAC->errorCode = ISAC_DECODER_NOT_INITIATED;
1020     return -1;
1021   }
1022
1023   /* Check that the size of the packet is valid, and if not return without
1024    * updating the bandwidth estimate. A valid size is at least 10 bytes. */
1025   if (packet_size < 10) {
1026     /* Return error code if the packet length is null. */
1027     instISAC->errorCode = ISAC_EMPTY_PACKET;
1028     return -1;
1029   }
1030
1031   WebRtcIsac_ResetBitstream(&(streamdata));
1032
1033 #ifndef WEBRTC_ARCH_BIG_ENDIAN
1034   for (k = 0; k < 10; k++) {
1035     streamdata.stream[k] = (uint8_t)((encoded[k >> 1] >>
1036                                             ((k & 1) << 3)) & 0xFF);
1037   }
1038 #else
1039   memcpy(streamdata.stream, encoded, 10);
1040 #endif
1041
1042   err = WebRtcIsac_EstimateBandwidth(&instISAC->bwestimator_obj, &streamdata,
1043                                      packet_size, rtp_seq_number, send_ts,
1044                                      arr_ts, instISAC->encoderSamplingRateKHz,
1045                                      instISAC->decoderSamplingRateKHz);
1046   if (err < 0) {
1047     /* Return error code if something went wrong. */
1048     instISAC->errorCode = -err;
1049     return -1;
1050   }
1051   return 0;
1052 }
1053
1054 static int16_t Decode(ISACStruct* ISAC_main_inst,
1055                       const uint16_t* encoded,
1056                       int16_t lenEncodedBytes,
1057                       int16_t* decoded,
1058                       int16_t* speechType,
1059                       int16_t isRCUPayload) {
1060   /* Number of samples (480 or 960), output from decoder
1061      that were actually used in the encoder/decoder
1062      (determined on the fly). */
1063   int16_t numSamplesLB;
1064   int16_t numSamplesUB;
1065   int16_t speechIdx;
1066   float outFrame[MAX_FRAMESAMPLES];
1067   int16_t outFrameLB[MAX_FRAMESAMPLES];
1068   int16_t outFrameUB[MAX_FRAMESAMPLES];
1069   int16_t numDecodedBytesLB;
1070   int16_t numDecodedBytesUB;
1071   int16_t lenEncodedLBBytes;
1072   int16_t validChecksum = 1;
1073   int16_t k;
1074   uint8_t* ptrEncodedUW8 = (uint8_t*)encoded;
1075   uint16_t numLayer;
1076   int16_t totSizeBytes;
1077   int16_t err;
1078
1079   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1080   ISACUBDecStruct* decInstUB = &(instISAC->instUB.ISACdecUB_obj);
1081   ISACLBDecStruct* decInstLB = &(instISAC->instLB.ISACdecLB_obj);
1082
1083   /* Check if decoder initiated. */
1084   if ((instISAC->initFlag & BIT_MASK_DEC_INIT) !=
1085       BIT_MASK_DEC_INIT) {
1086     instISAC->errorCode = ISAC_DECODER_NOT_INITIATED;
1087     return -1;
1088   }
1089
1090   if (lenEncodedBytes <= 0) {
1091     /* return error code if the packet length is null. */
1092     instISAC->errorCode = ISAC_EMPTY_PACKET;
1093     return -1;
1094   }
1095
1096   /* The size of the encoded lower-band is bounded by
1097    * STREAM_SIZE_MAX. If a payload with the size larger than STREAM_SIZE_MAX
1098    * is received, it is not considered erroneous. */
1099   lenEncodedLBBytes = (lenEncodedBytes > STREAM_SIZE_MAX) ?
1100       STREAM_SIZE_MAX : lenEncodedBytes;
1101
1102   /* Copy to lower-band bit-stream structure. */
1103   memcpy(instISAC->instLB.ISACdecLB_obj.bitstr_obj.stream, ptrEncodedUW8,
1104          lenEncodedLBBytes);
1105
1106   /* Regardless of that the current codec is setup to work in
1107    * wideband or super-wideband, the decoding of the lower-band
1108    * has to be performed. */
1109   numDecodedBytesLB = WebRtcIsac_DecodeLb(outFrame, decInstLB,
1110                                           &numSamplesLB, isRCUPayload);
1111
1112   if ((numDecodedBytesLB < 0) || (numDecodedBytesLB > lenEncodedLBBytes) ||
1113       (numSamplesLB > MAX_FRAMESAMPLES)) {
1114     instISAC->errorCode = ISAC_LENGTH_MISMATCH;
1115     return -1;
1116   }
1117
1118   /* Error Check, we accept multi-layer bit-stream This will limit number
1119    * of iterations of the while loop. Even without this the number
1120    * of iterations is limited. */
1121   numLayer = 1;
1122   totSizeBytes = numDecodedBytesLB;
1123   while (totSizeBytes != lenEncodedBytes) {
1124     if ((totSizeBytes > lenEncodedBytes) ||
1125         (ptrEncodedUW8[totSizeBytes] == 0) ||
1126         (numLayer > MAX_NUM_LAYERS)) {
1127       instISAC->errorCode = ISAC_LENGTH_MISMATCH;
1128       return -1;
1129     }
1130     totSizeBytes += ptrEncodedUW8[totSizeBytes];
1131     numLayer++;
1132   }
1133
1134   if (instISAC->decoderSamplingRateKHz == kIsacWideband) {
1135     for (k = 0; k < numSamplesLB; k++) {
1136       if (outFrame[k] > 32767) {
1137         decoded[k] = 32767;
1138       } else if (outFrame[k] < -32768) {
1139         decoded[k] = -32768;
1140       } else {
1141         decoded[k] = (int16_t)WebRtcIsac_lrint(outFrame[k]);
1142       }
1143     }
1144     numSamplesUB = 0;
1145   } else {
1146     uint32_t crc;
1147     /* We don't accept larger than 30ms (480 samples at lower-band)
1148      * frame-size. */
1149     for (k = 0; k < numSamplesLB; k++) {
1150       if (outFrame[k] > 32767) {
1151         outFrameLB[k] = 32767;
1152       } else if (outFrame[k] < -32768) {
1153         outFrameLB[k] = -32768;
1154       } else {
1155         outFrameLB[k] = (int16_t)WebRtcIsac_lrint(outFrame[k]);
1156       }
1157     }
1158
1159     /* Check for possible error, and if upper-band stream exists. */
1160     if (numDecodedBytesLB == lenEncodedBytes) {
1161       /* Decoding was successful. No super-wideband bit-stream exists. */
1162       numSamplesUB = numSamplesLB;
1163       memset(outFrameUB, 0, sizeof(int16_t) *  numSamplesUB);
1164
1165       /* Prepare for the potential increase of signal bandwidth. */
1166       instISAC->resetFlag_8kHz = 2;
1167     } else {
1168       /* This includes the checksum and the bytes that stores the length. */
1169       int16_t lenNextStream = ptrEncodedUW8[numDecodedBytesLB];
1170
1171       /* Is this garbage or valid super-wideband bit-stream?
1172        * Check if checksum is valid. */
1173       if (lenNextStream <= (LEN_CHECK_SUM_WORD8 + 1)) {
1174         /* Such a small second layer cannot be super-wideband layer.
1175          * It must be a short garbage. */
1176         validChecksum = 0;
1177       } else {
1178         /* Run CRC to see if the checksum match. */
1179         WebRtcIsac_GetCrc((int16_t*)(
1180                             &ptrEncodedUW8[numDecodedBytesLB + 1]),
1181                           lenNextStream - LEN_CHECK_SUM_WORD8 - 1, &crc);
1182
1183         validChecksum = 1;
1184         for (k = 0; k < LEN_CHECK_SUM_WORD8; k++) {
1185           validChecksum &= (((crc >> (24 - k * 8)) & 0xFF) ==
1186                             ptrEncodedUW8[numDecodedBytesLB + lenNextStream -
1187                                           LEN_CHECK_SUM_WORD8 + k]);
1188         }
1189       }
1190
1191       if (!validChecksum) {
1192         /* This is a garbage, we have received a wideband
1193          * bit-stream with garbage. */
1194         numSamplesUB = numSamplesLB;
1195         memset(outFrameUB, 0, sizeof(int16_t) * numSamplesUB);
1196       } else {
1197         /* A valid super-wideband biststream exists. */
1198         enum ISACBandwidth bandwidthKHz;
1199         int32_t maxDelayBit;
1200
1201         /* If we have super-wideband bit-stream, we cannot
1202          * have 60 ms frame-size. */
1203         if (numSamplesLB > FRAMESAMPLES) {
1204           instISAC->errorCode = ISAC_LENGTH_MISMATCH;
1205           return -1;
1206         }
1207
1208         /* The rest of the bit-stream contains the upper-band
1209          * bit-stream curently this is the only thing there,
1210          * however, we might add more layers. */
1211
1212         /* Have to exclude one byte where the length is stored
1213          * and last 'LEN_CHECK_SUM_WORD8' bytes where the
1214          * checksum is stored. */
1215         lenNextStream -= (LEN_CHECK_SUM_WORD8 + 1);
1216
1217         memcpy(decInstUB->bitstr_obj.stream,
1218                &ptrEncodedUW8[numDecodedBytesLB + 1], lenNextStream);
1219
1220         /* Reset bit-stream object, this is the first decoding. */
1221         WebRtcIsac_ResetBitstream(&(decInstUB->bitstr_obj));
1222
1223         /* Decode jitter information. */
1224         err = WebRtcIsac_DecodeJitterInfo(&decInstUB->bitstr_obj, &maxDelayBit);
1225         if (err < 0) {
1226           instISAC->errorCode = -err;
1227           return -1;
1228         }
1229
1230         /* Update jitter info which is in the upper-band bit-stream
1231          * only if the encoder is in super-wideband. Otherwise,
1232          * the jitter info is already embedded in bandwidth index
1233          * and has been updated. */
1234         if (instISAC->encoderSamplingRateKHz == kIsacSuperWideband) {
1235           err = WebRtcIsac_UpdateUplinkJitter(
1236                   &(instISAC->bwestimator_obj), maxDelayBit);
1237           if (err < 0) {
1238             instISAC->errorCode = -err;
1239             return -1;
1240           }
1241         }
1242
1243         /* Decode bandwidth information. */
1244         err = WebRtcIsac_DecodeBandwidth(&decInstUB->bitstr_obj,
1245                                          &bandwidthKHz);
1246         if (err < 0) {
1247           instISAC->errorCode = -err;
1248           return -1;
1249         }
1250
1251         switch (bandwidthKHz) {
1252           case isac12kHz: {
1253             numDecodedBytesUB = WebRtcIsac_DecodeUb12(outFrame, decInstUB,
1254                                                       isRCUPayload);
1255
1256             /* Hang-over for transient alleviation -
1257              * wait two frames to add the upper band going up from 8 kHz. */
1258             if (instISAC->resetFlag_8kHz > 0) {
1259               if (instISAC->resetFlag_8kHz == 2) {
1260                 /* Silence first and a half frame. */
1261                 memset(outFrame, 0, MAX_FRAMESAMPLES *
1262                        sizeof(float));
1263               } else {
1264                 const float rampStep = 2.0f / MAX_FRAMESAMPLES;
1265                 float rampVal = 0;
1266                 memset(outFrame, 0, (MAX_FRAMESAMPLES >> 1) *
1267                        sizeof(float));
1268
1269                 /* Ramp up second half of second frame. */
1270                 for (k = MAX_FRAMESAMPLES / 2; k < MAX_FRAMESAMPLES; k++) {
1271                   outFrame[k] *= rampVal;
1272                   rampVal += rampStep;
1273                 }
1274               }
1275               instISAC->resetFlag_8kHz -= 1;
1276             }
1277
1278             break;
1279           }
1280           case isac16kHz: {
1281             numDecodedBytesUB = WebRtcIsac_DecodeUb16(outFrame, decInstUB,
1282                                                       isRCUPayload);
1283             break;
1284           }
1285           default:
1286             return -1;
1287         }
1288
1289         /* It might be less due to garbage. */
1290         if ((numDecodedBytesUB != lenNextStream) &&
1291             (numDecodedBytesUB != (lenNextStream -
1292                 ptrEncodedUW8[numDecodedBytesLB + 1 + numDecodedBytesUB]))) {
1293           instISAC->errorCode = ISAC_LENGTH_MISMATCH;
1294           return -1;
1295         }
1296
1297         /* If there is no error Upper-band always decodes
1298          * 30 ms (480 samples). */
1299         numSamplesUB = FRAMESAMPLES;
1300
1301         /* Convert to W16. */
1302         for (k = 0; k < numSamplesUB; k++) {
1303           if (outFrame[k] > 32767) {
1304             outFrameUB[k] = 32767;
1305           } else if (outFrame[k] < -32768) {
1306             outFrameUB[k] = -32768;
1307           } else {
1308             outFrameUB[k] = (int16_t)WebRtcIsac_lrint(
1309                               outFrame[k]);
1310           }
1311         }
1312       }
1313     }
1314
1315     speechIdx = 0;
1316     while (speechIdx < numSamplesLB) {
1317       WebRtcSpl_SynthesisQMF(&outFrameLB[speechIdx], &outFrameUB[speechIdx],
1318                              FRAMESAMPLES_10ms, &decoded[(speechIdx << 1)],
1319                              instISAC->synthesisFBState1,
1320                              instISAC->synthesisFBState2);
1321
1322       speechIdx += FRAMESAMPLES_10ms;
1323     }
1324   }
1325   *speechType = 0;
1326   return (numSamplesLB + numSamplesUB);
1327 }
1328
1329
1330
1331
1332
1333
1334
1335 /****************************************************************************
1336  * WebRtcIsac_Decode(...)
1337  *
1338  * This function decodes a ISAC frame. Output speech length
1339  * will be a multiple of 480 samples: 480 or 960 samples,
1340  * depending on the  frameSize (30 or 60 ms).
1341  *
1342  * Input:
1343  *        - ISAC_main_inst    : ISAC instance.
1344  *        - encoded           : encoded ISAC frame(s)
1345  *        - len               : bytes in encoded vector
1346  *
1347  * Output:
1348  *        - decoded           : The decoded vector
1349  *
1350  * Return value               : >0 - number of samples in decoded vector
1351  *                              -1 - Error
1352  */
1353
1354 int16_t WebRtcIsac_Decode(ISACStruct* ISAC_main_inst,
1355                           const uint16_t* encoded,
1356                           int16_t lenEncodedBytes,
1357                           int16_t* decoded,
1358                           int16_t* speechType) {
1359   int16_t isRCUPayload = 0;
1360   return Decode(ISAC_main_inst, encoded, lenEncodedBytes, decoded,
1361                 speechType, isRCUPayload);
1362 }
1363
1364 /****************************************************************************
1365  * WebRtcIsac_DecodeRcu(...)
1366  *
1367  * This function decodes a redundant (RCU) iSAC frame. Function is called in
1368  * NetEq with a stored RCU payload in case of packet loss. Output speech length
1369  * will be a multiple of 480 samples: 480 or 960 samples,
1370  * depending on the framesize (30 or 60 ms).
1371  *
1372  * Input:
1373  *      - ISAC_main_inst     : ISAC instance.
1374  *      - encoded            : encoded ISAC RCU frame(s)
1375  *      - len                : bytes in encoded vector
1376  *
1377  * Output:
1378  *      - decoded            : The decoded vector
1379  *
1380  * Return value              : >0 - number of samples in decoded vector
1381  *                             -1 - Error
1382  */
1383
1384
1385
1386 int16_t WebRtcIsac_DecodeRcu(ISACStruct* ISAC_main_inst,
1387                              const uint16_t* encoded,
1388                              int16_t lenEncodedBytes,
1389                              int16_t* decoded,
1390                              int16_t* speechType) {
1391   int16_t isRCUPayload = 1;
1392   return Decode(ISAC_main_inst, encoded, lenEncodedBytes, decoded,
1393                 speechType, isRCUPayload);
1394 }
1395
1396
1397 /****************************************************************************
1398  * WebRtcIsac_DecodePlc(...)
1399  *
1400  * This function conducts PLC for ISAC frame(s). Output speech length
1401  * will be a multiple of 480 samples: 480 or 960 samples,
1402  * depending on the  frameSize (30 or 60 ms).
1403  *
1404  * Input:
1405  *        - ISAC_main_inst    : ISAC instance.
1406  *        - noOfLostFrames    : Number of PLC frames to produce
1407  *
1408  * Output:
1409  *        - decoded           : The decoded vector
1410  *
1411  * Return value               : >0 - number of samples in decoded PLC vector
1412  *                              -1 - Error
1413  */
1414 int16_t WebRtcIsac_DecodePlc(ISACStruct* ISAC_main_inst,
1415                              int16_t* decoded,
1416                              int16_t noOfLostFrames) {
1417   int16_t numSamples = 0;
1418   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1419
1420   /* Limit number of frames to two = 60 millisecond.
1421    * Otherwise we exceed data vectors. */
1422   if (noOfLostFrames > 2) {
1423     noOfLostFrames = 2;
1424   }
1425
1426   /* Get the number of samples per frame */
1427   switch (instISAC->decoderSamplingRateKHz) {
1428     case kIsacWideband: {
1429       numSamples = 480 * noOfLostFrames;
1430       break;
1431     }
1432     case kIsacSuperWideband: {
1433       numSamples = 960 * noOfLostFrames;
1434       break;
1435     }
1436   }
1437
1438   /* Set output samples to zero. */
1439   memset(decoded, 0, numSamples * sizeof(int16_t));
1440   return numSamples;
1441 }
1442
1443
1444 /****************************************************************************
1445  * ControlLb(...) - Internal function for controlling Lower Band
1446  * ControlUb(...) - Internal function for controlling Upper Band
1447  * WebRtcIsac_Control(...) - API function
1448  *
1449  * This function sets the limit on the short-term average bit rate and the
1450  * frame length. Should be used only in Instantaneous mode.
1451  *
1452  * Input:
1453  *        - ISAC_main_inst    : ISAC instance.
1454  *        - rate              : limit on the short-term average bit rate,
1455  *                              in bits/second (between 10000 and 32000)
1456  *        - frameSize         : number of milliseconds per frame (30 or 60)
1457  *
1458  * Return value               : 0 - ok
1459  *                             -1 - Error
1460  */
1461 static int16_t ControlLb(ISACLBStruct* instISAC, double rate,
1462                          int16_t frameSize) {
1463   if ((rate >= 10000) && (rate <= 32000)) {
1464     instISAC->ISACencLB_obj.bottleneck = rate;
1465   } else {
1466     return -ISAC_DISALLOWED_BOTTLENECK;
1467   }
1468
1469   if ((frameSize == 30) || (frameSize == 60)) {
1470     instISAC->ISACencLB_obj.new_framelength = (FS / 1000) *  frameSize;
1471   } else {
1472     return -ISAC_DISALLOWED_FRAME_LENGTH;
1473   }
1474
1475   return 0;
1476 }
1477
1478 static int16_t ControlUb(ISACUBStruct* instISAC, double rate) {
1479   if ((rate >= 10000) && (rate <= 32000)) {
1480     instISAC->ISACencUB_obj.bottleneck = rate;
1481   } else {
1482     return -ISAC_DISALLOWED_BOTTLENECK;
1483   }
1484   return 0;
1485 }
1486
1487 int16_t WebRtcIsac_Control(ISACStruct* ISAC_main_inst,
1488                            int32_t bottleneckBPS,
1489                            int16_t frameSize) {
1490   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1491   int16_t status;
1492   double rateLB;
1493   double rateUB;
1494   enum ISACBandwidth bandwidthKHz;
1495
1496   if (instISAC->codingMode == 0) {
1497     /* In adaptive mode. */
1498     instISAC->errorCode = ISAC_MODE_MISMATCH;
1499     return -1;
1500   }
1501
1502   /* Check if encoder initiated */
1503   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) !=
1504       BIT_MASK_ENC_INIT) {
1505     instISAC->errorCode = ISAC_ENCODER_NOT_INITIATED;
1506     return -1;
1507   }
1508
1509   if (instISAC->encoderSamplingRateKHz == kIsacWideband) {
1510     /* If the sampling rate is 16kHz then bandwith should be 8kHz,
1511      * regardless of bottleneck. */
1512     bandwidthKHz = isac8kHz;
1513     rateLB = (bottleneckBPS > 32000) ? 32000 : bottleneckBPS;
1514     rateUB = 0;
1515   } else {
1516     if (WebRtcIsac_RateAllocation(bottleneckBPS, &rateLB, &rateUB,
1517                                   &bandwidthKHz) < 0) {
1518       return -1;
1519     }
1520   }
1521
1522   if ((instISAC->encoderSamplingRateKHz == kIsacSuperWideband) &&
1523       (frameSize != 30) &&
1524       (bandwidthKHz != isac8kHz)) {
1525     /* Cannot have 60 ms in super-wideband. */
1526     instISAC->errorCode = ISAC_DISALLOWED_FRAME_LENGTH;
1527     return -1;
1528   }
1529
1530   status = ControlLb(&instISAC->instLB, rateLB, frameSize);
1531   if (status < 0) {
1532     instISAC->errorCode = -status;
1533     return -1;
1534   }
1535   if (bandwidthKHz != isac8kHz) {
1536     status = ControlUb(&(instISAC->instUB), rateUB);
1537     if (status < 0) {
1538       instISAC->errorCode = -status;
1539       return -1;
1540     }
1541   }
1542
1543
1544   /* Check if bandwidth is changing from wideband to super-wideband
1545    * then we have to synch data buffer of lower & upper-band. Also
1546    * clean up the upper-band data buffer. */
1547
1548   if ((instISAC->bandwidthKHz == isac8kHz) && (bandwidthKHz != isac8kHz)) {
1549     memset(instISAC->instUB.ISACencUB_obj.data_buffer_float, 0,
1550            sizeof(float) * (MAX_FRAMESAMPLES + LB_TOTAL_DELAY_SAMPLES));
1551
1552     if (bandwidthKHz == isac12kHz) {
1553       instISAC->instUB.ISACencUB_obj.buffer_index =
1554         instISAC->instLB.ISACencLB_obj.buffer_index;
1555     } else {
1556       instISAC->instUB.ISACencUB_obj.buffer_index =
1557           LB_TOTAL_DELAY_SAMPLES + instISAC->instLB.ISACencLB_obj.buffer_index;
1558
1559       memcpy(&(instISAC->instUB.ISACencUB_obj.lastLPCVec),
1560              WebRtcIsac_kMeanLarUb16, sizeof(double) * UB_LPC_ORDER);
1561     }
1562   }
1563
1564   /* Update the payload limit if the bandwidth is changing. */
1565   if (instISAC->bandwidthKHz != bandwidthKHz) {
1566     instISAC->bandwidthKHz = bandwidthKHz;
1567     UpdatePayloadSizeLimit(instISAC);
1568   }
1569   instISAC->bottleneck = bottleneckBPS;
1570   return 0;
1571 }
1572
1573
1574 /****************************************************************************
1575  * WebRtcIsac_ControlBwe(...)
1576  *
1577  * This function sets the initial values of bottleneck and frame-size if
1578  * iSAC is used in channel-adaptive mode. Through this API, users can
1579  * enforce a frame-size for all values of bottleneck. Then iSAC will not
1580  * automatically change the frame-size.
1581  *
1582  *
1583  * Input:
1584  *        - ISAC_main_inst    : ISAC instance.
1585  *        - rateBPS           : initial value of bottleneck in bits/second
1586  *                              10000 <= rateBPS <= 32000 is accepted
1587  *                              For default bottleneck set rateBPS = 0
1588  *        - frameSizeMs       : number of milliseconds per frame (30 or 60)
1589  *        - enforceFrameSize  : 1 to enforce the given frame-size through out
1590  *                              the adaptation process, 0 to let iSAC change
1591  *                              the frame-size if required.
1592  *
1593  * Return value               : 0 - ok
1594  *                             -1 - Error
1595  */
1596 int16_t WebRtcIsac_ControlBwe(ISACStruct* ISAC_main_inst,
1597                               int32_t bottleneckBPS,
1598                               int16_t frameSizeMs,
1599                               int16_t enforceFrameSize) {
1600   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1601   enum ISACBandwidth bandwidth;
1602
1603    /* Check if encoder initiated */
1604   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) !=
1605       BIT_MASK_ENC_INIT) {
1606     instISAC->errorCode = ISAC_ENCODER_NOT_INITIATED;
1607     return -1;
1608   }
1609
1610   /* Check that we are in channel-adaptive mode, otherwise, return (-1) */
1611   if (instISAC->codingMode != 0) {
1612     instISAC->errorCode = ISAC_MODE_MISMATCH;
1613     return -1;
1614   }
1615   if ((frameSizeMs != 30) &&
1616       (instISAC->encoderSamplingRateKHz == kIsacSuperWideband)) {
1617     return -1;
1618   }
1619
1620   /* Set structure variable if enforceFrameSize is set. ISAC will then
1621    * keep the chosen frame size. */
1622   if (enforceFrameSize != 0) {
1623     instISAC->instLB.ISACencLB_obj.enforceFrameSize = 1;
1624   } else {
1625     instISAC->instLB.ISACencLB_obj.enforceFrameSize = 0;
1626   }
1627
1628   /* Set the initial rate. If the input value is zero then the default intial
1629    * rate is used. Otehrwise, values between 10 to 32 kbps are accepted. */
1630   if (bottleneckBPS != 0) {
1631     double rateLB;
1632     double rateUB;
1633     if (WebRtcIsac_RateAllocation(bottleneckBPS, &rateLB, &rateUB,
1634                                   &bandwidth) < 0) {
1635       return -1;
1636     }
1637     instISAC->bwestimator_obj.send_bw_avg = (float)bottleneckBPS;
1638     instISAC->bandwidthKHz = bandwidth;
1639   }
1640
1641   /* Set the initial frame-size. If 'enforceFrameSize' is set, the frame-size
1642    *  will not change */
1643   if (frameSizeMs != 0) {
1644     if ((frameSizeMs  == 30) || (frameSizeMs == 60)) {
1645       instISAC->instLB.ISACencLB_obj.new_framelength = (FS / 1000) *
1646           frameSizeMs;
1647     } else {
1648       instISAC->errorCode = ISAC_DISALLOWED_FRAME_LENGTH;
1649       return -1;
1650     }
1651   }
1652   return 0;
1653 }
1654
1655
1656 /****************************************************************************
1657  * WebRtcIsac_GetDownLinkBwIndex(...)
1658  *
1659  * This function returns index representing the Bandwidth estimate from
1660  * the other side to this side.
1661  *
1662  * Input:
1663  *        - ISAC_main_inst    : iSAC structure
1664  *
1665  * Output:
1666  *        - bweIndex         : Bandwidth estimate to transmit to other side.
1667  *
1668  */
1669 int16_t WebRtcIsac_GetDownLinkBwIndex(ISACStruct* ISAC_main_inst,
1670                                       int16_t* bweIndex,
1671                                       int16_t* jitterInfo) {
1672   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1673
1674   /* Check if encoder initialized. */
1675   if ((instISAC->initFlag & BIT_MASK_DEC_INIT) !=
1676       BIT_MASK_DEC_INIT) {
1677     instISAC->errorCode = ISAC_ENCODER_NOT_INITIATED;
1678     return -1;
1679   }
1680
1681   /* Call function to get Bandwidth Estimate. */
1682   WebRtcIsac_GetDownlinkBwJitIndexImpl(&(instISAC->bwestimator_obj), bweIndex,
1683                                        jitterInfo,
1684                                        instISAC->decoderSamplingRateKHz);
1685   return 0;
1686 }
1687
1688
1689 /****************************************************************************
1690  * WebRtcIsac_UpdateUplinkBw(...)
1691  *
1692  * This function takes an index representing the Bandwidth estimate from
1693  * this side to other side and updates BWE.
1694  *
1695  * Input:
1696  *        - ISAC_main_inst    : iSAC structure
1697  *        - rateIndex         : Bandwidth estimate from other side.
1698  *
1699  * Return value               : 0 - ok
1700  *                             -1 - index out of range
1701  */
1702 int16_t WebRtcIsac_UpdateUplinkBw(ISACStruct* ISAC_main_inst,
1703                                   int16_t bweIndex) {
1704   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1705   int16_t returnVal;
1706
1707   /* Check if encoder initiated. */
1708   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) !=
1709       BIT_MASK_ENC_INIT) {
1710     instISAC->errorCode = ISAC_ENCODER_NOT_INITIATED;
1711     return -1;
1712   }
1713
1714   /* Call function to get Bandwidth Estimate. */
1715   returnVal = WebRtcIsac_UpdateUplinkBwImpl(
1716                 &(instISAC->bwestimator_obj), bweIndex,
1717                 instISAC->encoderSamplingRateKHz);
1718
1719   if (returnVal < 0) {
1720     instISAC->errorCode = -returnVal;
1721     return -1;
1722   } else {
1723     return 0;
1724   }
1725 }
1726
1727
1728 /****************************************************************************
1729  * WebRtcIsac_ReadBwIndex(...)
1730  *
1731  * This function returns the index of the Bandwidth estimate from the
1732  * bit-stream.
1733  *
1734  * Input:
1735  *        - encoded           : Encoded bit-stream
1736  *
1737  * Output:
1738  *        - frameLength       : Length of frame in packet (in samples)
1739  *        - bweIndex          : Bandwidth estimate in bit-stream
1740  *
1741  */
1742 int16_t WebRtcIsac_ReadBwIndex(const int16_t* encoded,
1743                                int16_t* bweIndex) {
1744   Bitstr streamdata;
1745 #ifndef WEBRTC_ARCH_BIG_ENDIAN
1746   int k;
1747 #endif
1748   int16_t err;
1749
1750   WebRtcIsac_ResetBitstream(&(streamdata));
1751
1752 #ifndef WEBRTC_ARCH_BIG_ENDIAN
1753   for (k = 0; k < 10; k++) {
1754     streamdata.stream[k] = (uint8_t)((encoded[k >> 1] >>
1755         ((k & 1) << 3)) & 0xFF);
1756   }
1757 #else
1758   memcpy(streamdata.stream, encoded, 10);
1759 #endif
1760
1761   /* Decode frame length. */
1762   err = WebRtcIsac_DecodeFrameLen(&streamdata, bweIndex);
1763   if (err < 0) {
1764     return err;
1765   }
1766
1767   /* Decode BW estimation. */
1768   err = WebRtcIsac_DecodeSendBW(&streamdata, bweIndex);
1769   if (err < 0) {
1770     return err;
1771   }
1772
1773   return 0;
1774 }
1775
1776
1777 /****************************************************************************
1778  * WebRtcIsac_ReadFrameLen(...)
1779  *
1780  * This function returns the number of samples the decoder will generate if
1781  * the given payload is decoded.
1782  *
1783  * Input:
1784  *        - encoded           : Encoded bitstream
1785  *
1786  * Output:
1787  *        - frameLength       : Length of frame in packet (in samples)
1788  *
1789  */
1790 int16_t WebRtcIsac_ReadFrameLen(ISACStruct* ISAC_main_inst,
1791                                 const int16_t* encoded,
1792                                 int16_t* frameLength) {
1793   Bitstr streamdata;
1794 #ifndef WEBRTC_ARCH_BIG_ENDIAN
1795   int k;
1796 #endif
1797   int16_t err;
1798   ISACMainStruct* instISAC;
1799
1800   WebRtcIsac_ResetBitstream(&(streamdata));
1801
1802 #ifndef WEBRTC_ARCH_BIG_ENDIAN
1803   for (k = 0; k < 10; k++) {
1804     streamdata.stream[k] = (uint8_t)((encoded[k >> 1] >>
1805                                             ((k & 1) << 3)) & 0xFF);
1806   }
1807 #else
1808   memcpy(streamdata.stream, encoded, 10);
1809 #endif
1810
1811   /* Decode frame length. */
1812   err = WebRtcIsac_DecodeFrameLen(&streamdata, frameLength);
1813   if (err < 0) {
1814     return -1;
1815   }
1816   instISAC = (ISACMainStruct*)ISAC_main_inst;
1817
1818   if (instISAC->decoderSamplingRateKHz == kIsacSuperWideband) {
1819     /* The decoded frame length indicates the number of samples in
1820      * lower-band in this case, multiply by 2 to get the total number
1821      * of samples. */
1822     *frameLength <<= 1;
1823   }
1824   return 0;
1825 }
1826
1827
1828 /*******************************************************************************
1829  * WebRtcIsac_GetNewFrameLen(...)
1830  *
1831  * This function returns the frame length (in samples) of the next packet.
1832  * In the case of channel-adaptive mode, iSAC decides on its frame length based
1833  * on the estimated bottleneck, this AOI allows a user to prepare for the next
1834  * packet (at the encoder).
1835  *
1836  * The primary usage is in CE to make the iSAC works in channel-adaptive mode
1837  *
1838  * Input:
1839  *        - ISAC_main_inst     : iSAC struct
1840  *
1841  * Return Value                : frame lenght in samples
1842  *
1843  */
1844 int16_t WebRtcIsac_GetNewFrameLen(ISACStruct* ISAC_main_inst) {
1845   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1846
1847   /* Return new frame length. */
1848   if (instISAC->in_sample_rate_hz == 16000)
1849     return (instISAC->instLB.ISACencLB_obj.new_framelength);
1850   else if (instISAC->in_sample_rate_hz == 32000)
1851     return ((instISAC->instLB.ISACencLB_obj.new_framelength) * 2);
1852   else
1853     return ((instISAC->instLB.ISACencLB_obj.new_framelength) * 3);
1854 }
1855
1856
1857 /****************************************************************************
1858  * WebRtcIsac_GetErrorCode(...)
1859  *
1860  * This function can be used to check the error code of an iSAC instance.
1861  * When a function returns -1 an error code will be set for that instance.
1862  * The function below extracts the code of the last error that occurred in
1863  * the specified instance.
1864  *
1865  * Input:
1866  *        - ISAC_main_inst    : ISAC instance
1867  *
1868  * Return value               : Error code
1869  */
1870 int16_t WebRtcIsac_GetErrorCode(ISACStruct* ISAC_main_inst) {
1871  return ((ISACMainStruct*)ISAC_main_inst)->errorCode;
1872 }
1873
1874
1875 /****************************************************************************
1876  * WebRtcIsac_GetUplinkBw(...)
1877  *
1878  * This function outputs the target bottleneck of the codec. In
1879  * channel-adaptive mode, the target bottleneck is specified through an in-band
1880  * signalling retrieved by bandwidth estimator.
1881  * In channel-independent, also called instantaneous mode, the target
1882  * bottleneck is provided to the encoder by calling xxx_control(...) (if
1883  * xxx_control is never called, the default values are used.).
1884  * Note that the output is the iSAC internal operating bottleneck which might
1885  * differ slightly from the one provided through xxx_control().
1886  *
1887  * Input:
1888  *        - ISAC_main_inst    : iSAC instance
1889  *
1890  * Output:
1891  *        - *bottleneck       : bottleneck in bits/sec
1892  *
1893  * Return value               : -1 if error happens
1894  *                               0 bit-rates computed correctly.
1895  */
1896 int16_t WebRtcIsac_GetUplinkBw(ISACStruct*  ISAC_main_inst,
1897                                int32_t* bottleneck) {
1898   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1899
1900   if (instISAC->codingMode == 0) {
1901     /* We are in adaptive mode then get the bottleneck from BWE. */
1902     *bottleneck = (int32_t)instISAC->bwestimator_obj.send_bw_avg;
1903   } else {
1904     *bottleneck = instISAC->bottleneck;
1905   }
1906
1907   if ((*bottleneck > 32000) && (*bottleneck < 38000)) {
1908     *bottleneck = 32000;
1909   } else if ((*bottleneck > 45000) && (*bottleneck < 50000)) {
1910     *bottleneck = 45000;
1911   } else if (*bottleneck > 56000) {
1912     *bottleneck = 56000;
1913   }
1914   return 0;
1915 }
1916
1917
1918 /******************************************************************************
1919  * WebRtcIsac_SetMaxPayloadSize(...)
1920  *
1921  * This function sets a limit for the maximum payload size of iSAC. The same
1922  * value is used both for 30 and 60 ms packets. If the encoder sampling rate
1923  * is 16 kHz the maximum payload size is between 120 and 400 bytes. If the
1924  * encoder sampling rate is 32 kHz the maximum payload size is between 120
1925  * and 600 bytes.
1926  *
1927  * ---------------
1928  * IMPORTANT NOTES
1929  * ---------------
1930  * The size of a packet is limited to the minimum of 'max-payload-size' and
1931  * 'max-rate.' For instance, let's assume the max-payload-size is set to
1932  * 170 bytes, and max-rate is set to 40 kbps. Note that a limit of 40 kbps
1933  * translates to 150 bytes for 30ms frame-size & 300 bytes for 60ms
1934  * frame-size. Then a packet with a frame-size of 30 ms is limited to 150,
1935  * i.e. min(170, 150), and a packet with 60 ms frame-size is limited to
1936  * 170 bytes, i.e. min(170, 300).
1937  *
1938  * Input:
1939  *        - ISAC_main_inst    : iSAC instance
1940  *        - maxPayloadBytes   : maximum size of the payload in bytes
1941  *                              valid values are between 100 and 400 bytes
1942  *                              if encoder sampling rate is 16 kHz. For
1943  *                              32 kHz encoder sampling rate valid values
1944  *                              are between 100 and 600 bytes.
1945  *
1946  * Return value               : 0 if successful
1947  *                             -1 if error happens
1948  */
1949 int16_t WebRtcIsac_SetMaxPayloadSize(ISACStruct* ISAC_main_inst,
1950                                      int16_t maxPayloadBytes) {
1951   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
1952   int16_t status = 0;
1953
1954   /* Check if encoder initiated */
1955   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) !=
1956       BIT_MASK_ENC_INIT) {
1957     instISAC->errorCode = ISAC_ENCODER_NOT_INITIATED;
1958     return -1;
1959   }
1960
1961   if (instISAC->encoderSamplingRateKHz == kIsacSuperWideband) {
1962     /* Sanity check. */
1963     if (maxPayloadBytes < 120) {
1964       /* 'maxRate' is out of valid range
1965        * set to the acceptable value and return -1. */
1966       maxPayloadBytes = 120;
1967       status = -1;
1968     }
1969
1970     /* sanity check */
1971     if (maxPayloadBytes > STREAM_SIZE_MAX) {
1972       /* maxRate is out of valid range,
1973        * set to the acceptable value and return -1. */
1974       maxPayloadBytes = STREAM_SIZE_MAX;
1975       status = -1;
1976     }
1977   } else {
1978     if (maxPayloadBytes < 120) {
1979       /* Max payload-size is out of valid range
1980        * set to the acceptable value and return -1. */
1981       maxPayloadBytes = 120;
1982       status = -1;
1983     }
1984     if (maxPayloadBytes > STREAM_SIZE_MAX_60) {
1985       /* Max payload-size is out of valid range
1986        * set to the acceptable value and return -1. */
1987       maxPayloadBytes = STREAM_SIZE_MAX_60;
1988       status = -1;
1989     }
1990   }
1991   instISAC->maxPayloadSizeBytes = maxPayloadBytes;
1992   UpdatePayloadSizeLimit(instISAC);
1993   return status;
1994 }
1995
1996
1997 /******************************************************************************
1998  * WebRtcIsac_SetMaxRate(...)
1999  *
2000  * This function sets the maximum rate which the codec may not exceed for
2001  * any signal packet. The maximum rate is defined and payload-size per
2002  * frame-size in bits per second.
2003  *
2004  * The codec has a maximum rate of 53400 bits per second (200 bytes per 30
2005  * ms) if the encoder sampling rate is 16kHz, and 160 kbps (600 bytes/30 ms)
2006  * if the encoder sampling rate is 32 kHz.
2007  *
2008  * It is possible to set a maximum rate between 32000 and 53400 bits/sec
2009  * in wideband mode, and 32000 to 160000 bits/sec in super-wideband mode.
2010  *
2011  * ---------------
2012  * IMPORTANT NOTES
2013  * ---------------
2014  * The size of a packet is limited to the minimum of 'max-payload-size' and
2015  * 'max-rate.' For instance, let's assume the max-payload-size is set to
2016  * 170 bytes, and max-rate is set to 40 kbps. Note that a limit of 40 kbps
2017  * translates to 150 bytes for 30ms frame-size & 300 bytes for 60ms
2018  * frame-size. Then a packet with a frame-size of 30 ms is limited to 150,
2019  * i.e. min(170, 150), and a packet with 60 ms frame-size is limited to
2020  * 170 bytes, min(170, 300).
2021  *
2022  * Input:
2023  *        - ISAC_main_inst    : iSAC instance
2024  *        - maxRate           : maximum rate in bits per second,
2025  *                              valid values are 32000 to 53400 bits/sec in
2026  *                              wideband mode, and 32000 to 160000 bits/sec in
2027  *                              super-wideband mode.
2028  *
2029  * Return value               : 0 if successful
2030  *                             -1 if error happens
2031  */
2032 int16_t WebRtcIsac_SetMaxRate(ISACStruct* ISAC_main_inst,
2033                               int32_t maxRate) {
2034   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
2035   int16_t maxRateInBytesPer30Ms;
2036   int16_t status = 0;
2037
2038   /* check if encoder initiated */
2039   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) != BIT_MASK_ENC_INIT) {
2040     instISAC->errorCode = ISAC_ENCODER_NOT_INITIATED;
2041     return -1;
2042   }
2043   /* Calculate maximum number of bytes per 30 msec packets for the
2044      given maximum rate. Multiply with 30/1000 to get number of
2045      bits per 30 ms, divide by 8 to get number of bytes per 30 ms:
2046      maxRateInBytes = floor((maxRate * 30/1000) / 8); */
2047   maxRateInBytesPer30Ms = (int16_t)(maxRate * 3 / 800);
2048
2049   if (instISAC->encoderSamplingRateKHz == kIsacWideband) {
2050     if (maxRate < 32000) {
2051       /* 'maxRate' is out of valid range.
2052        * Set to the acceptable value and return -1. */
2053       maxRateInBytesPer30Ms = 120;
2054       status = -1;
2055     }
2056
2057     if (maxRate > 53400) {
2058       /* 'maxRate' is out of valid range.
2059        * Set to the acceptable value and return -1. */
2060       maxRateInBytesPer30Ms = 200;
2061       status = -1;
2062     }
2063   } else {
2064     if (maxRateInBytesPer30Ms < 120) {
2065       /* 'maxRate' is out of valid range
2066        * Set to the acceptable value and return -1. */
2067       maxRateInBytesPer30Ms = 120;
2068       status = -1;
2069     }
2070
2071     if (maxRateInBytesPer30Ms > STREAM_SIZE_MAX) {
2072       /* 'maxRate' is out of valid range.
2073        * Set to the acceptable value and return -1. */
2074       maxRateInBytesPer30Ms = STREAM_SIZE_MAX;
2075       status = -1;
2076     }
2077   }
2078   instISAC->maxRateBytesPer30Ms = maxRateInBytesPer30Ms;
2079   UpdatePayloadSizeLimit(instISAC);
2080   return status;
2081 }
2082
2083
2084 /****************************************************************************
2085  * WebRtcIsac_GetRedPayload(...)
2086  *
2087  * This function populates "encoded" with the redundant payload of the recently
2088  * encodedframe. This function has to be called once that WebRtcIsac_Encode(...)
2089  * returns a positive value. Regardless of the frame-size this function will
2090  * be called only once after encoding is completed. The bit-stream is
2091  * targeted for 16000 bit/sec.
2092  *
2093  * Input:
2094  *        - ISAC_main_inst    : iSAC struct
2095  *
2096  * Output:
2097  *        - encoded           : the encoded data vector
2098  *
2099  *
2100  * Return value               : >0 - Length (in bytes) of coded data
2101  *                            : -1 - Error
2102  */
2103 int16_t WebRtcIsac_GetRedPayload(ISACStruct* ISAC_main_inst,
2104                                  int16_t* encoded) {
2105   Bitstr iSACBitStreamInst;
2106   int16_t streamLenLB;
2107   int16_t streamLenUB;
2108   int16_t streamLen;
2109   int16_t totalLenUB;
2110   uint8_t* ptrEncodedUW8 = (uint8_t*)encoded;
2111   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
2112 #ifndef WEBRTC_ARCH_BIG_ENDIAN
2113   int k;
2114 #endif
2115
2116   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) !=
2117       BIT_MASK_ENC_INIT) {
2118     instISAC->errorCode = ISAC_ENCODER_NOT_INITIATED;
2119   }
2120
2121   WebRtcIsac_ResetBitstream(&(iSACBitStreamInst));
2122
2123   streamLenLB = WebRtcIsac_EncodeStoredDataLb(
2124                   &instISAC->instLB.ISACencLB_obj.SaveEnc_obj,
2125                   &iSACBitStreamInst,
2126                   instISAC->instLB.ISACencLB_obj.lastBWIdx,
2127                   RCU_TRANSCODING_SCALE);
2128   if (streamLenLB < 0) {
2129     return -1;
2130   }
2131
2132   /* convert from bytes to int16_t. */
2133   memcpy(ptrEncodedUW8, iSACBitStreamInst.stream, streamLenLB);
2134   streamLen = streamLenLB;
2135   if (instISAC->bandwidthKHz == isac8kHz) {
2136     return streamLenLB;
2137   }
2138
2139   streamLenUB = WebRtcIsac_GetRedPayloadUb(
2140                   &instISAC->instUB.ISACencUB_obj.SaveEnc_obj,
2141                   &iSACBitStreamInst, instISAC->bandwidthKHz);
2142   if (streamLenUB < 0) {
2143     /* An error has happened but this is not the error due to a
2144      * bit-stream larger than the limit. */
2145     return -1;
2146   }
2147
2148   /* We have one byte to write the total length of the upper-band.
2149    * The length includes the bit-stream length, check-sum and the
2150    * single byte where the length is written to. This is according to
2151    * iSAC wideband and how the "garbage" is dealt. */
2152   totalLenUB = streamLenUB + 1 + LEN_CHECK_SUM_WORD8;
2153   if (totalLenUB > 255) {
2154     streamLenUB = 0;
2155   }
2156
2157   /* Generate CRC if required. */
2158   if ((instISAC->bandwidthKHz != isac8kHz) &&
2159       (streamLenUB > 0)) {
2160     uint32_t crc;
2161     streamLen += totalLenUB;
2162     ptrEncodedUW8[streamLenLB] = (uint8_t)totalLenUB;
2163     memcpy(&ptrEncodedUW8[streamLenLB + 1], iSACBitStreamInst.stream,
2164            streamLenUB);
2165
2166     WebRtcIsac_GetCrc((int16_t*)(&(ptrEncodedUW8[streamLenLB + 1])),
2167                       streamLenUB, &crc);
2168 #ifndef WEBRTC_ARCH_BIG_ENDIAN
2169     for (k = 0; k < LEN_CHECK_SUM_WORD8; k++) {
2170       ptrEncodedUW8[streamLen - LEN_CHECK_SUM_WORD8 + k] =
2171         (uint8_t)((crc >> (24 - k * 8)) & 0xFF);
2172     }
2173 #else
2174     memcpy(&ptrEncodedUW8[streamLenLB + streamLenUB + 1], &crc,
2175            LEN_CHECK_SUM_WORD8);
2176 #endif
2177   }
2178   return streamLen;
2179 }
2180
2181
2182 /****************************************************************************
2183  * WebRtcIsac_version(...)
2184  *
2185  * This function returns the version number.
2186  *
2187  * Output:
2188  *        - version      : Pointer to character string
2189  *
2190  */
2191 void WebRtcIsac_version(char* version) {
2192   strcpy(version, "4.3.0");
2193 }
2194
2195
2196 /******************************************************************************
2197  * WebRtcIsac_SetEncSampRate()
2198  * This function sets the sampling rate of the encoder. Initialization of the
2199  * encoder WILL NOT overwrite the sampling rate of the encoder. The default
2200  * value is 16 kHz which is set when the instance is created. The encoding-mode
2201  * and the bottleneck remain unchanged by this call, however, the maximum rate
2202  * and maximum payload-size will be reset to their default values.
2203  *
2204  * NOTE:
2205  * The maximum internal sampling rate is 32 kHz. If the encoder sample rate is
2206  * set to 48 kHz the input is expected to be at 48 kHz but will be resampled to
2207  * 32 kHz before any further processing.
2208  * This mode is created for compatibility with full-band codecs if iSAC is used
2209  * in dual-streaming. See SetDecSampleRate() for sampling rates at the decoder.
2210  *
2211  * Input:
2212  *        - ISAC_main_inst    : iSAC instance
2213  *        - sample_rate_hz    : sampling rate in Hertz, valid values are 16000,
2214  *                              32000 and 48000.
2215  *
2216  * Return value               : 0 if successful
2217  *                             -1 if failed.
2218  */
2219 int16_t WebRtcIsac_SetEncSampRate(ISACStruct* ISAC_main_inst,
2220                                   uint16_t sample_rate_hz) {
2221   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
2222   enum IsacSamplingRate encoder_operational_rate;
2223
2224   if ((sample_rate_hz != 16000) && (sample_rate_hz != 32000) &&
2225       (sample_rate_hz != 48000)) {
2226     /* Sampling Frequency is not supported. */
2227     instISAC->errorCode = ISAC_UNSUPPORTED_SAMPLING_FREQUENCY;
2228     return -1;
2229   }
2230   if (sample_rate_hz == 16000) {
2231     encoder_operational_rate = kIsacWideband;
2232   } else {
2233     encoder_operational_rate = kIsacSuperWideband;
2234   }
2235
2236   if ((instISAC->initFlag & BIT_MASK_ENC_INIT) !=
2237       BIT_MASK_ENC_INIT) {
2238     if (encoder_operational_rate == kIsacWideband) {
2239       instISAC->bandwidthKHz = isac8kHz;
2240     } else {
2241       instISAC->bandwidthKHz = isac16kHz;
2242     }
2243   } else {
2244     ISACUBStruct* instUB = &(instISAC->instUB);
2245     ISACLBStruct* instLB = &(instISAC->instLB);
2246     int32_t bottleneck = instISAC->bottleneck;
2247     int16_t codingMode = instISAC->codingMode;
2248     int16_t frameSizeMs = instLB->ISACencLB_obj.new_framelength /
2249         (FS / 1000);
2250
2251     if ((encoder_operational_rate == kIsacWideband) &&
2252         (instISAC->encoderSamplingRateKHz == kIsacSuperWideband)) {
2253       /* Changing from super-wideband to wideband.
2254        * we don't need to re-initialize the encoder of the lower-band. */
2255       instISAC->bandwidthKHz = isac8kHz;
2256       if (codingMode == 1) {
2257         ControlLb(instLB,
2258                   (bottleneck > 32000) ? 32000 : bottleneck, FRAMESIZE);
2259       }
2260       instISAC->maxPayloadSizeBytes = STREAM_SIZE_MAX_60;
2261       instISAC->maxRateBytesPer30Ms = STREAM_SIZE_MAX_30;
2262     } else if ((encoder_operational_rate == kIsacSuperWideband) &&
2263                (instISAC->encoderSamplingRateKHz == kIsacWideband)) {
2264       double bottleneckLB = 0;
2265       double bottleneckUB = 0;
2266       if (codingMode == 1) {
2267         WebRtcIsac_RateAllocation(bottleneck, &bottleneckLB, &bottleneckUB,
2268                                   &(instISAC->bandwidthKHz));
2269       }
2270
2271       instISAC->bandwidthKHz = isac16kHz;
2272       instISAC->maxPayloadSizeBytes = STREAM_SIZE_MAX;
2273       instISAC->maxRateBytesPer30Ms = STREAM_SIZE_MAX;
2274
2275       EncoderInitLb(instLB, codingMode, encoder_operational_rate);
2276       EncoderInitUb(instUB, instISAC->bandwidthKHz);
2277
2278       memset(instISAC->analysisFBState1, 0,
2279              FB_STATE_SIZE_WORD32 * sizeof(int32_t));
2280       memset(instISAC->analysisFBState2, 0,
2281              FB_STATE_SIZE_WORD32 * sizeof(int32_t));
2282
2283       if (codingMode == 1) {
2284         instISAC->bottleneck = bottleneck;
2285         ControlLb(instLB, bottleneckLB,
2286                   (instISAC->bandwidthKHz == isac8kHz) ? frameSizeMs:FRAMESIZE);
2287         if (instISAC->bandwidthKHz > isac8kHz) {
2288           ControlUb(instUB, bottleneckUB);
2289         }
2290       } else {
2291         instLB->ISACencLB_obj.enforceFrameSize = 0;
2292         instLB->ISACencLB_obj.new_framelength = FRAMESAMPLES;
2293       }
2294     }
2295   }
2296   instISAC->encoderSamplingRateKHz = encoder_operational_rate;
2297   instISAC->in_sample_rate_hz = sample_rate_hz;
2298   return 0;
2299 }
2300
2301
2302 /******************************************************************************
2303  * WebRtcIsac_SetDecSampRate()
2304  * This function sets the sampling rate of the decoder. Initialization of the
2305  * decoder WILL NOT overwrite the sampling rate of the encoder. The default
2306  * value is 16 kHz which is set when the instance is created.
2307  *
2308  * Input:
2309  *        - ISAC_main_inst    : iSAC instance
2310  *        - sample_rate_hz    : sampling rate in Hertz, valid values are 16000
2311  *                              and 32000.
2312  *
2313  * Return value               : 0 if successful
2314  *                             -1 if failed.
2315  */
2316 int16_t WebRtcIsac_SetDecSampRate(ISACStruct* ISAC_main_inst,
2317                                   uint16_t sample_rate_hz) {
2318   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
2319   enum IsacSamplingRate decoder_operational_rate;
2320
2321   if (sample_rate_hz == 16000) {
2322     decoder_operational_rate = kIsacWideband;
2323   } else if (sample_rate_hz == 32000) {
2324     decoder_operational_rate = kIsacSuperWideband;
2325   } else {
2326     /* Sampling Frequency is not supported. */
2327     instISAC->errorCode = ISAC_UNSUPPORTED_SAMPLING_FREQUENCY;
2328     return -1;
2329   }
2330
2331   if ((instISAC->decoderSamplingRateKHz == kIsacWideband) &&
2332         (decoder_operational_rate == kIsacSuperWideband)) {
2333       /* Switching from wideband to super-wideband at the decoder
2334        * we need to reset the filter-bank and initialize upper-band decoder. */
2335       memset(instISAC->synthesisFBState1, 0,
2336              FB_STATE_SIZE_WORD32 * sizeof(int32_t));
2337       memset(instISAC->synthesisFBState2, 0,
2338              FB_STATE_SIZE_WORD32 * sizeof(int32_t));
2339
2340       if (DecoderInitUb(&(instISAC->instUB)) < 0) {
2341         return -1;
2342       }
2343   }
2344   instISAC->decoderSamplingRateKHz = decoder_operational_rate;
2345   return 0;
2346 }
2347
2348
2349 /******************************************************************************
2350  * WebRtcIsac_EncSampRate()
2351  *
2352  * Input:
2353  *        - ISAC_main_inst    : iSAC instance
2354  *
2355  * Return value               : sampling rate in Hertz. The input to encoder
2356  *                              is expected to be sampled in this rate.
2357  *
2358  */
2359 uint16_t WebRtcIsac_EncSampRate(ISACStruct* ISAC_main_inst) {
2360   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
2361   return instISAC->in_sample_rate_hz;
2362 }
2363
2364
2365 /******************************************************************************
2366  * WebRtcIsac_DecSampRate()
2367  * Return the sampling rate of the decoded audio.
2368  *
2369  * Input:
2370  *        - ISAC_main_inst    : iSAC instance
2371  *
2372  * Return value               : sampling rate in Hertz. Decoder output is
2373  *                              sampled at this rate.
2374  *
2375  */
2376 uint16_t WebRtcIsac_DecSampRate(ISACStruct* ISAC_main_inst) {
2377   ISACMainStruct* instISAC = (ISACMainStruct*)ISAC_main_inst;
2378   return instISAC->decoderSamplingRateKHz == kIsacWideband ? 16000 : 32000;
2379 }