Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / third_party / webrtc / modules / audio_coding / codecs / isac / fix / source / isacfix.c
1 /*
2  *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 /*
12  * isacfix.c
13  *
14  * This C file contains the functions for the ISAC API
15  *
16  */
17
18 #include "webrtc/modules/audio_coding/codecs/isac/fix/interface/isacfix.h"
19
20 #include <assert.h>
21 #include <stdlib.h>
22
23 #include "webrtc/modules/audio_coding/codecs/isac/fix/source/bandwidth_estimator.h"
24 #include "webrtc/modules/audio_coding/codecs/isac/fix/source/codec.h"
25 #include "webrtc/modules/audio_coding/codecs/isac/fix/source/entropy_coding.h"
26 #include "webrtc/modules/audio_coding/codecs/isac/fix/source/filterbank_internal.h"
27 #include "webrtc/modules/audio_coding/codecs/isac/fix/source/lpc_masking_model.h"
28 #include "webrtc/modules/audio_coding/codecs/isac/fix/source/structs.h"
29 #include "webrtc/system_wrappers/interface/cpu_features_wrapper.h"
30
31 // Declare function pointers.
32 FilterMaLoopFix WebRtcIsacfix_FilterMaLoopFix;
33 Spec2Time WebRtcIsacfix_Spec2Time;
34 Time2Spec WebRtcIsacfix_Time2Spec;
35 MatrixProduct1 WebRtcIsacfix_MatrixProduct1;
36 MatrixProduct2 WebRtcIsacfix_MatrixProduct2;
37
38 /* This method assumes that |stream_size_bytes| is in valid range,
39  * i.e. >= 0 && <=  STREAM_MAXW16_60MS
40  */
41 static void InitializeDecoderBitstream(int stream_size_bytes,
42                                        Bitstr_dec* bitstream) {
43   bitstream->W_upper = 0xFFFFFFFF;
44   bitstream->streamval = 0;
45   bitstream->stream_index = 0;
46   bitstream->full = 1;
47   bitstream->stream_size = (stream_size_bytes + 1) >> 1;
48   memset(bitstream->stream, 0, sizeof(bitstream->stream));
49 }
50
51 /**************************************************************************
52  * WebRtcIsacfix_AssignSize(...)
53  *
54  * Functions used when malloc is not allowed
55  * Returns number of bytes needed to allocate for iSAC struct.
56  *
57  */
58
59 int16_t WebRtcIsacfix_AssignSize(int *sizeinbytes) {
60   *sizeinbytes=sizeof(ISACFIX_SubStruct)*2/sizeof(int16_t);
61   return(0);
62 }
63
64 /***************************************************************************
65  * WebRtcIsacfix_Assign(...)
66  *
67  * Functions used when malloc is not allowed
68  * Place struct at given address
69  *
70  * If successful, Return 0, else Return -1
71  */
72
73 int16_t WebRtcIsacfix_Assign(ISACFIX_MainStruct **inst, void *ISACFIX_inst_Addr) {
74   if (ISACFIX_inst_Addr!=NULL) {
75     *inst = (ISACFIX_MainStruct*)ISACFIX_inst_Addr;
76     (*(ISACFIX_SubStruct**)inst)->errorcode = 0;
77     (*(ISACFIX_SubStruct**)inst)->initflag = 0;
78     (*(ISACFIX_SubStruct**)inst)->ISACenc_obj.SaveEnc_ptr = NULL;
79     return(0);
80   } else {
81     return(-1);
82   }
83 }
84
85
86 #ifndef ISACFIX_NO_DYNAMIC_MEM
87
88 /****************************************************************************
89  * WebRtcIsacfix_Create(...)
90  *
91  * This function creates a ISAC instance, which will contain the state
92  * information for one coding/decoding channel.
93  *
94  * Input:
95  *      - *ISAC_main_inst   : a pointer to the coder instance.
96  *
97  * Return value             :  0 - Ok
98  *                            -1 - Error
99  */
100
101 int16_t WebRtcIsacfix_Create(ISACFIX_MainStruct **ISAC_main_inst)
102 {
103   ISACFIX_SubStruct *tempo;
104   tempo = malloc(1 * sizeof(ISACFIX_SubStruct));
105   *ISAC_main_inst = (ISACFIX_MainStruct *)tempo;
106   if (*ISAC_main_inst!=NULL) {
107     (*(ISACFIX_SubStruct**)ISAC_main_inst)->errorcode = 0;
108     (*(ISACFIX_SubStruct**)ISAC_main_inst)->initflag = 0;
109     (*(ISACFIX_SubStruct**)ISAC_main_inst)->ISACenc_obj.SaveEnc_ptr = NULL;
110     WebRtcSpl_Init();
111     return(0);
112   } else {
113     return(-1);
114   }
115 }
116
117
118 /****************************************************************************
119  * WebRtcIsacfix_CreateInternal(...)
120  *
121  * This function creates the memory that is used to store data in the encoder
122  *
123  * Input:
124  *      - *ISAC_main_inst   : a pointer to the coder instance.
125  *
126  * Return value             :  0 - Ok
127  *                            -1 - Error
128  */
129
130 int16_t WebRtcIsacfix_CreateInternal(ISACFIX_MainStruct *ISAC_main_inst)
131 {
132   ISACFIX_SubStruct *ISAC_inst;
133
134   /* typecast pointer to real structure */
135   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
136
137   /* Allocate memory for storing encoder data */
138   ISAC_inst->ISACenc_obj.SaveEnc_ptr = malloc(1 * sizeof(ISAC_SaveEncData_t));
139
140   if (ISAC_inst->ISACenc_obj.SaveEnc_ptr!=NULL) {
141     return(0);
142   } else {
143     return(-1);
144   }
145 }
146
147
148 #endif
149
150
151
152 /****************************************************************************
153  * WebRtcIsacfix_Free(...)
154  *
155  * This function frees the ISAC instance created at the beginning.
156  *
157  * Input:
158  *      - ISAC_main_inst    : a ISAC instance.
159  *
160  * Return value             :  0 - Ok
161  *                            -1 - Error
162  */
163
164 int16_t WebRtcIsacfix_Free(ISACFIX_MainStruct *ISAC_main_inst)
165 {
166   free(ISAC_main_inst);
167   return(0);
168 }
169
170 /****************************************************************************
171  * WebRtcIsacfix_FreeInternal(...)
172  *
173  * This function frees the internal memory for storing encoder data.
174  *
175  * Input:
176  *       - ISAC_main_inst    : a ISAC instance.
177  *
178  * Return value              :  0 - Ok
179  *                             -1 - Error
180  */
181
182 int16_t WebRtcIsacfix_FreeInternal(ISACFIX_MainStruct *ISAC_main_inst)
183 {
184   ISACFIX_SubStruct *ISAC_inst;
185
186   /* typecast pointer to real structure */
187   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
188
189   /* Release memory */
190   free(ISAC_inst->ISACenc_obj.SaveEnc_ptr);
191
192   return(0);
193 }
194
195 /****************************************************************************
196  * WebRtcIsacfix_InitNeon(...)
197  *
198  * This function initializes function pointers for ARM Neon platform.
199  */
200
201 #if (defined WEBRTC_DETECT_ARM_NEON || defined WEBRTC_ARCH_ARM_NEON)
202 static void WebRtcIsacfix_InitNeon(void) {
203   WebRtcIsacfix_AutocorrFix = WebRtcIsacfix_AutocorrNeon;
204   WebRtcIsacfix_FilterMaLoopFix = WebRtcIsacfix_FilterMaLoopNeon;
205   WebRtcIsacfix_Spec2Time = WebRtcIsacfix_Spec2TimeNeon;
206   WebRtcIsacfix_Time2Spec = WebRtcIsacfix_Time2SpecNeon;
207   WebRtcIsacfix_CalculateResidualEnergy =
208       WebRtcIsacfix_CalculateResidualEnergyNeon;
209   WebRtcIsacfix_AllpassFilter2FixDec16 =
210       WebRtcIsacfix_AllpassFilter2FixDec16Neon;
211   WebRtcIsacfix_MatrixProduct1 = WebRtcIsacfix_MatrixProduct1Neon;
212   WebRtcIsacfix_MatrixProduct2 = WebRtcIsacfix_MatrixProduct2Neon;
213 }
214 #endif
215
216 /****************************************************************************
217  * WebRtcIsacfix_InitMIPS(...)
218  *
219  * This function initializes function pointers for MIPS platform.
220  */
221
222 #if defined(MIPS32_LE)
223 static void WebRtcIsacfix_InitMIPS(void) {
224   WebRtcIsacfix_AutocorrFix = WebRtcIsacfix_AutocorrMIPS;
225   WebRtcIsacfix_FilterMaLoopFix = WebRtcIsacfix_FilterMaLoopMIPS;
226   WebRtcIsacfix_Spec2Time = WebRtcIsacfix_Spec2TimeMIPS;
227   WebRtcIsacfix_Time2Spec = WebRtcIsacfix_Time2SpecMIPS;
228   WebRtcIsacfix_MatrixProduct1 = WebRtcIsacfix_MatrixProduct1MIPS;
229   WebRtcIsacfix_MatrixProduct2 = WebRtcIsacfix_MatrixProduct2MIPS;
230 #if defined(MIPS_DSP_R1_LE)
231   WebRtcIsacfix_AllpassFilter2FixDec16 =
232       WebRtcIsacfix_AllpassFilter2FixDec16MIPS;
233   WebRtcIsacfix_HighpassFilterFixDec32 =
234       WebRtcIsacfix_HighpassFilterFixDec32MIPS;
235 #endif
236 #if defined(MIPS_DSP_R2_LE)
237   WebRtcIsacfix_CalculateResidualEnergy =
238       WebRtcIsacfix_CalculateResidualEnergyMIPS;
239 #endif
240 }
241 #endif
242
243 /****************************************************************************
244  * WebRtcIsacfix_EncoderInit(...)
245  *
246  * This function initializes a ISAC instance prior to the encoder calls.
247  *
248  * Input:
249  *      - ISAC_main_inst    : ISAC instance.
250  *      - CodingMode        : 0 -> Bit rate and frame length are automatically
251  *                                 adjusted to available bandwidth on
252  *                                 transmission channel.
253  *                            1 -> User sets a frame length and a target bit
254  *                                 rate which is taken as the maximum short-term
255  *                                 average bit rate.
256  *
257  * Return value             :  0 - Ok
258  *                            -1 - Error
259  */
260
261 int16_t WebRtcIsacfix_EncoderInit(ISACFIX_MainStruct *ISAC_main_inst,
262                                   int16_t  CodingMode)
263 {
264   int k;
265   int16_t statusInit;
266   ISACFIX_SubStruct *ISAC_inst;
267
268   statusInit = 0;
269   /* typecast pointer to rela structure */
270   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
271
272   /* flag encoder init */
273   ISAC_inst->initflag |= 2;
274
275   if (CodingMode == 0)
276     /* Adaptive mode */
277     ISAC_inst->ISACenc_obj.new_framelength  = INITIAL_FRAMESAMPLES;
278   else if (CodingMode == 1)
279     /* Instantaneous mode */
280     ISAC_inst->ISACenc_obj.new_framelength = 480;    /* default for I-mode */
281   else {
282     ISAC_inst->errorcode = ISAC_DISALLOWED_CODING_MODE;
283     statusInit = -1;
284   }
285
286   ISAC_inst->CodingMode = CodingMode;
287
288   WebRtcIsacfix_InitMaskingEnc(&ISAC_inst->ISACenc_obj.maskfiltstr_obj);
289   WebRtcIsacfix_InitPreFilterbank(&ISAC_inst->ISACenc_obj.prefiltbankstr_obj);
290   WebRtcIsacfix_InitPitchFilter(&ISAC_inst->ISACenc_obj.pitchfiltstr_obj);
291   WebRtcIsacfix_InitPitchAnalysis(&ISAC_inst->ISACenc_obj.pitchanalysisstr_obj);
292
293
294   WebRtcIsacfix_InitBandwidthEstimator(&ISAC_inst->bwestimator_obj);
295   WebRtcIsacfix_InitRateModel(&ISAC_inst->ISACenc_obj.rate_data_obj);
296
297
298   ISAC_inst->ISACenc_obj.buffer_index   = 0;
299   ISAC_inst->ISACenc_obj.frame_nb    = 0;
300   ISAC_inst->ISACenc_obj.BottleNeck      = 32000; /* default for I-mode */
301   ISAC_inst->ISACenc_obj.MaxDelay    = 10;    /* default for I-mode */
302   ISAC_inst->ISACenc_obj.current_framesamples = 0;
303   ISAC_inst->ISACenc_obj.s2nr     = 0;
304   ISAC_inst->ISACenc_obj.MaxBits    = 0;
305   ISAC_inst->ISACenc_obj.bitstr_seed   = 4447;
306   ISAC_inst->ISACenc_obj.payloadLimitBytes30  = STREAM_MAXW16_30MS << 1;
307   ISAC_inst->ISACenc_obj.payloadLimitBytes60  = STREAM_MAXW16_60MS << 1;
308   ISAC_inst->ISACenc_obj.maxPayloadBytes      = STREAM_MAXW16_60MS << 1;
309   ISAC_inst->ISACenc_obj.maxRateInBytes       = STREAM_MAXW16_30MS << 1;
310   ISAC_inst->ISACenc_obj.enforceFrameSize     = 0;
311
312   /* Init the bistream data area to zero */
313   for (k=0; k<STREAM_MAXW16_60MS; k++){
314     ISAC_inst->ISACenc_obj.bitstr_obj.stream[k] = 0;
315   }
316
317 #ifdef WEBRTC_ISAC_FIX_NB_CALLS_ENABLED
318   WebRtcIsacfix_InitPostFilterbank(&ISAC_inst->ISACenc_obj.interpolatorstr_obj);
319 #endif
320
321   // Initiaze function pointers.
322   WebRtcIsacfix_AutocorrFix = WebRtcIsacfix_AutocorrC;
323   WebRtcIsacfix_FilterMaLoopFix = WebRtcIsacfix_FilterMaLoopC;
324   WebRtcIsacfix_CalculateResidualEnergy =
325       WebRtcIsacfix_CalculateResidualEnergyC;
326   WebRtcIsacfix_AllpassFilter2FixDec16 = WebRtcIsacfix_AllpassFilter2FixDec16C;
327   WebRtcIsacfix_HighpassFilterFixDec32 = WebRtcIsacfix_HighpassFilterFixDec32C;
328   WebRtcIsacfix_Time2Spec = WebRtcIsacfix_Time2SpecC;
329   WebRtcIsacfix_Spec2Time = WebRtcIsacfix_Spec2TimeC;
330   WebRtcIsacfix_MatrixProduct1 = WebRtcIsacfix_MatrixProduct1C;
331   WebRtcIsacfix_MatrixProduct2 = WebRtcIsacfix_MatrixProduct2C;
332
333 #ifdef WEBRTC_DETECT_ARM_NEON
334   if ((WebRtc_GetCPUFeaturesARM() & kCPUFeatureNEON) != 0) {
335     WebRtcIsacfix_InitNeon();
336   }
337 #elif defined(WEBRTC_ARCH_ARM_NEON)
338   WebRtcIsacfix_InitNeon();
339 #endif
340
341 #if defined(MIPS32_LE)
342   WebRtcIsacfix_InitMIPS();
343 #endif
344
345   return statusInit;
346 }
347
348 /* Read the given number of bytes of big-endian 16-bit integers from |src| and
349    write them to |dest| in host endian. If |nbytes| is odd, the number of
350    output elements is rounded up, and the least significant byte of the last
351    element is set to 0. */
352 static void read_be16(const uint8_t* src, size_t nbytes, uint16_t* dest) {
353   size_t i;
354   for (i = 0; i < nbytes / 2; ++i)
355     dest[i] = src[2 * i] << 8 | src[2 * i + 1];
356   if (nbytes % 2 == 1)
357     dest[nbytes / 2] = src[nbytes - 1] << 8;
358 }
359
360 /* Read the given number of bytes of host-endian 16-bit integers from |src| and
361    write them to |dest| in big endian. If |nbytes| is odd, the number of source
362    elements is rounded up (but only the most significant byte of the last
363    element is used), and the number of output bytes written will be
364    nbytes + 1. */
365 static void write_be16(const uint16_t* src, size_t nbytes, uint8_t* dest) {
366   size_t i;
367   for (i = 0; i < nbytes / 2; ++i) {
368     dest[2 * i] = src[i] >> 8;
369     dest[2 * i + 1] = src[i];
370   }
371   if (nbytes % 2 == 1) {
372     dest[nbytes - 1] = src[nbytes / 2] >> 8;
373     dest[nbytes] = 0;
374   }
375 }
376
377 /****************************************************************************
378  * WebRtcIsacfix_Encode(...)
379  *
380  * This function encodes 10ms frame(s) and inserts it into a package.
381  * Input speech length has to be 160 samples (10ms). The encoder buffers those
382  * 10ms frames until it reaches the chosen Framesize (480 or 960 samples
383  * corresponding to 30 or 60 ms frames), and then proceeds to the encoding.
384  *
385  * Input:
386  *      - ISAC_main_inst    : ISAC instance.
387  *      - speechIn          : input speech vector.
388  *
389  * Output:
390  *      - encoded           : the encoded data vector
391  *
392  * Return value:
393  *                          : >0 - Length (in bytes) of coded data
394  *                          :  0 - The buffer didn't reach the chosen framesize
395  *                            so it keeps buffering speech samples.
396  *                          : -1 - Error
397  */
398
399 int16_t WebRtcIsacfix_Encode(ISACFIX_MainStruct *ISAC_main_inst,
400                              const int16_t    *speechIn,
401                              uint8_t* encoded)
402 {
403   ISACFIX_SubStruct *ISAC_inst;
404   int16_t stream_len;
405
406   /* typecast pointer to rela structure */
407   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
408
409
410   /* check if encoder initiated */
411   if ((ISAC_inst->initflag & 2) != 2) {
412     ISAC_inst->errorcode = ISAC_ENCODER_NOT_INITIATED;
413     return (-1);
414   }
415
416   stream_len = WebRtcIsacfix_EncodeImpl((int16_t*)speechIn,
417                                         &ISAC_inst->ISACenc_obj,
418                                         &ISAC_inst->bwestimator_obj,
419                                         ISAC_inst->CodingMode);
420   if (stream_len<0) {
421     ISAC_inst->errorcode = - stream_len;
422     return -1;
423   }
424
425   write_be16(ISAC_inst->ISACenc_obj.bitstr_obj.stream, stream_len, encoded);
426   return stream_len;
427
428 }
429
430
431
432
433 /****************************************************************************
434  * WebRtcIsacfix_EncodeNb(...)
435  *
436  * This function encodes 10ms narrow band (8 kHz sampling) frame(s) and inserts
437  * it into a package. Input speech length has to be 80 samples (10ms). The encoder
438  * interpolates into wide-band (16 kHz sampling) buffers those
439  * 10ms frames until it reaches the chosen Framesize (480 or 960 wide-band samples
440  * corresponding to 30 or 60 ms frames), and then proceeds to the encoding.
441  *
442  * The function is enabled if WEBRTC_ISAC_FIX_NB_CALLS_ENABLED is defined
443  *
444  * Input:
445  *      - ISAC_main_inst    : ISAC instance.
446  *      - speechIn          : input speech vector.
447  *
448  * Output:
449  *      - encoded           : the encoded data vector
450  *
451  * Return value:
452  *                          : >0 - Length (in bytes) of coded data
453  *                          :  0 - The buffer didn't reach the chosen framesize
454  *                            so it keeps buffering speech samples.
455  *                          : -1 - Error
456  */
457 #ifdef WEBRTC_ISAC_FIX_NB_CALLS_ENABLED
458 int16_t WebRtcIsacfix_EncodeNb(ISACFIX_MainStruct *ISAC_main_inst,
459                                const int16_t    *speechIn,
460                                int16_t          *encoded)
461 {
462   ISACFIX_SubStruct *ISAC_inst;
463   int16_t stream_len;
464   int16_t speechInWB[FRAMESAMPLES_10ms];
465   int16_t Vector_Word16_1[FRAMESAMPLES_10ms/2];
466   int16_t Vector_Word16_2[FRAMESAMPLES_10ms/2];
467
468   int k;
469
470
471   /* typecast pointer to rela structure */
472   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
473
474
475   /* check if encoder initiated */
476   if ((ISAC_inst->initflag & 2) != 2) {
477     ISAC_inst->errorcode = ISAC_ENCODER_NOT_INITIATED;
478     return (-1);
479   }
480
481
482   /* Oversample to WB */
483
484   /* Form polyphase signals, and compensate for DC offset */
485   for (k=0;k<FRAMESAMPLES_10ms/2;k++) {
486     Vector_Word16_1[k] = speechIn[k] + 1;
487     Vector_Word16_2[k] = speechIn[k];
488   }
489   WebRtcIsacfix_FilterAndCombine2(Vector_Word16_1, Vector_Word16_2, speechInWB, &ISAC_inst->ISACenc_obj.interpolatorstr_obj, FRAMESAMPLES_10ms);
490
491
492   /* Encode WB signal */
493   stream_len = WebRtcIsacfix_EncodeImpl((int16_t*)speechInWB,
494                                         &ISAC_inst->ISACenc_obj,
495                                         &ISAC_inst->bwestimator_obj,
496                                         ISAC_inst->CodingMode);
497   if (stream_len<0) {
498     ISAC_inst->errorcode = - stream_len;
499     return -1;
500   }
501
502   write_be16(ISAC_inst->ISACenc_obj.bitstr_obj.stream,
503              stream_len,
504              (uint8_t*)encoded);
505   return stream_len;
506 }
507 #endif  /* WEBRTC_ISAC_FIX_NB_CALLS_ENABLED */
508
509
510 /****************************************************************************
511  * WebRtcIsacfix_GetNewBitStream(...)
512  *
513  * This function returns encoded data, with the recieved bwe-index in the
514  * stream. It should always return a complete packet, i.e. only called once
515  * even for 60 msec frames
516  *
517  * Input:
518  *      - ISAC_main_inst    : ISAC instance.
519  *      - bweIndex          : index of bandwidth estimate to put in new bitstream
520  *
521  * Output:
522  *      - encoded           : the encoded data vector
523  *
524  * Return value:
525  *                          : >0 - Length (in bytes) of coded data
526  *                          : -1 - Error
527  */
528
529 int16_t WebRtcIsacfix_GetNewBitStream(ISACFIX_MainStruct *ISAC_main_inst,
530                                       int16_t      bweIndex,
531                                       float              scale,
532                                       uint8_t* encoded)
533 {
534   ISACFIX_SubStruct *ISAC_inst;
535   int16_t stream_len;
536
537   /* typecast pointer to rela structure */
538   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
539
540
541   /* check if encoder initiated */
542   if ((ISAC_inst->initflag & 2) != 2) {
543     ISAC_inst->errorcode = ISAC_ENCODER_NOT_INITIATED;
544     return (-1);
545   }
546
547   stream_len = WebRtcIsacfix_EncodeStoredData(&ISAC_inst->ISACenc_obj,
548                                               bweIndex,
549                                               scale);
550   if (stream_len<0) {
551     ISAC_inst->errorcode = - stream_len;
552     return -1;
553   }
554
555   write_be16(ISAC_inst->ISACenc_obj.bitstr_obj.stream, stream_len, encoded);
556   return stream_len;
557 }
558
559
560
561 /****************************************************************************
562  * WebRtcIsacfix_DecoderInit(...)
563  *
564  * This function initializes a ISAC instance prior to the decoder calls.
565  *
566  * Input:
567  *      - ISAC_main_inst    : ISAC instance.
568  *
569  * Return value
570  *                          :  0 - Ok
571  *                            -1 - Error
572  */
573
574 int16_t WebRtcIsacfix_DecoderInit(ISACFIX_MainStruct *ISAC_main_inst)
575 {
576   ISACFIX_SubStruct *ISAC_inst;
577
578   /* typecast pointer to real structure */
579   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
580
581   /* flag decoder init */
582   ISAC_inst->initflag |= 1;
583
584   WebRtcIsacfix_InitMaskingDec(&ISAC_inst->ISACdec_obj.maskfiltstr_obj);
585   WebRtcIsacfix_InitPostFilterbank(&ISAC_inst->ISACdec_obj.postfiltbankstr_obj);
586   WebRtcIsacfix_InitPitchFilter(&ISAC_inst->ISACdec_obj.pitchfiltstr_obj);
587
588   /* TS */
589   WebRtcIsacfix_InitPlc( &ISAC_inst->ISACdec_obj.plcstr_obj );
590
591
592 #ifdef WEBRTC_ISAC_FIX_NB_CALLS_ENABLED
593   WebRtcIsacfix_InitPreFilterbank(&ISAC_inst->ISACdec_obj.decimatorstr_obj);
594 #endif
595
596   return 0;
597 }
598
599
600 /****************************************************************************
601  * WebRtcIsacfix_UpdateBwEstimate1(...)
602  *
603  * This function updates the estimate of the bandwidth.
604  *
605  * Input:
606  *      - ISAC_main_inst    : ISAC instance.
607  *      - encoded           : encoded ISAC frame(s).
608  *      - packet_size       : size of the packet.
609  *      - rtp_seq_number    : the RTP number of the packet.
610  *      - arr_ts            : the arrival time of the packet (from NetEq)
611  *                            in samples.
612  *
613  * Return value             :  0 - Ok
614  *                            -1 - Error
615  */
616
617 int16_t WebRtcIsacfix_UpdateBwEstimate1(ISACFIX_MainStruct *ISAC_main_inst,
618                                         const uint8_t* encoded,
619                                         int32_t          packet_size,
620                                         uint16_t         rtp_seq_number,
621                                         uint32_t         arr_ts)
622 {
623   ISACFIX_SubStruct *ISAC_inst;
624   Bitstr_dec streamdata;
625   int16_t err;
626   const int kRequiredEncodedLenBytes = 10;
627
628   /* typecast pointer to real structure */
629   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
630
631   /* Sanity check of packet length */
632   if (packet_size <= 0) {
633     /* return error code if the packet length is null or less */
634     ISAC_inst->errorcode = ISAC_EMPTY_PACKET;
635     return -1;
636   } else if (packet_size > (STREAM_MAXW16<<1)) {
637     /* return error code if length of stream is too long */
638     ISAC_inst->errorcode = ISAC_LENGTH_MISMATCH;
639     return -1;
640   }
641
642   /* check if decoder initiated */
643   if ((ISAC_inst->initflag & 1) != 1) {
644     ISAC_inst->errorcode = ISAC_DECODER_NOT_INITIATED;
645     return (-1);
646   }
647
648   InitializeDecoderBitstream(packet_size, &streamdata);
649
650   read_be16(encoded, kRequiredEncodedLenBytes, streamdata.stream);
651
652   err = WebRtcIsacfix_EstimateBandwidth(&ISAC_inst->bwestimator_obj,
653                                         &streamdata,
654                                         packet_size,
655                                         rtp_seq_number,
656                                         0,
657                                         arr_ts);
658
659
660   if (err < 0)
661   {
662     /* return error code if something went wrong */
663     ISAC_inst->errorcode = -err;
664     return -1;
665   }
666
667
668   return 0;
669 }
670
671 /****************************************************************************
672  * WebRtcIsacfix_UpdateBwEstimate(...)
673  *
674  * This function updates the estimate of the bandwidth.
675  *
676  * Input:
677  *      - ISAC_main_inst    : ISAC instance.
678  *      - encoded           : encoded ISAC frame(s).
679  *      - packet_size       : size of the packet.
680  *      - rtp_seq_number    : the RTP number of the packet.
681  *      - send_ts           : Send Time Stamp from RTP header
682  *      - arr_ts            : the arrival time of the packet (from NetEq)
683  *                            in samples.
684  *
685  * Return value             :  0 - Ok
686  *                            -1 - Error
687  */
688
689 int16_t WebRtcIsacfix_UpdateBwEstimate(ISACFIX_MainStruct *ISAC_main_inst,
690                                        const uint8_t* encoded,
691                                        int32_t          packet_size,
692                                        uint16_t         rtp_seq_number,
693                                        uint32_t         send_ts,
694                                        uint32_t         arr_ts)
695 {
696   ISACFIX_SubStruct *ISAC_inst;
697   Bitstr_dec streamdata;
698   int16_t err;
699   const int kRequiredEncodedLenBytes = 10;
700
701   /* typecast pointer to real structure */
702   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
703
704   /* Sanity check of packet length */
705   if (packet_size <= 0) {
706     /* return error code if the packet length is null  or less */
707     ISAC_inst->errorcode = ISAC_EMPTY_PACKET;
708     return -1;
709   } else if (packet_size < kRequiredEncodedLenBytes) {
710     ISAC_inst->errorcode = ISAC_PACKET_TOO_SHORT;
711     return -1;
712   } else if (packet_size > (STREAM_MAXW16<<1)) {
713     /* return error code if length of stream is too long */
714     ISAC_inst->errorcode = ISAC_LENGTH_MISMATCH;
715     return -1;
716   }
717
718   /* check if decoder initiated */
719   if ((ISAC_inst->initflag & 1) != 1) {
720     ISAC_inst->errorcode = ISAC_DECODER_NOT_INITIATED;
721     return (-1);
722   }
723
724   InitializeDecoderBitstream(packet_size, &streamdata);
725
726   read_be16(encoded, kRequiredEncodedLenBytes, streamdata.stream);
727
728   err = WebRtcIsacfix_EstimateBandwidth(&ISAC_inst->bwestimator_obj,
729                                         &streamdata,
730                                         packet_size,
731                                         rtp_seq_number,
732                                         send_ts,
733                                         arr_ts);
734
735   if (err < 0)
736   {
737     /* return error code if something went wrong */
738     ISAC_inst->errorcode = -err;
739     return -1;
740   }
741
742
743   return 0;
744 }
745
746 /****************************************************************************
747  * WebRtcIsacfix_Decode(...)
748  *
749  * This function decodes a ISAC frame. Output speech length
750  * will be a multiple of 480 samples: 480 or 960 samples,
751  * depending on the framesize (30 or 60 ms).
752  *
753  * Input:
754  *      - ISAC_main_inst    : ISAC instance.
755  *      - encoded           : encoded ISAC frame(s)
756  *      - len               : bytes in encoded vector
757  *
758  * Output:
759  *      - decoded           : The decoded vector
760  *
761  * Return value             : >0 - number of samples in decoded vector
762  *                            -1 - Error
763  */
764
765
766 int16_t WebRtcIsacfix_Decode(ISACFIX_MainStruct *ISAC_main_inst,
767                              const uint8_t* encoded,
768                              int16_t          len,
769                              int16_t          *decoded,
770                              int16_t     *speechType)
771 {
772   ISACFIX_SubStruct *ISAC_inst;
773   /* number of samples (480 or 960), output from decoder */
774   /* that were actually used in the encoder/decoder (determined on the fly) */
775   int16_t     number_of_samples;
776   int16_t declen = 0;
777
778   /* typecast pointer to real structure */
779   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
780
781   /* check if decoder initiated */
782   if ((ISAC_inst->initflag & 1) != 1) {
783     ISAC_inst->errorcode = ISAC_DECODER_NOT_INITIATED;
784     return (-1);
785   }
786
787   /* Sanity check of packet length */
788   if (len <= 0) {
789     /* return error code if the packet length is null  or less */
790     ISAC_inst->errorcode = ISAC_EMPTY_PACKET;
791     return -1;
792   } else if (len > (STREAM_MAXW16<<1)) {
793     /* return error code if length of stream is too long */
794     ISAC_inst->errorcode = ISAC_LENGTH_MISMATCH;
795     return -1;
796   }
797
798   InitializeDecoderBitstream(len, &ISAC_inst->ISACdec_obj.bitstr_obj);
799
800   read_be16(encoded, len, ISAC_inst->ISACdec_obj.bitstr_obj.stream);
801
802   /* added for NetEq purposes (VAD/DTX related) */
803   *speechType=1;
804
805   declen = WebRtcIsacfix_DecodeImpl(decoded,&ISAC_inst->ISACdec_obj, &number_of_samples);
806
807   if (declen < 0) {
808     /* Some error inside the decoder */
809     ISAC_inst->errorcode = -declen;
810     memset(decoded, 0, sizeof(int16_t) * MAX_FRAMESAMPLES);
811     return -1;
812   }
813
814   /* error check */
815
816   if (declen & 0x0001) {
817     if (len != declen && len != declen + (((ISAC_inst->ISACdec_obj.bitstr_obj).stream[declen>>1]) & 0x00FF) ) {
818       ISAC_inst->errorcode = ISAC_LENGTH_MISMATCH;
819       memset(decoded, 0, sizeof(int16_t) * number_of_samples);
820       return -1;
821     }
822   } else {
823     if (len != declen && len != declen + (((ISAC_inst->ISACdec_obj.bitstr_obj).stream[declen>>1]) >> 8) ) {
824       ISAC_inst->errorcode = ISAC_LENGTH_MISMATCH;
825       memset(decoded, 0, sizeof(int16_t) * number_of_samples);
826       return -1;
827     }
828   }
829
830   return number_of_samples;
831 }
832
833
834
835
836
837 /****************************************************************************
838  * WebRtcIsacfix_DecodeNb(...)
839  *
840  * This function decodes a ISAC frame in narrow-band (8 kHz sampling).
841  * Output speech length will be a multiple of 240 samples: 240 or 480 samples,
842  * depending on the framesize (30 or 60 ms).
843  *
844  * The function is enabled if WEBRTC_ISAC_FIX_NB_CALLS_ENABLED is defined
845  *
846  * Input:
847  *      - ISAC_main_inst    : ISAC instance.
848  *      - encoded           : encoded ISAC frame(s)
849  *      - len               : bytes in encoded vector
850  *
851  * Output:
852  *      - decoded           : The decoded vector
853  *
854  * Return value             : >0 - number of samples in decoded vector
855  *                            -1 - Error
856  */
857
858 #ifdef WEBRTC_ISAC_FIX_NB_CALLS_ENABLED
859 int16_t WebRtcIsacfix_DecodeNb(ISACFIX_MainStruct *ISAC_main_inst,
860                                const uint16_t   *encoded,
861                                int16_t          len,
862                                int16_t          *decoded,
863                                int16_t    *speechType)
864 {
865   ISACFIX_SubStruct *ISAC_inst;
866   /* twice the number of samples (480 or 960), output from decoder */
867   /* that were actually used in the encoder/decoder (determined on the fly) */
868   int16_t     number_of_samples;
869   int16_t declen = 0;
870   int16_t dummy[FRAMESAMPLES/2];
871
872
873   /* typecast pointer to real structure */
874   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
875
876   /* check if decoder initiated */
877   if ((ISAC_inst->initflag & 1) != 1) {
878     ISAC_inst->errorcode = ISAC_DECODER_NOT_INITIATED;
879     return (-1);
880   }
881
882   if (len <= 0) {
883     /* return error code if the packet length is null  or less */
884     ISAC_inst->errorcode = ISAC_EMPTY_PACKET;
885     return -1;
886   } else if (len > (STREAM_MAXW16<<1)) {
887     /* return error code if length of stream is too long */
888     ISAC_inst->errorcode = ISAC_LENGTH_MISMATCH;
889     return -1;
890   }
891
892   InitializeDecoderBitstream(len, &ISAC_inst->ISACdec_obj.bitstr_obj);
893
894   read_be16(encoded, len, ISAC_inst->ISACdec_obj.bitstr_obj.stream);
895
896   /* added for NetEq purposes (VAD/DTX related) */
897   *speechType=1;
898
899   declen = WebRtcIsacfix_DecodeImpl(decoded,&ISAC_inst->ISACdec_obj, &number_of_samples);
900
901   if (declen < 0) {
902     /* Some error inside the decoder */
903     ISAC_inst->errorcode = -declen;
904     memset(decoded, 0, sizeof(int16_t) * FRAMESAMPLES);
905     return -1;
906   }
907
908   /* error check */
909
910   if (declen & 0x0001) {
911     if (len != declen && len != declen + (((ISAC_inst->ISACdec_obj.bitstr_obj).stream[declen>>1]) & 0x00FF) ) {
912       ISAC_inst->errorcode = ISAC_LENGTH_MISMATCH;
913       memset(decoded, 0, sizeof(int16_t) * number_of_samples);
914       return -1;
915     }
916   } else {
917     if (len != declen && len != declen + (((ISAC_inst->ISACdec_obj.bitstr_obj).stream[declen>>1]) >> 8) ) {
918       ISAC_inst->errorcode = ISAC_LENGTH_MISMATCH;
919       memset(decoded, 0, sizeof(int16_t) * number_of_samples);
920       return -1;
921     }
922   }
923
924   WebRtcIsacfix_SplitAndFilter2(decoded, decoded, dummy, &ISAC_inst->ISACdec_obj.decimatorstr_obj);
925
926   if (number_of_samples>FRAMESAMPLES) {
927     WebRtcIsacfix_SplitAndFilter2(decoded + FRAMESAMPLES, decoded + FRAMESAMPLES/2,
928                                   dummy, &ISAC_inst->ISACdec_obj.decimatorstr_obj);
929   }
930
931   return number_of_samples/2;
932 }
933 #endif /* WEBRTC_ISAC_FIX_NB_CALLS_ENABLED */
934
935
936 /****************************************************************************
937  * WebRtcIsacfix_DecodePlcNb(...)
938  *
939  * This function conducts PLC for ISAC frame(s) in narrow-band (8kHz sampling).
940  * Output speech length  will be "240*noOfLostFrames" samples
941  * that is equevalent of "30*noOfLostFrames" millisecond.
942  *
943  * The function is enabled if WEBRTC_ISAC_FIX_NB_CALLS_ENABLED is defined
944  *
945  * Input:
946  *      - ISAC_main_inst    : ISAC instance.
947  *      - noOfLostFrames    : Number of PLC frames (240 sample=30ms) to produce
948  *
949  * Output:
950  *      - decoded           : The decoded vector
951  *
952  * Return value             : >0 - number of samples in decoded PLC vector
953  *                            -1 - Error
954  */
955
956 #ifdef WEBRTC_ISAC_FIX_NB_CALLS_ENABLED
957 int16_t WebRtcIsacfix_DecodePlcNb(ISACFIX_MainStruct *ISAC_main_inst,
958                                   int16_t          *decoded,
959                                   int16_t noOfLostFrames )
960 {
961   int16_t no_of_samples, declen, k, ok;
962   int16_t outframeNB[FRAMESAMPLES];
963   int16_t outframeWB[FRAMESAMPLES];
964   int16_t dummy[FRAMESAMPLES/2];
965
966
967   ISACFIX_SubStruct *ISAC_inst;
968   /* typecast pointer to real structure */
969   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
970
971   /* Limit number of frames to two = 60 msec. Otherwise we exceed data vectors */
972   if (noOfLostFrames > 2){
973     noOfLostFrames = 2;
974   }
975
976   k = 0;
977   declen = 0;
978   while( noOfLostFrames > 0 )
979   {
980     ok = WebRtcIsacfix_DecodePlcImpl( outframeWB, &ISAC_inst->ISACdec_obj, &no_of_samples );
981     if(ok)
982       return -1;
983
984     WebRtcIsacfix_SplitAndFilter2(outframeWB, &(outframeNB[k*240]), dummy, &ISAC_inst->ISACdec_obj.decimatorstr_obj);
985
986     declen += no_of_samples;
987     noOfLostFrames--;
988     k++;
989   }
990
991   declen>>=1;
992
993   for (k=0;k<declen;k++) {
994     decoded[k] = outframeNB[k];
995   }
996
997   return declen;
998 }
999 #endif /* WEBRTC_ISAC_FIX_NB_CALLS_ENABLED */
1000
1001
1002
1003
1004 /****************************************************************************
1005  * WebRtcIsacfix_DecodePlc(...)
1006  *
1007  * This function conducts PLC for ISAC frame(s) in wide-band (16kHz sampling).
1008  * Output speech length  will be "480*noOfLostFrames" samples
1009  * that is equevalent of "30*noOfLostFrames" millisecond.
1010  *
1011  * Input:
1012  *      - ISAC_main_inst    : ISAC instance.
1013  *      - noOfLostFrames    : Number of PLC frames (480sample = 30ms)
1014  *                                to produce
1015  *
1016  * Output:
1017  *      - decoded           : The decoded vector
1018  *
1019  * Return value             : >0 - number of samples in decoded PLC vector
1020  *                            -1 - Error
1021  */
1022
1023 int16_t WebRtcIsacfix_DecodePlc(ISACFIX_MainStruct *ISAC_main_inst,
1024                                 int16_t          *decoded,
1025                                 int16_t noOfLostFrames)
1026 {
1027
1028   int16_t no_of_samples, declen, k, ok;
1029   int16_t outframe16[MAX_FRAMESAMPLES];
1030
1031   ISACFIX_SubStruct *ISAC_inst;
1032   /* typecast pointer to real structure */
1033   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1034
1035   /* Limit number of frames to two = 60 msec. Otherwise we exceed data vectors */
1036   if (noOfLostFrames > 2) {
1037     noOfLostFrames = 2;
1038   }
1039   k = 0;
1040   declen = 0;
1041   while( noOfLostFrames > 0 )
1042   {
1043     ok = WebRtcIsacfix_DecodePlcImpl( &(outframe16[k*480]), &ISAC_inst->ISACdec_obj, &no_of_samples );
1044     if(ok)
1045       return -1;
1046     declen += no_of_samples;
1047     noOfLostFrames--;
1048     k++;
1049   }
1050
1051   for (k=0;k<declen;k++) {
1052     decoded[k] = outframe16[k];
1053   }
1054
1055   return declen;
1056 }
1057
1058
1059 /****************************************************************************
1060  * WebRtcIsacfix_Control(...)
1061  *
1062  * This function sets the limit on the short-term average bit rate and the
1063  * frame length. Should be used only in Instantaneous mode.
1064  *
1065  * Input:
1066  *      - ISAC_main_inst    : ISAC instance.
1067  *      - rate              : limit on the short-term average bit rate,
1068  *                            in bits/second (between 10000 and 32000)
1069  *      - framesize         : number of milliseconds per frame (30 or 60)
1070  *
1071  * Return value             : 0  - ok
1072  *                            -1 - Error
1073  */
1074
1075 int16_t WebRtcIsacfix_Control(ISACFIX_MainStruct *ISAC_main_inst,
1076                               int16_t          rate,
1077                               int16_t          framesize)
1078 {
1079   ISACFIX_SubStruct *ISAC_inst;
1080   /* typecast pointer to real structure */
1081   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1082
1083   if (ISAC_inst->CodingMode == 0)
1084   {
1085     /* in adaptive mode */
1086     ISAC_inst->errorcode = ISAC_MODE_MISMATCH;
1087     return -1;
1088   }
1089
1090
1091   if (rate >= 10000 && rate <= 32000)
1092     ISAC_inst->ISACenc_obj.BottleNeck = rate;
1093   else {
1094     ISAC_inst->errorcode = ISAC_DISALLOWED_BOTTLENECK;
1095     return -1;
1096   }
1097
1098
1099
1100   if (framesize  == 30 || framesize == 60)
1101     ISAC_inst->ISACenc_obj.new_framelength = (FS/1000) * framesize;
1102   else {
1103     ISAC_inst->errorcode = ISAC_DISALLOWED_FRAME_LENGTH;
1104     return -1;
1105   }
1106
1107   return 0;
1108 }
1109
1110
1111 /****************************************************************************
1112  * WebRtcIsacfix_ControlBwe(...)
1113  *
1114  * This function sets the initial values of bottleneck and frame-size if
1115  * iSAC is used in channel-adaptive mode. Through this API, users can
1116  * enforce a frame-size for all values of bottleneck. Then iSAC will not
1117  * automatically change the frame-size.
1118  *
1119  *
1120  * Input:
1121  *  - ISAC_main_inst : ISAC instance.
1122  *      - rateBPS           : initial value of bottleneck in bits/second
1123  *                            10000 <= rateBPS <= 32000 is accepted
1124  *                            For default bottleneck set rateBPS = 0
1125  *      - frameSizeMs       : number of milliseconds per frame (30 or 60)
1126  *      - enforceFrameSize  : 1 to enforce the given frame-size through out
1127  *                            the adaptation process, 0 to let iSAC change
1128  *                            the frame-size if required.
1129  *
1130  * Return value    : 0  - ok
1131  *         -1 - Error
1132  */
1133
1134 int16_t WebRtcIsacfix_ControlBwe(ISACFIX_MainStruct *ISAC_main_inst,
1135                                  int16_t rateBPS,
1136                                  int16_t frameSizeMs,
1137                                  int16_t enforceFrameSize)
1138 {
1139   ISACFIX_SubStruct *ISAC_inst;
1140   /* Typecast pointer to real structure */
1141   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1142
1143   /* check if encoder initiated */
1144   if ((ISAC_inst->initflag & 2) != 2) {
1145     ISAC_inst->errorcode = ISAC_ENCODER_NOT_INITIATED;
1146     return (-1);
1147   }
1148
1149   /* Check that we are in channel-adaptive mode, otherwise, return -1 */
1150   if (ISAC_inst->CodingMode != 0) {
1151     ISAC_inst->errorcode = ISAC_MODE_MISMATCH;
1152     return (-1);
1153   }
1154
1155   /* Set struct variable if enforceFrameSize is set. ISAC will then keep the */
1156   /* chosen frame size.                                                      */
1157   ISAC_inst->ISACenc_obj.enforceFrameSize = (enforceFrameSize != 0)? 1:0;
1158
1159   /* Set initial rate, if value between 10000 and 32000,                */
1160   /* if rateBPS is 0, keep the default initial bottleneck value (15000) */
1161   if ((rateBPS >= 10000) && (rateBPS <= 32000)) {
1162     ISAC_inst->bwestimator_obj.sendBwAvg = (((uint32_t)rateBPS) << 7);
1163   } else if (rateBPS != 0) {
1164     ISAC_inst->errorcode = ISAC_DISALLOWED_BOTTLENECK;
1165     return -1;
1166   }
1167
1168   /* Set initial framesize. If enforceFrameSize is set the frame size will not change */
1169   if ((frameSizeMs  == 30) || (frameSizeMs == 60)) {
1170     ISAC_inst->ISACenc_obj.new_framelength = (FS/1000) * frameSizeMs;
1171   } else {
1172     ISAC_inst->errorcode = ISAC_DISALLOWED_FRAME_LENGTH;
1173     return -1;
1174   }
1175
1176   return 0;
1177 }
1178
1179
1180
1181
1182
1183 /****************************************************************************
1184  * WebRtcIsacfix_GetDownLinkBwIndex(...)
1185  *
1186  * This function returns index representing the Bandwidth estimate from
1187  * other side to this side.
1188  *
1189  * Input:
1190  *      - ISAC_main_inst: iSAC struct
1191  *
1192  * Output:
1193  *      - rateIndex     : Bandwidth estimate to transmit to other side.
1194  *
1195  */
1196
1197 int16_t WebRtcIsacfix_GetDownLinkBwIndex(ISACFIX_MainStruct* ISAC_main_inst,
1198                                          int16_t*     rateIndex)
1199 {
1200   ISACFIX_SubStruct *ISAC_inst;
1201
1202   /* typecast pointer to real structure */
1203   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1204
1205   /* Call function to get Bandwidth Estimate */
1206   *rateIndex = WebRtcIsacfix_GetDownlinkBwIndexImpl(&ISAC_inst->bwestimator_obj);
1207
1208   return 0;
1209 }
1210
1211
1212 /****************************************************************************
1213  * WebRtcIsacfix_UpdateUplinkBw(...)
1214  *
1215  * This function takes an index representing the Bandwidth estimate from
1216  * this side to other side and updates BWE.
1217  *
1218  * Input:
1219  *      - ISAC_main_inst: iSAC struct
1220  *      - rateIndex     : Bandwidth estimate from other side.
1221  *
1222  */
1223
1224 int16_t WebRtcIsacfix_UpdateUplinkBw(ISACFIX_MainStruct* ISAC_main_inst,
1225                                      int16_t     rateIndex)
1226 {
1227   int16_t err = 0;
1228   ISACFIX_SubStruct *ISAC_inst;
1229
1230   /* typecast pointer to real structure */
1231   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1232
1233   /* Call function to update BWE with received Bandwidth Estimate */
1234   err = WebRtcIsacfix_UpdateUplinkBwRec(&ISAC_inst->bwestimator_obj, rateIndex);
1235   if (err < 0) {
1236     ISAC_inst->errorcode = -err;
1237     return (-1);
1238   }
1239
1240   return 0;
1241 }
1242
1243 /****************************************************************************
1244  * WebRtcIsacfix_ReadFrameLen(...)
1245  *
1246  * This function returns the length of the frame represented in the packet.
1247  *
1248  * Input:
1249  *      - encoded       : Encoded bitstream
1250  *
1251  * Output:
1252  *      - frameLength   : Length of frame in packet (in samples)
1253  *
1254  */
1255
1256 int16_t WebRtcIsacfix_ReadFrameLen(const uint8_t* encoded,
1257                                    int encoded_len_bytes,
1258                                    int16_t* frameLength)
1259 {
1260   Bitstr_dec streamdata;
1261   int16_t err;
1262   const int kRequiredEncodedLenBytes = 10;
1263
1264   if (encoded_len_bytes < kRequiredEncodedLenBytes) {
1265     return -1;
1266   }
1267
1268   InitializeDecoderBitstream(encoded_len_bytes, &streamdata);
1269
1270   read_be16(encoded, kRequiredEncodedLenBytes, streamdata.stream);
1271
1272   /* decode frame length */
1273   err = WebRtcIsacfix_DecodeFrameLen(&streamdata, frameLength);
1274   if (err<0)  // error check
1275     return err;
1276
1277   return 0;
1278 }
1279
1280
1281 /****************************************************************************
1282  * WebRtcIsacfix_ReadBwIndex(...)
1283  *
1284  * This function returns the index of the Bandwidth estimate from the bitstream.
1285  *
1286  * Input:
1287  *      - encoded       : Encoded bitstream
1288  *
1289  * Output:
1290  *      - frameLength   : Length of frame in packet (in samples)
1291  *      - rateIndex     : Bandwidth estimate in bitstream
1292  *
1293  */
1294
1295 int16_t WebRtcIsacfix_ReadBwIndex(const uint8_t* encoded,
1296                                   int encoded_len_bytes,
1297                                   int16_t* rateIndex)
1298 {
1299   Bitstr_dec streamdata;
1300   int16_t err;
1301   const int kRequiredEncodedLenBytes = 10;
1302
1303   if (encoded_len_bytes < kRequiredEncodedLenBytes) {
1304     return -1;
1305   }
1306
1307   InitializeDecoderBitstream(encoded_len_bytes, &streamdata);
1308
1309   read_be16(encoded, kRequiredEncodedLenBytes, streamdata.stream);
1310
1311   /* decode frame length, needed to get to the rateIndex in the bitstream */
1312   err = WebRtcIsacfix_DecodeFrameLen(&streamdata, rateIndex);
1313   if (err<0)  // error check
1314     return err;
1315
1316   /* decode BW estimation */
1317   err = WebRtcIsacfix_DecodeSendBandwidth(&streamdata, rateIndex);
1318   if (err<0)  // error check
1319     return err;
1320
1321   return 0;
1322 }
1323
1324
1325
1326
1327 /****************************************************************************
1328  * WebRtcIsacfix_GetErrorCode(...)
1329  *
1330  * This function can be used to check the error code of an iSAC instance. When
1331  * a function returns -1 a error code will be set for that instance. The
1332  * function below extract the code of the last error that occured in the
1333  * specified instance.
1334  *
1335  * Input:
1336  *      - ISAC_main_inst    : ISAC instance
1337  *
1338  * Return value             : Error code
1339  */
1340
1341 int16_t WebRtcIsacfix_GetErrorCode(ISACFIX_MainStruct *ISAC_main_inst)
1342 {
1343   ISACFIX_SubStruct *ISAC_inst;
1344   /* typecast pointer to real structure */
1345   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1346
1347   return ISAC_inst->errorcode;
1348 }
1349
1350
1351
1352 /****************************************************************************
1353  * WebRtcIsacfix_GetUplinkBw(...)
1354  *
1355  * This function returns the inst quantized iSAC send bitrate
1356  *
1357  * Input:
1358  *      - ISAC_main_inst    : iSAC instance
1359  *
1360  * Return value             : bitrate
1361  */
1362
1363 int32_t WebRtcIsacfix_GetUplinkBw(ISACFIX_MainStruct *ISAC_main_inst)
1364 {
1365   ISACFIX_SubStruct *ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1366   BwEstimatorstr * bw = (BwEstimatorstr*)&(ISAC_inst->bwestimator_obj);
1367
1368   return (int32_t) WebRtcIsacfix_GetUplinkBandwidth(bw);
1369 }
1370
1371 /****************************************************************************
1372  * WebRtcIsacfix_GetNewFrameLen(...)
1373  *
1374  * This function return the next frame length (in samples) of iSAC.
1375  *
1376  * Input:
1377  *      - ISAC_main_inst    : iSAC instance
1378  *
1379  * Return value             :  frame lenght in samples
1380  */
1381
1382 int16_t WebRtcIsacfix_GetNewFrameLen(ISACFIX_MainStruct *ISAC_main_inst)
1383 {
1384   ISACFIX_SubStruct *ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1385   return ISAC_inst->ISACenc_obj.new_framelength;
1386 }
1387
1388
1389 /****************************************************************************
1390  * WebRtcIsacfix_SetMaxPayloadSize(...)
1391  *
1392  * This function sets a limit for the maximum payload size of iSAC. The same
1393  * value is used both for 30 and 60 msec packets.
1394  * The absolute max will be valid until next time the function is called.
1395  * NOTE! This function may override the function WebRtcIsacfix_SetMaxRate()
1396  *
1397  * Input:
1398  *      - ISAC_main_inst    : iSAC instance
1399  *      - maxPayloadBytes   : maximum size of the payload in bytes
1400  *                            valid values are between 100 and 400 bytes
1401  *
1402  *
1403  * Return value             : 0 if sucessful
1404  *                           -1 if error happens
1405  */
1406
1407 int16_t WebRtcIsacfix_SetMaxPayloadSize(ISACFIX_MainStruct *ISAC_main_inst,
1408                                         int16_t maxPayloadBytes)
1409 {
1410   ISACFIX_SubStruct *ISAC_inst;
1411
1412   /* typecast pointer to real structure */
1413   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1414
1415   if((maxPayloadBytes < 100) || (maxPayloadBytes > 400))
1416   {
1417     /* maxPayloadBytes is out of valid range */
1418     return -1;
1419   }
1420   else
1421   {
1422     /* Set new absolute max, which will not change unless this function
1423        is called again with a new value */
1424     ISAC_inst->ISACenc_obj.maxPayloadBytes = maxPayloadBytes;
1425
1426     /* Set new maximum values for 30 and 60 msec packets */
1427     if (maxPayloadBytes < ISAC_inst->ISACenc_obj.maxRateInBytes) {
1428       ISAC_inst->ISACenc_obj.payloadLimitBytes30 = maxPayloadBytes;
1429     } else {
1430       ISAC_inst->ISACenc_obj.payloadLimitBytes30 = ISAC_inst->ISACenc_obj.maxRateInBytes;
1431     }
1432
1433     if ( maxPayloadBytes < (ISAC_inst->ISACenc_obj.maxRateInBytes << 1)) {
1434       ISAC_inst->ISACenc_obj.payloadLimitBytes60 = maxPayloadBytes;
1435     } else {
1436       ISAC_inst->ISACenc_obj.payloadLimitBytes60 = (ISAC_inst->ISACenc_obj.maxRateInBytes << 1);
1437     }
1438   }
1439   return 0;
1440 }
1441
1442
1443 /****************************************************************************
1444  * WebRtcIsacfix_SetMaxRate(...)
1445  *
1446  * This function sets the maximum rate which the codec may not exceed for a
1447  * singel packet. The maximum rate is set in bits per second.
1448  * The codec has an absolute maximum rate of 53400 bits per second (200 bytes
1449  * per 30 msec).
1450  * It is possible to set a maximum rate between 32000 and 53400 bits per second.
1451  *
1452  * The rate limit is valid until next time the function is called.
1453  *
1454  * NOTE! Packet size will never go above the value set if calling
1455  * WebRtcIsacfix_SetMaxPayloadSize() (default max packet size is 400 bytes).
1456  *
1457  * Input:
1458  *      - ISAC_main_inst    : iSAC instance
1459  *      - maxRateInBytes    : maximum rate in bits per second,
1460  *                            valid values are 32000 to 53400 bits
1461  *
1462  * Return value             : 0 if sucessful
1463  *                           -1 if error happens
1464  */
1465
1466 int16_t WebRtcIsacfix_SetMaxRate(ISACFIX_MainStruct *ISAC_main_inst,
1467                                  int32_t maxRate)
1468 {
1469   ISACFIX_SubStruct *ISAC_inst;
1470   int16_t maxRateInBytes;
1471
1472   /* typecast pointer to real structure */
1473   ISAC_inst = (ISACFIX_SubStruct *)ISAC_main_inst;
1474
1475   if((maxRate < 32000) || (maxRate > 53400))
1476   {
1477     /* maxRate is out of valid range */
1478     return -1;
1479   }
1480   else
1481   {
1482     /* Calculate maximum number of bytes per 30 msec packets for the given
1483        maximum rate. Multiply with 30/1000 to get number of bits per 30 msec,
1484        divide by 8 to get number of bytes per 30 msec:
1485        maxRateInBytes = floor((maxRate * 30/1000) / 8); */
1486     maxRateInBytes = (int16_t)( WebRtcSpl_DivW32W16ResW16(WEBRTC_SPL_MUL(maxRate, 3), 800) );
1487
1488     /* Store the value for usage in the WebRtcIsacfix_SetMaxPayloadSize-function */
1489     ISAC_inst->ISACenc_obj.maxRateInBytes = maxRateInBytes;
1490
1491     /* For 30 msec packets: if the new limit is below the maximum
1492        payload size, set a new limit */
1493     if (maxRateInBytes < ISAC_inst->ISACenc_obj.maxPayloadBytes) {
1494       ISAC_inst->ISACenc_obj.payloadLimitBytes30 = maxRateInBytes;
1495     } else {
1496       ISAC_inst->ISACenc_obj.payloadLimitBytes30 = ISAC_inst->ISACenc_obj.maxPayloadBytes;
1497     }
1498
1499     /* For 60 msec packets: if the new limit (times 2) is below the
1500        maximum payload size, set a new limit */
1501     if ( (maxRateInBytes << 1) < ISAC_inst->ISACenc_obj.maxPayloadBytes) {
1502       ISAC_inst->ISACenc_obj.payloadLimitBytes60 = (maxRateInBytes << 1);
1503     } else {
1504       ISAC_inst->ISACenc_obj.payloadLimitBytes60 = ISAC_inst->ISACenc_obj.maxPayloadBytes;
1505     }
1506   }
1507
1508   return 0;
1509 }
1510
1511
1512
1513 /****************************************************************************
1514  * WebRtcIsacfix_version(...)
1515  *
1516  * This function returns the version number.
1517  *
1518  * Output:
1519  *      - version  : Pointer to character string
1520  *
1521  */
1522
1523 void WebRtcIsacfix_version(char *version)
1524 {
1525   strcpy(version, "3.6.0");
1526 }