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