Update SILK code using the CELT range coder
[opus.git] / src_FLP / SKP_Silk_control_codec_FLP.c
1 /***********************************************************************\r
2 Copyright (c) 2006-2010, Skype Limited. All rights reserved. \r
3 Redistribution and use in source and binary forms, with or without \r
4 modification, (subject to the limitations in the disclaimer below) \r
5 are permitted provided that the following conditions are met:\r
6 - Redistributions of source code must retain the above copyright notice,\r
7 this list of conditions and the following disclaimer.\r
8 - Redistributions in binary form must reproduce the above copyright \r
9 notice, this list of conditions and the following disclaimer in the \r
10 documentation and/or other materials provided with the distribution.\r
11 - Neither the name of Skype Limited, nor the names of specific \r
12 contributors, may be used to endorse or promote products derived from \r
13 this software without specific prior written permission.\r
14 NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \r
15 BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \r
16 CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\r
17 BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \r
18 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \r
19 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \r
20 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\r
21 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \r
22 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \r
23 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \r
24 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \r
25 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
26 ***********************************************************************/\r
27 \r
28 #include "SKP_Silk_main_FLP.h"\r
29 \r
30 /* ToDo: Move the functions below to common to be able to use them in FLP control codec also */\r
31 SKP_INLINE SKP_int SKP_Silk_setup_resamplers(\r
32     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
33     SKP_int                         API_fs_Hz,          /* I                        */\r
34     SKP_int                         fs_kHz              /* I                        */\r
35 );\r
36 \r
37 SKP_INLINE SKP_int SKP_Silk_setup_packetsize(\r
38     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
39     SKP_int                         PacketSize_ms       /* I                        */\r
40 );\r
41 \r
42 SKP_INLINE SKP_int SKP_Silk_setup_fs(\r
43     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
44     SKP_int                         fs_kHz              /* I                        */\r
45 );\r
46 \r
47 SKP_INLINE SKP_int SKP_Silk_setup_complexity(\r
48     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
49     SKP_int                         Complexity          /* I                        */\r
50 );\r
51 \r
52 SKP_INLINE SKP_int SKP_Silk_setup_rate(\r
53     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
54     SKP_int                         TargetRate_bps      /* I                        */\r
55 );\r
56 \r
57 SKP_INLINE SKP_int SKP_Silk_setup_LBRR(\r
58     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
59     SKP_int                         INBandFEC_enabled   /* I                        */\r
60 );\r
61 \r
62 /* Control encoder SNR */\r
63 SKP_int SKP_Silk_control_encoder_FLP( \r
64     SKP_Silk_encoder_state_FLP  *psEnc,             /* I/O  Pointer to Silk encoder state FLP       */\r
65     const SKP_int32             API_fs_Hz,          /* I    External (API) sampling rate (Hz)       */\r
66     const SKP_int               max_internal_fs_kHz,/* I    Maximum internal sampling rate (kHz)    */\r
67     const SKP_int               PacketSize_ms,      /* I    Packet length (ms)                      */\r
68           SKP_int32             TargetRate_bps,     /* I    Target max bitrate (if SNR_dB == 0)     */\r
69     const SKP_int               PacketLoss_perc,    /* I    Packet loss rate (in percent)           */\r
70     const SKP_int               INBandFEC_enabled,  /* I    Enable (1) / disable (0) inband FEC     */\r
71     const SKP_int               DTX_enabled,        /* I    Enable / disable DTX                    */\r
72     const SKP_int               InputFramesize_ms,  /* I    Inputframe in ms                        */\r
73     const SKP_int               Complexity          /* I    Complexity (0->low; 1->medium; 2->high) */\r
74 )\r
75 {\r
76     SKP_int   fs_kHz, ret = 0;\r
77 \r
78     /* State machine for the SWB/WB switching */\r
79     fs_kHz = psEnc->sCmn.fs_kHz;\r
80     \r
81     /* Only switch during low speech activity, when no frames are sitting in the payload buffer */\r
82     if( API_fs_Hz == 8000 || fs_kHz == 0 || API_fs_Hz < fs_kHz * 1000 || fs_kHz > max_internal_fs_kHz ) {\r
83         /* Switching is not possible, encoder just initialized, internal mode higher than external, */\r
84         /* or internal mode higher than maximum allowed internal mode                               */\r
85         fs_kHz = SKP_min( SKP_DIV32_16( API_fs_Hz, 1000 ), max_internal_fs_kHz );\r
86     } else {\r
87         /* Accumulate the difference between the target rate and limit for switching down */\r
88         psEnc->sCmn.bitrateDiff += SKP_MUL( InputFramesize_ms, TargetRate_bps - psEnc->sCmn.bitrate_threshold_down );\r
89         psEnc->sCmn.bitrateDiff  = SKP_min( psEnc->sCmn.bitrateDiff, 0 );\r
90 \r
91         if( psEnc->speech_activity < 0.5f && psEnc->sCmn.nFramesInPayloadBuf == 0 ) { /* Low speech activity and payload buffer empty */\r
92             /* Check if we should switch down */\r
93 #if SWITCH_TRANSITION_FILTERING \r
94             if( ( psEnc->sCmn.sLP.transition_frame_no == 0 ) &&                         /* Transition phase not active */\r
95                 ( psEnc->sCmn.bitrateDiff <= -ACCUM_BITS_DIFF_THRESHOLD ||              /* Bitrate threshold is met */\r
96                 ( psEnc->sCmn.sSWBdetect.WB_detected * psEnc->sCmn.fs_kHz == 24 ) ) ) { /* Forced down-switching due to WB input */\r
97                 psEnc->sCmn.sLP.transition_frame_no = 1;                                /* Begin transition phase */\r
98                 psEnc->sCmn.sLP.mode                = 0;                                /* Switch down */\r
99             } else if( \r
100                 ( psEnc->sCmn.sLP.transition_frame_no >= TRANSITION_FRAMES_DOWN ) &&    /* Transition phase complete */\r
101                 ( psEnc->sCmn.sLP.mode == 0 ) ) {                                       /* Ready to switch down */\r
102                 psEnc->sCmn.sLP.transition_frame_no = 0;                                /* Ready for new transition phase */\r
103 #else\r
104             if( psEnc->sCmn.bitrateDiff <= -ACCUM_BITS_DIFF_THRESHOLD ) {               /* Bitrate threshold is met */ \r
105 #endif            \r
106                 psEnc->sCmn.bitrateDiff = 0;\r
107 \r
108                 /* Switch to a lower sample frequency */\r
109                 if( psEnc->sCmn.fs_kHz == 24 ) {\r
110                     fs_kHz = 16;\r
111                 } else if( psEnc->sCmn.fs_kHz == 16 ) {\r
112                     fs_kHz = 12;\r
113                 } else {\r
114                     SKP_assert( psEnc->sCmn.fs_kHz == 12 );\r
115                     fs_kHz = 8;\r
116                 }\r
117             }\r
118 \r
119             /* Check if we should switch up */\r
120             if( ( ( psEnc->sCmn.fs_kHz * 1000 < API_fs_Hz ) &&\r
121                 ( TargetRate_bps >= psEnc->sCmn.bitrate_threshold_up ) && \r
122                 ( psEnc->sCmn.sSWBdetect.WB_detected * psEnc->sCmn.fs_kHz != 16 ) ) && \r
123                 ( ( psEnc->sCmn.fs_kHz == 16 ) && ( max_internal_fs_kHz >= 24 ) || \r
124                   ( psEnc->sCmn.fs_kHz == 12 ) && ( max_internal_fs_kHz >= 16 ) ||\r
125                   ( psEnc->sCmn.fs_kHz ==  8 ) && ( max_internal_fs_kHz >= 12 ) ) \r
126 #if SWITCH_TRANSITION_FILTERING\r
127                   && ( psEnc->sCmn.sLP.transition_frame_no == 0 ) ) { /* No transition phase running, ready to switch */\r
128                     psEnc->sCmn.sLP.mode = 1; /* Switch up */\r
129 #else\r
130                 ) {\r
131 #endif\r
132                 psEnc->sCmn.bitrateDiff = 0;\r
133 \r
134                 /* Switch to a higher sample frequency */\r
135                 if( psEnc->sCmn.fs_kHz == 8 ) {\r
136                     fs_kHz = 12;\r
137                 } else if( psEnc->sCmn.fs_kHz == 12 ) {\r
138                     fs_kHz = 16;\r
139                 } else {\r
140                     SKP_assert( psEnc->sCmn.fs_kHz == 16 );\r
141                     fs_kHz = 24;\r
142                 } \r
143             }\r
144         }\r
145     }\r
146 \r
147 #if SWITCH_TRANSITION_FILTERING\r
148     /* After switching up, stop transition filter during speech inactivity */\r
149     if( ( psEnc->sCmn.sLP.mode == 1 ) &&\r
150         ( psEnc->sCmn.sLP.transition_frame_no >= TRANSITION_FRAMES_UP ) && \r
151         ( psEnc->speech_activity < 0.5f ) && \r
152         ( psEnc->sCmn.nFramesInPayloadBuf == 0 ) ) {\r
153         \r
154         psEnc->sCmn.sLP.transition_frame_no = 0;\r
155 \r
156         /* Reset transition filter state */\r
157         SKP_memset( psEnc->sCmn.sLP.In_LP_State, 0, 2 * sizeof( SKP_int32 ) );\r
158     }\r
159 #endif\r
160 \r
161     /********************************************/\r
162     /* Prepare resampler and buffered data      */    \r
163     /********************************************/\r
164     SKP_Silk_setup_resamplers( psEnc, API_fs_Hz, fs_kHz );\r
165 \r
166     /********************************************/\r
167     /* Set packet size                          */\r
168     /********************************************/\r
169     ret += SKP_Silk_setup_packetsize( psEnc, PacketSize_ms );\r
170 \r
171     /********************************************/\r
172     /* Set internal sampling frequency          */\r
173     /********************************************/\r
174     ret += SKP_Silk_setup_fs( psEnc, fs_kHz );\r
175 \r
176     /********************************************/\r
177     /* Set encoding complexity                  */\r
178     /********************************************/\r
179     ret += SKP_Silk_setup_complexity( psEnc, Complexity );\r
180 \r
181     /********************************************/\r
182     /* Set bitrate/coding quality               */\r
183     /********************************************/\r
184     ret += SKP_Silk_setup_rate( psEnc, TargetRate_bps );\r
185 \r
186     /********************************************/\r
187     /* Set packet loss rate measured by farend  */\r
188     /********************************************/\r
189     if( ( PacketLoss_perc < 0 ) || ( PacketLoss_perc > 100 ) ) {\r
190         ret = SKP_SILK_ENC_INVALID_LOSS_RATE;\r
191     }\r
192     psEnc->sCmn.PacketLoss_perc = PacketLoss_perc;\r
193 \r
194     /********************************************/\r
195     /* Set LBRR usage                           */\r
196     /********************************************/\r
197     ret += SKP_Silk_setup_LBRR( psEnc, INBandFEC_enabled );\r
198 \r
199     /********************************************/\r
200     /* Set DTX mode                             */\r
201     /********************************************/\r
202     if( DTX_enabled < 0 || DTX_enabled > 1 ) {\r
203         ret = SKP_SILK_ENC_INVALID_DTX_SETTING;\r
204     }\r
205     psEnc->sCmn.useDTX = DTX_enabled;\r
206 \r
207     return ret;\r
208 }\r
209 \r
210 /* Control low bitrate redundancy usage */\r
211 void SKP_Silk_LBRR_ctrl_FLP(\r
212     SKP_Silk_encoder_state_FLP      *psEnc,             /* I    Encoder state FLP                       */\r
213     SKP_Silk_encoder_control        *psEncCtrl          /* I/O  Encoder control                         */\r
214 )\r
215 {\r
216     SKP_int LBRR_usage;\r
217 \r
218     if( psEnc->sCmn.LBRR_enabled ) {\r
219         /* Control LBRR */\r
220 \r
221         /* Usage Control based on sensitivity and packet loss caracteristics */\r
222         /* For now only enable adding to next for active frames. Make more complex later */\r
223         LBRR_usage = SKP_SILK_NO_LBRR;\r
224         if( psEnc->speech_activity > LBRR_SPEECH_ACTIVITY_THRES && psEnc->sCmn.PacketLoss_perc > LBRR_LOSS_THRES ) { // nb! maybe multiply loss prob and speech activity \r
225             LBRR_usage = SKP_SILK_ADD_LBRR_TO_PLUS1;\r
226         }\r
227         psEncCtrl->LBRR_usage = LBRR_usage;\r
228     } else {\r
229         psEncCtrl->LBRR_usage = SKP_SILK_NO_LBRR;\r
230     }\r
231 }\r
232 \r
233 SKP_INLINE SKP_int SKP_Silk_setup_packetsize(\r
234     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
235     SKP_int                         PacketSize_ms       /* I                        */\r
236 )\r
237 {\r
238     SKP_int ret = SKP_SILK_NO_ERROR;\r
239     if( ( PacketSize_ms !=  10 ) &&\r
240         ( PacketSize_ms !=  20 ) &&\r
241         ( PacketSize_ms !=  40 ) && \r
242         ( PacketSize_ms !=  60 ) && \r
243         ( PacketSize_ms !=  80 ) && \r
244         ( PacketSize_ms != 100 ) ) {\r
245         ret = SKP_SILK_ENC_PACKET_SIZE_NOT_SUPPORTED;\r
246     } else {\r
247         if( PacketSize_ms != psEnc->sCmn.PacketSize_ms ) {\r
248             if( PacketSize_ms == 10 ) {\r
249                 if( psEnc->sCmn.nFramesInPayloadBuf == 0 ) {\r
250                     /* Only allowed when the payload buffer is empty */\r
251                     psEnc->sCmn.nb_subfr = MAX_NB_SUBFR >> 1;\r
252                     psEnc->sCmn.frame_length   = SKP_SMULBB( psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr );\r
253                     psEnc->sCmn.PacketSize_ms = PacketSize_ms;\r
254                     psEnc->sPred.pitch_LPC_win_length = SKP_SMULBB( FIND_PITCH_LPC_WIN_MS_2_SF, psEnc->sCmn.fs_kHz );\r
255                     /* Packet length changes. Reset LBRR buffer */\r
256                     SKP_Silk_LBRR_reset( &psEnc->sCmn );\r
257                 }\r
258             } else{\r
259                 psEnc->sCmn.nb_subfr = MAX_NB_SUBFR;\r
260                 psEnc->sCmn.frame_length   = SKP_SMULBB( psEnc->sCmn.subfr_length, psEnc->sCmn.nb_subfr );\r
261                 psEnc->sCmn.PacketSize_ms = PacketSize_ms;\r
262                 psEnc->sPred.pitch_LPC_win_length = SKP_SMULBB( FIND_PITCH_LPC_WIN_MS, psEnc->sCmn.fs_kHz );\r
263                 /* Packet length changes. Reset LBRR buffer */\r
264                 SKP_Silk_LBRR_reset( &psEnc->sCmn );\r
265             }\r
266         }\r
267     }\r
268     return(ret);\r
269 }\r
270 \r
271 SKP_INLINE SKP_int SKP_Silk_setup_resamplers(\r
272     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
273     SKP_int                         API_fs_Hz,          /* I                        */\r
274     SKP_int                         fs_kHz              /* I                        */\r
275 )\r
276 {\r
277     SKP_int ret = SKP_SILK_NO_ERROR;\r
278     \r
279     if( psEnc->sCmn.fs_kHz != fs_kHz || psEnc->sCmn.prev_API_fs_Hz != API_fs_Hz ) {\r
280 \r
281         /* Allocate space for worst case temporary upsampling, 8 to 48 kHz, so a factor 6 */\r
282         SKP_int16 x_buf_API_fs_Hz[ ( MAX_API_FS_KHZ / 8 ) * ( 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX ) ];\r
283         SKP_int16 x_bufFIX[               2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX ]; \r
284 \r
285         SKP_int32 nSamples_temp = 2 * psEnc->sCmn.frame_length + psEnc->sCmn.la_shape;\r
286 \r
287         SKP_float2short_array( x_bufFIX, psEnc->x_buf, 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX );\r
288 \r
289         if( fs_kHz * 1000 < API_fs_Hz && psEnc->sCmn.fs_kHz != 0 ) {\r
290             /* Resample buffered data in x_buf to API_fs_Hz */\r
291 \r
292             SKP_Silk_resampler_state_struct  temp_resampler_state;\r
293 \r
294             /* Initialize resampler for temporary resampling of x_buf data to API_fs_Hz */\r
295             ret += SKP_Silk_resampler_init( &temp_resampler_state, psEnc->sCmn.fs_kHz * 1000, API_fs_Hz );\r
296 \r
297             /* Temporary resampling of x_buf data to API_fs_Hz */\r
298             ret += SKP_Silk_resampler( &temp_resampler_state, x_buf_API_fs_Hz, x_bufFIX, nSamples_temp );\r
299 \r
300             /* Calculate number of samples that has been temporarily upsampled */\r
301             nSamples_temp = SKP_DIV32_16( nSamples_temp * API_fs_Hz, psEnc->sCmn.fs_kHz * 1000 );\r
302 \r
303             /* Initialize the resampler for enc_API.c preparing resampling from API_fs_Hz to fs_kHz */\r
304             ret += SKP_Silk_resampler_init( &psEnc->sCmn.resampler_state, API_fs_Hz, fs_kHz * 1000 );\r
305 \r
306         } else {\r
307             /* Copy data */\r
308             SKP_memcpy( x_buf_API_fs_Hz, x_bufFIX, nSamples_temp * sizeof( SKP_int16 ) );\r
309         }\r
310 \r
311         if( 1000 * fs_kHz != API_fs_Hz ) {\r
312             /* Correct resampler state (unless resampling by a factor 1) by resampling buffered data from API_fs_Hz to fs_kHz */\r
313             ret += SKP_Silk_resampler( &psEnc->sCmn.resampler_state, x_bufFIX, x_buf_API_fs_Hz, nSamples_temp );\r
314         }\r
315         SKP_short2float_array( psEnc->x_buf, x_bufFIX, 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX );\r
316     }\r
317 \r
318     psEnc->sCmn.prev_API_fs_Hz = API_fs_Hz;\r
319 \r
320     return(ret);\r
321 }\r
322 \r
323 SKP_INLINE SKP_int SKP_Silk_setup_fs(\r
324     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
325     SKP_int                         fs_kHz              /* I                        */\r
326 )\r
327 {\r
328     SKP_int ret = SKP_SILK_NO_ERROR;\r
329 \r
330     /* Set internal sampling frequency */\r
331     if( psEnc->sCmn.fs_kHz != fs_kHz ) {\r
332         /* reset part of the state */\r
333         SKP_memset( &psEnc->sShape,          0,                            sizeof( SKP_Silk_shape_state_FLP ) );\r
334         SKP_memset( &psEnc->sPrefilt,        0,                            sizeof( SKP_Silk_prefilter_state_FLP ) );\r
335         SKP_memset( &psEnc->sNSQ,            0,                            sizeof( SKP_Silk_nsq_state ) );\r
336         SKP_memset( &psEnc->sPred,           0,                            sizeof( SKP_Silk_predict_state_FLP ) );\r
337         SKP_memset( psEnc->sNSQ.xq,          0, ( 2 * MAX_FRAME_LENGTH ) * sizeof( SKP_int16 ) );\r
338         SKP_memset( psEnc->sNSQ_LBRR.xq,     0, ( 2 * MAX_FRAME_LENGTH ) * sizeof( SKP_int16 ) );\r
339         SKP_memset( psEnc->sCmn.LBRR_buffer, 0,           MAX_LBRR_DELAY * sizeof( SKP_SILK_LBRR_struct ) );\r
340 #if SWITCH_TRANSITION_FILTERING\r
341         SKP_memset( psEnc->sCmn.sLP.In_LP_State, 0, 2 * sizeof( SKP_int32 ) );\r
342         if( psEnc->sCmn.sLP.mode == 1 ) {\r
343             /* Begin transition phase */\r
344             psEnc->sCmn.sLP.transition_frame_no = 1;\r
345         } else {\r
346             /* End transition phase */\r
347             psEnc->sCmn.sLP.transition_frame_no = 0;\r
348         }\r
349 #endif\r
350         psEnc->sCmn.inputBufIx          = 0;\r
351         psEnc->sCmn.nFramesInPayloadBuf = 0;\r
352         psEnc->sCmn.nBytesInPayloadBuf  = 0;\r
353         psEnc->sCmn.oldest_LBRR_idx     = 0;\r
354         psEnc->sCmn.TargetRate_bps      = 0; /* Ensures that psEnc->SNR_dB is recomputed */\r
355 \r
356         SKP_memset( psEnc->sPred.prev_NLSFq, 0, MAX_LPC_ORDER * sizeof( SKP_float ) );\r
357 \r
358         /* Initialize non-zero parameters */\r
359         psEnc->sCmn.prevLag                 = 100;\r
360         psEnc->sCmn.prev_sigtype            = SIG_TYPE_UNVOICED;\r
361         psEnc->sCmn.first_frame_after_reset = 1;\r
362         psEnc->sPrefilt.lagPrev             = 100;\r
363         psEnc->sShape.LastGainIndex         = 1;\r
364         psEnc->sNSQ.lagPrev                 = 100;\r
365         psEnc->sNSQ.prev_inv_gain_Q16       = 65536;\r
366         psEnc->sNSQ_LBRR.prev_inv_gain_Q16  = 65536;\r
367 \r
368         psEnc->sCmn.fs_kHz = fs_kHz;\r
369         if( psEnc->sCmn.fs_kHz == 8 ) {\r
370             psEnc->sCmn.predictLPCOrder = MIN_LPC_ORDER;\r
371             psEnc->sCmn.psNLSF_CB[ 0 ]  = &SKP_Silk_NLSF_CB0_10;\r
372             psEnc->sCmn.psNLSF_CB[ 1 ]  = &SKP_Silk_NLSF_CB1_10;\r
373             psEnc->psNLSF_CB_FLP[  0 ]  = &SKP_Silk_NLSF_CB0_10_FLP;\r
374             psEnc->psNLSF_CB_FLP[  1 ]  = &SKP_Silk_NLSF_CB1_10_FLP;\r
375         } else {\r
376             psEnc->sCmn.predictLPCOrder = MAX_LPC_ORDER;\r
377             psEnc->sCmn.psNLSF_CB[ 0 ]  = &SKP_Silk_NLSF_CB0_16;\r
378             psEnc->sCmn.psNLSF_CB[ 1 ]  = &SKP_Silk_NLSF_CB1_16;\r
379             psEnc->psNLSF_CB_FLP[  0 ]  = &SKP_Silk_NLSF_CB0_16_FLP;\r
380             psEnc->psNLSF_CB_FLP[  1 ]  = &SKP_Silk_NLSF_CB1_16_FLP;\r
381         }\r
382         psEnc->sCmn.subfr_length   = SUB_FRAME_LENGTH_MS * fs_kHz;\r
383         psEnc->sCmn.frame_length   = psEnc->sCmn.subfr_length * psEnc->sCmn.nb_subfr;\r
384         psEnc->sCmn.ltp_mem_length = LTP_MEM_LENGTH_MS * fs_kHz; \r
385         psEnc->sCmn.la_pitch       = LA_PITCH_MS * fs_kHz;\r
386         psEnc->sCmn.la_shape       = LA_SHAPE_MS * fs_kHz;\r
387         psEnc->sPred.min_pitch_lag =  3 * fs_kHz;\r
388         psEnc->sPred.max_pitch_lag = 18 * fs_kHz;\r
389         if( psEnc->sCmn.nb_subfr == MAX_NB_SUBFR ){\r
390             psEnc->sPred.pitch_LPC_win_length = SKP_SMULBB( FIND_PITCH_LPC_WIN_MS, fs_kHz );\r
391         } else {\r
392             psEnc->sPred.pitch_LPC_win_length = SKP_SMULBB( FIND_PITCH_LPC_WIN_MS_2_SF, fs_kHz );\r
393         }\r
394         if( psEnc->sCmn.fs_kHz == 24 ) {\r
395             psEnc->mu_LTP = MU_LTP_QUANT_SWB;\r
396             psEnc->sCmn.bitrate_threshold_up   = SKP_int32_MAX;\r
397             psEnc->sCmn.bitrate_threshold_down = SWB2WB_BITRATE_BPS; \r
398         } else if( psEnc->sCmn.fs_kHz == 16 ) {\r
399             psEnc->mu_LTP = MU_LTP_QUANT_WB;\r
400             psEnc->sCmn.bitrate_threshold_up   = WB2SWB_BITRATE_BPS;\r
401             psEnc->sCmn.bitrate_threshold_down = WB2MB_BITRATE_BPS; \r
402         } else if( psEnc->sCmn.fs_kHz == 12 ) {\r
403             psEnc->mu_LTP = MU_LTP_QUANT_MB;\r
404             psEnc->sCmn.bitrate_threshold_up   = MB2WB_BITRATE_BPS;\r
405             psEnc->sCmn.bitrate_threshold_down = MB2NB_BITRATE_BPS;\r
406         } else {\r
407             psEnc->mu_LTP = MU_LTP_QUANT_NB;\r
408             psEnc->sCmn.bitrate_threshold_up   = NB2MB_BITRATE_BPS;\r
409             psEnc->sCmn.bitrate_threshold_down = 0;\r
410         }\r
411         psEnc->sCmn.fs_kHz_changed = 1;\r
412 \r
413         /* Check that settings are valid */\r
414         SKP_assert( ( psEnc->sCmn.subfr_length * psEnc->sCmn.nb_subfr ) == psEnc->sCmn.frame_length );\r
415     }\r
416     return( ret );\r
417 }\r
418 \r
419 SKP_INLINE SKP_int SKP_Silk_setup_complexity(\r
420     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
421     SKP_int                         Complexity          /* I                        */\r
422 )\r
423 {\r
424     SKP_int ret = SKP_SILK_NO_ERROR;\r
425 \r
426     /* Check that settings are valid */\r
427     if( LOW_COMPLEXITY_ONLY && Complexity != 0 ) { \r
428         ret = SKP_SILK_ENC_INVALID_COMPLEXITY_SETTING;\r
429     }\r
430 \r
431     /* Set encoding complexity */\r
432     if( Complexity == 0 || LOW_COMPLEXITY_ONLY ) {\r
433         /* Low complexity */\r
434         psEnc->sCmn.Complexity                  = 0;\r
435         psEnc->sCmn.pitchEstimationComplexity   = PITCH_EST_COMPLEXITY_LC_MODE;\r
436         psEnc->pitchEstimationThreshold         = FIND_PITCH_CORRELATION_THRESHOLD_LC_MODE;\r
437         psEnc->sCmn.pitchEstimationLPCOrder     = 8;\r
438         psEnc->sCmn.shapingLPCOrder             = 8;\r
439         psEnc->sCmn.nStatesDelayedDecision      = 1;\r
440         psEnc->sCmn.useInterpolatedNLSFs        = 0;\r
441         psEnc->sCmn.LTPQuantLowComplexity       = 1;\r
442         psEnc->sCmn.NLSF_MSVQ_Survivors         = MAX_NLSF_MSVQ_SURVIVORS_LC_MODE;\r
443     } else if( Complexity == 1 ) {\r
444         /* Medium complexity */\r
445         psEnc->sCmn.Complexity                  = 1;\r
446         psEnc->sCmn.pitchEstimationComplexity   = PITCH_EST_COMPLEXITY_MC_MODE;\r
447         psEnc->pitchEstimationThreshold         = FIND_PITCH_CORRELATION_THRESHOLD_MC_MODE;\r
448         psEnc->sCmn.pitchEstimationLPCOrder     = 12;\r
449         psEnc->sCmn.shapingLPCOrder             = 12;\r
450         psEnc->sCmn.nStatesDelayedDecision      = 2;\r
451         psEnc->sCmn.useInterpolatedNLSFs        = 0;\r
452         psEnc->sCmn.LTPQuantLowComplexity       = 0;\r
453         psEnc->sCmn.NLSF_MSVQ_Survivors         = MAX_NLSF_MSVQ_SURVIVORS_MC_MODE;\r
454     } else if( Complexity == 2 ) {\r
455         /* High complexity */\r
456         psEnc->sCmn.Complexity                  = 2;\r
457         psEnc->sCmn.pitchEstimationComplexity   = PITCH_EST_COMPLEXITY_HC_MODE;\r
458         psEnc->pitchEstimationThreshold         = FIND_PITCH_CORRELATION_THRESHOLD_HC_MODE;\r
459         psEnc->sCmn.pitchEstimationLPCOrder     = 16;\r
460         psEnc->sCmn.shapingLPCOrder             = 16;\r
461         psEnc->sCmn.nStatesDelayedDecision      = 4;\r
462         psEnc->sCmn.useInterpolatedNLSFs        = 1;\r
463         psEnc->sCmn.LTPQuantLowComplexity       = 0;\r
464         psEnc->sCmn.NLSF_MSVQ_Survivors         = MAX_NLSF_MSVQ_SURVIVORS;\r
465     } else {\r
466         ret = SKP_SILK_ENC_INVALID_COMPLEXITY_SETTING;\r
467     }\r
468 \r
469     /* Do not allow higher pitch estimation LPC order than predict LPC order */\r
470     psEnc->sCmn.pitchEstimationLPCOrder = SKP_min_int( psEnc->sCmn.pitchEstimationLPCOrder, psEnc->sCmn.predictLPCOrder );\r
471 \r
472     SKP_assert( psEnc->sCmn.pitchEstimationLPCOrder <= MAX_FIND_PITCH_LPC_ORDER );\r
473     SKP_assert( psEnc->sCmn.shapingLPCOrder         <= MAX_SHAPE_LPC_ORDER      );\r
474     SKP_assert( psEnc->sCmn.nStatesDelayedDecision  <= MAX_DEL_DEC_STATES       );\r
475     return( ret );\r
476 }\r
477 \r
478 SKP_INLINE SKP_int SKP_Silk_setup_rate(\r
479     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
480     SKP_int                         TargetRate_bps      /* I                        */\r
481 )\r
482 {\r
483     SKP_int k, ret = SKP_SILK_NO_ERROR;\r
484     SKP_float frac;\r
485     const SKP_int32 *rateTable;\r
486 \r
487     /* Set bitrate/coding quality */\r
488     TargetRate_bps = SKP_min( TargetRate_bps, 100000 );\r
489     if( psEnc->sCmn.fs_kHz == 8 ) {\r
490         TargetRate_bps = SKP_max( TargetRate_bps, MIN_TARGET_RATE_NB_BPS );\r
491     } else if( psEnc->sCmn.fs_kHz == 12 ) {\r
492         TargetRate_bps = SKP_max( TargetRate_bps, MIN_TARGET_RATE_MB_BPS );\r
493     } else if( psEnc->sCmn.fs_kHz == 16 ) {\r
494         TargetRate_bps = SKP_max( TargetRate_bps, MIN_TARGET_RATE_WB_BPS );\r
495     } else {\r
496         TargetRate_bps = SKP_max( TargetRate_bps, MIN_TARGET_RATE_SWB_BPS );\r
497     }\r
498     if( TargetRate_bps != psEnc->sCmn.TargetRate_bps ) {\r
499         psEnc->sCmn.TargetRate_bps = TargetRate_bps;\r
500 \r
501         /* If new TargetRate_bps, translate to SNR_dB value */\r
502         if( psEnc->sCmn.fs_kHz == 8 ) {\r
503             rateTable = TargetRate_table_NB;\r
504         } else if( psEnc->sCmn.fs_kHz == 12 ) {\r
505             rateTable = TargetRate_table_MB;\r
506         } else if( psEnc->sCmn.fs_kHz == 16 ) {\r
507             rateTable = TargetRate_table_WB;\r
508         } else {\r
509             rateTable = TargetRate_table_SWB;\r
510         }\r
511         for( k = 1; k < TARGET_RATE_TAB_SZ; k++ ) {\r
512             /* Find bitrate interval in table and interpolate */\r
513             if( TargetRate_bps < rateTable[ k ] ) {\r
514                 frac = (SKP_float)( TargetRate_bps - rateTable[ k - 1 ] ) / \r
515                        (SKP_float)( rateTable[ k ] - rateTable[ k - 1 ] );\r
516                 psEnc->SNR_dB = 0.5f * ( SNR_table_Q1[ k - 1 ] + frac * ( SNR_table_Q1[ k ] - SNR_table_Q1[ k - 1 ] ) );\r
517                 break;\r
518             }\r
519         }\r
520     }\r
521     return( ret );\r
522 }\r
523 \r
524 SKP_INLINE SKP_int SKP_Silk_setup_LBRR(\r
525     SKP_Silk_encoder_state_FLP      *psEnc,             /* I/O                      */\r
526     SKP_int                         INBandFEC_enabled   /* I                        */\r
527 )\r
528 {\r
529     SKP_int   ret = SKP_SILK_NO_ERROR;\r
530     SKP_int32 LBRRRate_thres_bps;\r
531 \r
532 #if USE_LBRR\r
533     if( INBandFEC_enabled < 0 || INBandFEC_enabled > 1 ) {\r
534         ret = SKP_SILK_ENC_INVALID_INBAND_FEC_SETTING;\r
535     }\r
536     \r
537     /* Only change settings if first frame in packet */\r
538     if( psEnc->sCmn.nFramesInPayloadBuf == 0 ) {\r
539         \r
540         psEnc->sCmn.LBRR_enabled = INBandFEC_enabled;\r
541         if( psEnc->sCmn.fs_kHz == 8 ) {\r
542             LBRRRate_thres_bps = INBAND_FEC_MIN_RATE_BPS - 9000;\r
543         } else if( psEnc->sCmn.fs_kHz == 12 ) {\r
544             LBRRRate_thres_bps = INBAND_FEC_MIN_RATE_BPS - 6000;;\r
545         } else if( psEnc->sCmn.fs_kHz == 16 ) {\r
546             LBRRRate_thres_bps = INBAND_FEC_MIN_RATE_BPS - 3000;\r
547         } else {\r
548             LBRRRate_thres_bps = INBAND_FEC_MIN_RATE_BPS;\r
549         }\r
550 \r
551         if( psEnc->sCmn.TargetRate_bps >= LBRRRate_thres_bps ) {\r
552             /* Set gain increase / rate reduction for LBRR usage */\r
553             /* Coarsely tuned with PESQ for now. */\r
554             /* Linear regression coefs G = 8 - 0.5 * loss */\r
555             /* Meaning that at 16% loss main rate and redundant rate is the same, -> G = 0 */\r
556             psEnc->sCmn.LBRR_GainIncreases = SKP_max_int( 8 - SKP_RSHIFT( psEnc->sCmn.PacketLoss_perc, 1 ), 0 );\r
557 \r
558             /* Set main stream rate compensation */\r
559             if( psEnc->sCmn.LBRR_enabled && psEnc->sCmn.PacketLoss_perc > LBRR_LOSS_THRES ) {\r
560                 /* Tuned to give aprox same mean / weighted bitrate as no inband FEC */\r
561                 psEnc->inBandFEC_SNR_comp = 6.0f - 0.5f * psEnc->sCmn.LBRR_GainIncreases;\r
562             } else {\r
563                 psEnc->inBandFEC_SNR_comp = 0;\r
564                 psEnc->sCmn.LBRR_enabled  = 0;\r
565             }\r
566         } else {\r
567             psEnc->inBandFEC_SNR_comp     = 0;\r
568             psEnc->sCmn.LBRR_enabled      = 0;\r
569         }\r
570     }\r
571 #else\r
572     if( INBandFEC_enabled != 0 ) {\r
573         ret = SKP_SILK_ENC_INVALID_INBAND_FEC_SETTING;\r
574     }\r
575     psEnc->sCmn.LBRR_enabled = 0;\r
576 #endif\r
577     return( ret );\r
578 }\r