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