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