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