Git init
[external/opencore-amr.git] / opencore / codecs_v2 / audio / gsm_amr / amr_nb / enc / src / cod_amr.cpp
1 /* ------------------------------------------------------------------
2  * Copyright (C) 1998-2009 PacketVideo
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13  * express or implied.
14  * See the License for the specific language governing permissions
15  * and limitations under the License.
16  * -------------------------------------------------------------------
17  */
18 /****************************************************************************************
19 Portions of this file are derived from the following 3GPP standard:
20
21     3GPP TS 26.073
22     ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
23     Available from http://www.3gpp.org
24
25 (C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
26 Permission to distribute, modify and use this file under the standard license
27 terms listed above has been obtained from the copyright holder.
28 ****************************************************************************************/
29 /*
30 ------------------------------------------------------------------------------
31
32
33
34  Filename: cod_amr.cpp
35  Functions: cod_amr_init
36            cod_amr_reset
37            cod_amr_exit
38            cod_amr_first
39            cod_amr
40
41 ------------------------------------------------------------------------------
42  MODULE DESCRIPTION
43
44  These functions comprise the main encoder routine operating on a frame basis.
45
46 ------------------------------------------------------------------------------
47 */
48
49
50 /*----------------------------------------------------------------------------
51 ; INCLUDES
52 ----------------------------------------------------------------------------*/
53 #include "cod_amr.h"
54 #include "typedef.h"
55 #include "cnst.h"
56 #include "qua_gain.h"
57 #include "lpc.h"
58 #include "lsp.h"
59 #include "pre_big.h"
60 #include "ol_ltp.h"
61 #include "p_ol_wgh.h"
62 #include "spreproc.h"
63 #include "cl_ltp.h"
64 #include "pred_lt.h"
65 #include "spstproc.h"
66 #include "cbsearch.h"
67 #include "gain_q.h"
68 #include "convolve.h"
69 #include "ton_stab.h"
70 #include "vad.h"
71 #include "dtx_enc.h"
72 #include "oscl_mem.h"
73
74 #ifdef VAD2
75 #include "vad2.h"
76 #endif
77
78 /*----------------------------------------------------------------------------
79 ; MACROS
80 ; Define module specific macros here
81 ----------------------------------------------------------------------------*/
82
83
84 /*----------------------------------------------------------------------------
85 ; DEFINES
86 ; Include all pre-processor statements here. Include conditional
87 ; compile variables also.
88 ----------------------------------------------------------------------------*/
89
90 /*----------------------------------------------------------------------------
91 ; LOCAL FUNCTION DEFINITIONS
92 ; Function Prototype declaration
93 ----------------------------------------------------------------------------*/
94
95 /*----------------------------------------------------------------------------
96 ; LOCAL VARIABLE DEFINITIONS
97 ; Variable declaration - defined here and used outside this module
98 ----------------------------------------------------------------------------*/
99
100 /* Spectral expansion factors */
101
102 static const Word16 gamma1[M] =
103 {
104     30802, 28954, 27217, 25584, 24049,
105     22606, 21250, 19975, 18777, 17650
106 };
107
108 /* gamma1 differs for the 12k2 coder */
109 static const Word16 gamma1_12k2[M] =
110 {
111     29491, 26542, 23888, 21499, 19349,
112     17414, 15672, 14105, 12694, 11425
113 };
114
115 static const Word16 gamma2[M] =
116 {
117     19661, 11797, 7078, 4247, 2548,
118     1529, 917, 550, 330, 198
119 };
120
121
122 /*
123 ------------------------------------------------------------------------------
124  FUNCTION NAME: cod_amr_init
125 ------------------------------------------------------------------------------
126  INPUT AND OUTPUT DEFINITIONS
127
128  Inputs:
129     state = pointer to a pointer to a structure of type cod_amrState
130
131  Outputs:
132     Structure pointed to by the pointer pointed to by state is
133       initialized to its reset value
134     state points to the allocated memory
135
136  Returns:
137     Returns 0 if memory was successfully initialized,
138         otherwise returns -1.
139
140  Global Variables Used:
141     None.
142
143  Local Variables Needed:
144     None.
145
146 ------------------------------------------------------------------------------
147  FUNCTION DESCRIPTION
148
149  This function allocates memory and initializes state variables.
150
151 ------------------------------------------------------------------------------
152  REQUIREMENTS
153
154  None.
155
156 ------------------------------------------------------------------------------
157  REFERENCES
158
159  cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
160
161 ------------------------------------------------------------------------------
162  PSEUDO-CODE
163
164 int cod_amr_init (cod_amrState **state, Flag dtx)
165 {
166   cod_amrState* s;
167
168   if (state == (cod_amrState **) NULL){
169       fprintf(stderr, "cod_amr_init: invalid parameter\n");
170       return -1;
171   }
172   *state = NULL;
173
174   // allocate memory
175   if ((s= (cod_amrState *) malloc(sizeof(cod_amrState))) == NULL){
176       fprintf(stderr, "cod_amr_init: can not malloc state structure\n");
177       return -1;
178   }
179
180   s->lpcSt = NULL;
181   s->lspSt = NULL;
182   s->clLtpSt = NULL;
183   s->gainQuantSt = NULL;
184   s->pitchOLWghtSt = NULL;
185   s->tonStabSt = NULL;
186   s->vadSt = NULL;
187   s->dtx_encSt = NULL;
188   s->dtx = dtx;
189
190   // Init sub states
191   if (cl_ltp_init(&s->clLtpSt) ||
192       lsp_init(&s->lspSt) ||
193       gainQuant_init(&s->gainQuantSt) ||
194       p_ol_wgh_init(&s->pitchOLWghtSt) ||
195       ton_stab_init(&s->tonStabSt) ||
196 #ifndef VAD2
197       vad1_init(&s->vadSt) ||
198 #else
199       vad2_init(&s->vadSt) ||
200 #endif
201       dtx_enc_init(&s->dtx_encSt) ||
202       lpc_init(&s->lpcSt)) {
203      cod_amr_exit(&s);
204      return -1;
205   }
206
207   cod_amr_reset(s);
208
209   *state = s;
210
211   return 0;
212 }
213
214 ------------------------------------------------------------------------------
215  CAUTION [optional]
216  [State any special notes, constraints or cautions for users of this function]
217
218 ------------------------------------------------------------------------------
219 */
220
221 Word16 cod_amr_init(cod_amrState **state, Flag dtx)
222 {
223     cod_amrState* s;
224
225     if (state == (cod_amrState **) NULL)
226     {
227         /* fprint(stderr, "cod_amr_init: invalid parameter\n");  */
228         return(-1);
229     }
230     *state = NULL;
231
232     /* allocate memory */
233     if ((s = (cod_amrState *) oscl_malloc(sizeof(cod_amrState))) == NULL)
234     {
235         /* fprint(stderr, "cod_amr_init:
236                            can not malloc state structure\n");  */
237         return(-1);
238     }
239
240     get_const_tbls(&s->common_amr_tbls);
241
242     s->lpcSt = NULL;
243     s->lspSt = NULL;
244     s->clLtpSt = NULL;
245     s->gainQuantSt = NULL;
246     s->pitchOLWghtSt = NULL;
247     s->tonStabSt = NULL;
248     s->vadSt = NULL;
249     s->dtx_encSt = NULL;
250     s->dtx = dtx;
251
252     /* Initialize overflow Flag */
253
254     s->overflow = 0;
255
256
257     /* Init sub states */
258     if (cl_ltp_init(&s->clLtpSt) ||
259             lsp_init(&s->lspSt) ||
260             gainQuant_init(&s->gainQuantSt) ||
261             p_ol_wgh_init(&s->pitchOLWghtSt) ||
262             ton_stab_init(&s->tonStabSt) ||
263 #ifndef VAD2
264             vad1_init(&s->vadSt) ||
265 #else
266             vad2_init(&s->vadSt) ||
267 #endif
268             dtx_enc_init(&s->dtx_encSt, s->common_amr_tbls.lsp_init_data_ptr) ||
269             lpc_init(&s->lpcSt))
270     {
271         cod_amr_exit(&s);
272         return(-1);
273     }
274
275     cod_amr_reset(s);
276
277     *state = s;
278
279     return(0);
280 }
281
282 /****************************************************************************/
283
284 /*
285 ------------------------------------------------------------------------------
286  FUNCTION NAME: cod_amr_reset
287 ------------------------------------------------------------------------------
288  INPUT AND OUTPUT DEFINITIONS
289
290  Inputs:
291     state = pointer to a structure of type cod_amrState
292
293  Outputs:
294     Structure pointed to by state is initialized to initial values.
295
296  Returns:
297     Returns 0 if memory was successfully initialized,
298         otherwise returns -1.
299
300  Global Variables Used:
301     None.
302
303  Local Variables Needed:
304     None.
305
306 ------------------------------------------------------------------------------
307  FUNCTION DESCRIPTION
308
309  This function resets the state memory for cod_amr.
310
311 ------------------------------------------------------------------------------
312  REQUIREMENTS
313
314  None.
315
316 ------------------------------------------------------------------------------
317  REFERENCES
318
319  cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
320
321 ------------------------------------------------------------------------------
322  PSEUDO-CODE
323
324 int cod_amr_reset (cod_amrState *st)
325 {
326    Word16 i;
327
328    if (st == (cod_amrState *) NULL){
329       fprintf(stderr, "cod_amr_reset: invalid parameter\n");
330       return -1;
331    }
332
333     *-----------------------------------------------------------------------*
334     *          Initialize pointers to speech vector.                        *
335     *-----------------------------------------------------------------------*
336
337    st->new_speech = st->old_speech + L_TOTAL - L_FRAME;   // New speech
338
339    st->speech = st->new_speech - L_NEXT;                  // Present frame
340
341    st->p_window = st->old_speech + L_TOTAL - L_WINDOW;    // For LPC window
342    st->p_window_12k2 = st->p_window - L_NEXT; // EFR LPC window: no lookahead
343
344    // Initialize static pointers
345
346    st->wsp = st->old_wsp + PIT_MAX;
347    st->exc = st->old_exc + PIT_MAX + L_INTERPOL;
348    st->zero = st->ai_zero + MP1;
349    st->error = st->mem_err + M;
350    st->h1 = &st->hvec[L_SUBFR];
351
352    // Static vectors to zero
353
354    Set_zero(st->old_speech, L_TOTAL);
355    Set_zero(st->old_exc,    PIT_MAX + L_INTERPOL);
356    Set_zero(st->old_wsp,    PIT_MAX);
357    Set_zero(st->mem_syn,    M);
358    Set_zero(st->mem_w,      M);
359    Set_zero(st->mem_w0,     M);
360    Set_zero(st->mem_err,    M);
361    Set_zero(st->zero,       L_SUBFR);
362    Set_zero(st->hvec,       L_SUBFR);    // set to zero "h1[-L_SUBFR..-1]"
363
364    // OL LTP states
365    for (i = 0; i < 5; i++)
366    {
367       st->old_lags[i] = 40;
368    }
369
370    // Reset lpc states
371    lpc_reset(st->lpcSt);
372
373    // Reset lsp states
374    lsp_reset(st->lspSt);
375
376    // Reset clLtp states
377    cl_ltp_reset(st->clLtpSt);
378
379    gainQuant_reset(st->gainQuantSt);
380
381    p_ol_wgh_reset(st->pitchOLWghtSt);
382
383    ton_stab_reset(st->tonStabSt);
384
385 #ifndef VAD2
386    vad1_reset(st->vadSt);
387 #else
388    vad2_reset(st->vadSt);
389 #endif
390
391    dtx_enc_reset(st->dtx_encSt);
392
393    st->sharp = SHARPMIN;
394
395    return 0;
396 }
397
398 ------------------------------------------------------------------------------
399  CAUTION [optional]
400  [State any special notes, constraints or cautions for users of this function]
401
402 ------------------------------------------------------------------------------
403 */
404
405 Word16 cod_amr_reset(cod_amrState *st)
406 {
407     Word16 i;
408
409     if (st == (cod_amrState *) NULL)
410     {
411         /* fprint(stderr, "cod_amr_reset: invalid parameter\n");  */
412         return(-1);
413     }
414
415     /*-----------------------------------------------------------------------*
416      *          Initialize pointers to speech vector.                        *
417      *-----------------------------------------------------------------------*/
418
419     st->new_speech = st->old_speech + L_TOTAL - L_FRAME;   /* New speech     */
420
421     st->speech = st->new_speech - L_NEXT;                  /* Present frame  */
422
423     st->p_window = st->old_speech + L_TOTAL - L_WINDOW;    /* For LPC window */
424     st->p_window_12k2 = st->p_window - L_NEXT; /* EFR LPC window: no lookahead */
425
426     /* Initialize static pointers */
427
428     st->wsp = st->old_wsp + PIT_MAX;
429     st->exc = st->old_exc + PIT_MAX + L_INTERPOL;
430     st->zero = st->ai_zero + MP1;
431     st->error = st->mem_err + M;
432     st->h1 = &st->hvec[L_SUBFR];
433
434     /* Initialize overflow Flag */
435
436     st->overflow = 0;
437
438     /* Static vectors to zero */
439     oscl_memset(st->old_speech, 0, sizeof(Word16)*L_TOTAL);
440     oscl_memset(st->old_exc, 0,    sizeof(Word16)*(PIT_MAX + L_INTERPOL));
441     oscl_memset(st->old_wsp, 0,    sizeof(Word16)*PIT_MAX);
442     oscl_memset(st->mem_syn, 0,    sizeof(Word16)*M);
443     oscl_memset(st->mem_w,   0,    sizeof(Word16)*M);
444     oscl_memset(st->mem_w0,  0,    sizeof(Word16)*M);
445     oscl_memset(st->mem_err, 0,    sizeof(Word16)*M);
446     oscl_memset(st->zero, 0,       sizeof(Word16)*L_SUBFR);
447     oscl_memset(st->hvec, 0,       sizeof(Word16)*L_SUBFR);    /* set to zero "h1[-L_SUBFR..-1]" */
448
449     /* OL LTP states */
450     for (i = 0; i < 5; i++)
451     {
452         st->old_lags[i] = 40;
453     }
454
455     /* Reset lpc states */
456     lpc_reset(st->lpcSt);
457
458     /* Reset lsp states */
459     lsp_reset(st->lspSt);
460
461     /* Reset clLtp states */
462     cl_ltp_reset(st->clLtpSt);
463
464     gainQuant_reset(st->gainQuantSt);
465
466     p_ol_wgh_reset(st->pitchOLWghtSt);
467
468     ton_stab_reset(st->tonStabSt);
469
470 #ifndef VAD2
471     vad1_reset(st->vadSt);
472 #else
473     vad2_reset(st->vadSt);
474 #endif
475
476     dtx_enc_reset(st->dtx_encSt, st->common_amr_tbls.lsp_init_data_ptr);
477
478     st->sharp = SHARPMIN;
479
480     return(0);
481 }
482
483 /****************************************************************************/
484
485 /*
486 ------------------------------------------------------------------------------
487  FUNCTION NAME: cod_amr_exit
488 ------------------------------------------------------------------------------
489  INPUT AND OUTPUT DEFINITIONS
490
491  Inputs:
492     state = pointer to a pointer to a structure of type cod_amrState
493
494  Outputs:
495     state points to a NULL address
496
497  Returns:
498     None.
499
500  Global Variables Used:
501     None.
502
503  Local Variables Needed:
504     None.
505
506 ------------------------------------------------------------------------------
507  FUNCTION DESCRIPTION
508
509  This function frees the memory used for state memory.
510
511 ------------------------------------------------------------------------------
512  REQUIREMENTS
513
514  None.
515
516 ------------------------------------------------------------------------------
517  REFERENCES
518
519  cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
520
521 ------------------------------------------------------------------------------
522  PSEUDO-CODE
523
524 void cod_amr_exit (cod_amrState **state)
525 {
526    if (state == NULL || *state == NULL)
527       return;
528
529    // dealloc members
530    lpc_exit(&(*state)->lpcSt);
531    lsp_exit(&(*state)->lspSt);
532    gainQuant_exit(&(*state)->gainQuantSt);
533    cl_ltp_exit(&(*state)->clLtpSt);
534    p_ol_wgh_exit(&(*state)->pitchOLWghtSt);
535    ton_stab_exit(&(*state)->tonStabSt);
536 #ifndef VAD2
537    vad1_exit(&(*state)->vadSt);
538 #else
539    vad2_exit(&(*state)->vadSt);
540 #endif
541    dtx_enc_exit(&(*state)->dtx_encSt);
542
543    // deallocate memory
544    free(*state);
545    *state = NULL;
546
547    return;
548 }
549
550 ------------------------------------------------------------------------------
551  CAUTION [optional]
552  [State any special notes, constraints or cautions for users of this function]
553
554 ------------------------------------------------------------------------------
555 */
556
557 void cod_amr_exit(cod_amrState **state)
558 {
559     if (state == NULL || *state == NULL)
560     {
561         return;
562     }
563
564     /* dealloc members */
565     lpc_exit(&(*state)->lpcSt);
566     lsp_exit(&(*state)->lspSt);
567     gainQuant_exit(&(*state)->gainQuantSt);
568     cl_ltp_exit(&(*state)->clLtpSt);
569     p_ol_wgh_exit(&(*state)->pitchOLWghtSt);
570     ton_stab_exit(&(*state)->tonStabSt);
571 #ifndef VAD2
572     vad1_exit(&(*state)->vadSt);
573 #else
574     vad2_exit(&(*state)->vadSt);
575 #endif
576     dtx_enc_exit(&(*state)->dtx_encSt);
577
578     /* deallocate memory */
579     oscl_free(*state); // BX
580     *state = NULL;
581
582     return;
583 }
584
585 /****************************************************************************/
586
587 /*
588 ------------------------------------------------------------------------------
589  FUNCTION NAME: cod_amr_first
590 ------------------------------------------------------------------------------
591  INPUT AND OUTPUT DEFINITIONS
592
593  Inputs:
594     st = pointer to a structure of type cod_amrState
595     new_speech = pointer to buffer of length L_FRAME that contains
596                  the speech input (Word16)
597
598  Outputs:
599     The structure of type cod_amrState pointed to by st is updated.
600
601  Returns:
602     return_value = 0 (int)
603
604  Global Variables Used:
605     None.
606
607  Local Variables Needed:
608     None.
609
610 ------------------------------------------------------------------------------
611  FUNCTION DESCRIPTION
612
613  This function copes with look-ahead and calls cod_amr.
614  No input argument are passed to this function. However, before
615  calling this function, 40 new speech data should be copied to the
616  vector new_speech[]. This is a global pointer which is declared in
617  this file (it points to the end of speech buffer minus 200).
618
619 ------------------------------------------------------------------------------
620  REQUIREMENTS
621
622  None.
623
624 ------------------------------------------------------------------------------
625  REFERENCES
626
627  cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
628
629 ------------------------------------------------------------------------------
630  PSEUDO-CODE
631
632 int cod_amr_first(cod_amrState *st,     // i/o : State struct
633                   Word16 new_speech[])  // i   : speech input (L_FRAME)
634 {
635    Copy(new_speech,&st->new_speech[-L_NEXT], L_NEXT);
636    //   Copy(new_speech,st->new_speech,L_FRAME);
637
638    return 0;
639 }
640
641 ------------------------------------------------------------------------------
642  CAUTION [optional]
643  [State any special notes, constraints or cautions for users of this function]
644
645 ------------------------------------------------------------------------------
646 */
647
648 Word16 cod_amr_first(cod_amrState *st,     /* i/o : State struct           */
649                      Word16 new_speech[])  /* i   : speech input (L_FRAME) */
650 {
651
652     oscl_memcpy(&st->new_speech[-L_NEXT], new_speech, L_NEXT*sizeof(Word16));
653
654     /*   Copy(new_speech,st->new_speech,L_FRAME); */
655
656     return(0);
657 }
658
659 /****************************************************************************/
660
661 /*
662 ------------------------------------------------------------------------------
663  FUNCTION NAME: cod_amr
664 ------------------------------------------------------------------------------
665  INPUT AND OUTPUT DEFINITIONS
666
667  Inputs:
668     st = pointer to a structure of type cod_amrState
669     mode = AMR mode of type enum Mode
670     new_speech = pointer to buffer of length L_FRAME that contains
671              the speech input of type Word16
672     ana = pointer to the analysis parameters of type Word16
673     usedMode = pointer to the used mode of type enum Mode
674     synth = pointer to a buffer containing the local synthesis speech of
675         type Word16
676
677  Outputs:
678     The structure of type cod_amrState pointed to by st is updated.
679     The analysis parameter buffer pointed to by ana is updated.
680     The value pointed to by usedMode is updated.
681     The local synthesis speech buffer pointed to by synth is updated.
682
683  Returns:
684     return_value = 0 (int)
685
686  Global Variables Used:
687     None.
688
689  Local Variables Needed:
690     None.
691
692 ------------------------------------------------------------------------------
693  FUNCTION DESCRIPTION
694
695  This function is the main encoder routine. It is called every 20 ms speech
696  frame, operating on the newly read 160 speech samples. It performs the
697  principle encoding functions to produce the set of encoded parameters
698  which include the LSP, adaptive codebook, and fixed codebook
699  quantization indices (addresses and gains).
700
701  Before calling this function, 160 new speech data should be copied to the
702  vector new_speech[]. This is a global pointer which is declared in
703  this file (it points to the end of speech buffer minus 160).
704
705  The outputs of the function are:
706      ana[]:     vector of analysis parameters.
707      synth[]:   Local synthesis speech (for debugging purposes)
708
709 ------------------------------------------------------------------------------
710  REQUIREMENTS
711
712  None.
713
714 ------------------------------------------------------------------------------
715  REFERENCES
716
717  cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
718
719 ------------------------------------------------------------------------------
720  PSEUDO-CODE
721
722 int cod_amr(
723     cod_amrState *st,          // i/o : State struct
724     enum Mode mode,            // i   : AMR mode
725     Word16 new_speech[],       // i   : speech input (L_FRAME)
726     Word16 ana[],              // o   : Analysis parameters
727     enum Mode *usedMode,       // o   : used mode
728     Word16 synth[]             // o   : Local synthesis
729 )
730 {
731    // LPC coefficients
732    Word16 A_t[(MP1) * 4];      // A(z) unquantized for the 4 subframes
733    Word16 Aq_t[(MP1) * 4];     // A(z)   quantized for the 4 subframes
734    Word16 *A, *Aq;             // Pointer on A_t and Aq_t
735    Word16 lsp_new[M];
736
737    // Other vectors
738    Word16 xn[L_SUBFR];         // Target vector for pitch search
739    Word16 xn2[L_SUBFR];        // Target vector for codebook search
740    Word16 code[L_SUBFR];       // Fixed codebook excitation
741    Word16 y1[L_SUBFR];         // Filtered adaptive excitation
742    Word16 y2[L_SUBFR];         // Filtered fixed codebook excitation
743    Word16 gCoeff[6];           // Correlations between xn, y1, & y2:
744    Word16 res[L_SUBFR];        // Short term (LPC) prediction residual
745    Word16 res2[L_SUBFR];       // Long term (LTP) prediction residual
746
747    // Vector and scalars needed for the MR475
748    Word16 xn_sf0[L_SUBFR];     // Target vector for pitch search
749    Word16 y2_sf0[L_SUBFR];     // Filtered codebook innovation
750    Word16 code_sf0[L_SUBFR];   // Fixed codebook excitation
751    Word16 h1_sf0[L_SUBFR];     // The impulse response of sf0
752    Word16 mem_syn_save[M];     // Filter memory
753    Word16 mem_w0_save[M];      // Filter memory
754    Word16 mem_err_save[M];     // Filter memory
755    Word16 sharp_save;          // Sharpening
756    Word16 evenSubfr;           // Even subframe indicator
757    Word16 T0_sf0 = 0;          // Integer pitch lag of sf0
758    Word16 T0_frac_sf0 = 0;     // Fractional pitch lag of sf0
759    Word16 i_subfr_sf0 = 0;     // Position in exc[] for sf0
760    Word16 gain_pit_sf0;        // Quantized pitch gain for sf0
761    Word16 gain_code_sf0;       // Quantized codebook gain for sf0
762
763    // Scalars
764    Word16 i_subfr, subfrNr;
765    Word16 T_op[L_FRAME/L_FRAME_BY2];
766    Word16 T0, T0_frac;
767    Word16 gain_pit, gain_code;
768
769    // Flags
770    Word16 lsp_flag = 0;        // indicates resonance in LPC filter
771    Word16 gp_limit;            // pitch gain limit value
772    Word16 vad_flag;            // VAD decision flag
773    Word16 compute_sid_flag;    // SID analysis  flag
774
775    Copy(new_speech, st->new_speech, L_FRAME);
776
777    *usedMode = mode;
778
779    // DTX processing
780    if (st->dtx)
781    {  // no test() call since this if is only in simulation env
782       // Find VAD decision
783
784 #ifdef  VAD2
785       vad_flag = vad2 (st->new_speech,    st->vadSt);
786       vad_flag = vad2 (st->new_speech+80, st->vadSt) || vad_flag;
787 #else
788       vad_flag = vad1(st->vadSt, st->new_speech);
789 #endif
790
791       // NB! usedMode may change here
792       compute_sid_flag = tx_dtx_handler(st->dtx_encSt,
793                                         vad_flag,
794                                         usedMode);
795    }
796    else
797    {
798       compute_sid_flag = 0;
799    }
800
801     *------------------------------------------------------------------------*
802     *  - Perform LPC analysis:                                               *
803     *       * autocorrelation + lag windowing                                *
804     *       * Levinson-durbin algorithm to find a[]                          *
805     *       * convert a[] to lsp[]                                           *
806     *       * quantize and code the LSPs                                     *
807     *       * find the interpolated LSPs and convert to a[] for all          *
808     *         subframes (both quantized and unquantized)                     *
809     *------------------------------------------------------------------------*
810
811    // LP analysis
812    lpc(st->lpcSt, mode, st->p_window, st->p_window_12k2, A_t);
813
814
815    // From A(z) to lsp. LSP quantization and interpolation
816    lsp(st->lspSt, mode, *usedMode, A_t, Aq_t, lsp_new, &ana);
817
818
819    // Buffer lsp's and energy
820    dtx_buffer(st->dtx_encSt,
821           lsp_new,
822           st->new_speech);
823
824    // Check if in DTX mode
825    if (sub(*usedMode, MRDTX) == 0)
826    {
827       dtx_enc(st->dtx_encSt,
828               compute_sid_flag,
829               st->lspSt->qSt,
830               st->gainQuantSt->gc_predSt,
831               &ana);
832
833       Set_zero(st->old_exc,    PIT_MAX + L_INTERPOL);
834       Set_zero(st->mem_w0,     M);
835       Set_zero(st->mem_err,    M);
836       Set_zero(st->zero,       L_SUBFR);
837       Set_zero(st->hvec,       L_SUBFR);    // set to zero "h1[-L_SUBFR..-1]"
838       // Reset lsp states
839       lsp_reset(st->lspSt);
840       Copy(lsp_new, st->lspSt->lsp_old, M);
841       Copy(lsp_new, st->lspSt->lsp_old_q, M);
842
843       // Reset clLtp states
844       cl_ltp_reset(st->clLtpSt);
845       st->sharp = SHARPMIN;
846    }
847    else
848    {
849        // check resonance in the filter
850       lsp_flag = check_lsp(st->tonStabSt, st->lspSt->lsp_old);
851    }
852
853     *----------------------------------------------------------------------*
854     * - Find the weighted input speech w_sp[] for the whole speech frame   *
855     * - Find the open-loop pitch delay for first 2 subframes               *
856     * - Set the range for searching closed-loop pitch in 1st subframe      *
857     * - Find the open-loop pitch delay for last 2 subframes                *
858     *----------------------------------------------------------------------*
859
860 #ifdef VAD2
861    if (st->dtx)
862    {  // no test() call since this if is only in simulation env
863        st->vadSt->L_Rmax = 0;
864        st->vadSt->L_R0 = 0;
865    }
866 #endif
867    for(subfrNr = 0, i_subfr = 0;
868        subfrNr < L_FRAME/L_FRAME_BY2;
869        subfrNr++, i_subfr += L_FRAME_BY2)
870    {
871       // Pre-processing on 80 samples
872       pre_big(mode, gamma1, gamma1_12k2, gamma2, A_t, i_subfr, st->speech,
873               st->mem_w, st->wsp);
874
875       if ((sub(mode, MR475) != 0) && (sub(mode, MR515) != 0))
876       {
877          // Find open loop pitch lag for two subframes
878          ol_ltp(st->pitchOLWghtSt, st->vadSt, mode, &st->wsp[i_subfr],
879                 &T_op[subfrNr], st->old_lags, st->ol_gain_flg, subfrNr,
880                 st->dtx);
881       }
882    }
883
884    if ((sub(mode, MR475) == 0) || (sub(mode, MR515) == 0))
885    {
886       // Find open loop pitch lag for ONE FRAME ONLY
887       // search on 160 samples
888
889       ol_ltp(st->pitchOLWghtSt, st->vadSt, mode, &st->wsp[0], &T_op[0],
890              st->old_lags, st->ol_gain_flg, 1, st->dtx);
891       T_op[1] = T_op[0];
892    }
893
894 #ifdef VAD2
895    if (st->dtx)
896    {  // no test() call since this if is only in simulation env
897       LTP_flag_update(st->vadSt, mode);
898    }
899 #endif
900
901 #ifndef VAD2
902    // run VAD pitch detection
903    if (st->dtx)
904    {  // no test() call since this if is only in simulation env
905       vad_pitch_detection(st->vadSt, T_op);
906    }
907 #endif
908
909    if (sub(*usedMode, MRDTX) == 0)
910    {
911       goto the_end;
912    }
913
914     *------------------------------------------------------------------------*
915     *          Loop for every subframe in the analysis frame                 *
916     *------------------------------------------------------------------------*
917     *  To find the pitch and innovation parameters. The subframe size is     *
918     *  L_SUBFR and the loop is repeated L_FRAME/L_SUBFR times.               *
919     *     - find the weighted LPC coefficients                               *
920     *     - find the LPC residual signal res[]                               *
921     *     - compute the target signal for pitch search                       *
922     *     - compute impulse response of weighted synthesis filter (h1[])     *
923     *     - find the closed-loop pitch parameters                            *
924     *     - encode the pitch dealy                                           *
925     *     - update the impulse response h1[] by including fixed-gain pitch   *
926     *     - find target vector for codebook search                           *
927     *     - codebook search                                                  *
928     *     - encode codebook address                                          *
929     *     - VQ of pitch and codebook gains                                   *
930     *     - find synthesis speech                                            *
931     *     - update states of weighting filter                                *
932     *------------------------------------------------------------------------*
933
934    A = A_t;      // pointer to interpolated LPC parameters
935    Aq = Aq_t;    // pointer to interpolated quantized LPC parameters
936
937    evenSubfr = 0;
938    subfrNr = -1;
939    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
940    {
941       subfrNr = add(subfrNr, 1);
942       evenSubfr = sub(1, evenSubfr);
943
944       // Save states for the MR475 mode
945       if ((evenSubfr != 0) && (sub(*usedMode, MR475) == 0))
946       {
947          Copy(st->mem_syn, mem_syn_save, M);
948          Copy(st->mem_w0, mem_w0_save, M);
949          Copy(st->mem_err, mem_err_save, M);
950          sharp_save = st->sharp;
951       }
952
953        *-----------------------------------------------------------------*
954        * - Preprocessing of subframe                                     *
955        *-----------------------------------------------------------------*
956       if (sub(*usedMode, MR475) != 0)
957       {
958          subframePreProc(*usedMode, gamma1, gamma1_12k2,
959                          gamma2, A, Aq, &st->speech[i_subfr],
960                          st->mem_err, st->mem_w0, st->zero,
961                          st->ai_zero, &st->exc[i_subfr],
962                          st->h1, xn, res, st->error);
963       }
964       else
965       { // MR475
966          subframePreProc(*usedMode, gamma1, gamma1_12k2,
967                          gamma2, A, Aq, &st->speech[i_subfr],
968                          st->mem_err, mem_w0_save, st->zero,
969                          st->ai_zero, &st->exc[i_subfr],
970                          st->h1, xn, res, st->error);
971
972          // save impulse response (modified in cbsearch)
973          if (evenSubfr != 0)
974          {
975              Copy (st->h1, h1_sf0, L_SUBFR);
976          }
977       }
978
979       // copy the LP residual (res2 is modified in the CL LTP search)
980       Copy (res, res2, L_SUBFR);
981
982
983        *-----------------------------------------------------------------*
984        * - Closed-loop LTP search                                        *
985        *-----------------------------------------------------------------*
986       cl_ltp(st->clLtpSt, st->tonStabSt, *usedMode, i_subfr, T_op, st->h1,
987              &st->exc[i_subfr], res2, xn, lsp_flag, xn2, y1,
988              &T0, &T0_frac, &gain_pit, gCoeff, &ana,
989              &gp_limit);
990
991       // update LTP lag history
992       if ((subfrNr == 0) && (st->ol_gain_flg[0] > 0))
993       {
994          st->old_lags[1] = T0;
995       }
996
997       if ((sub(subfrNr, 3) == 0) && (st->ol_gain_flg[1] > 0))
998       {
999          st->old_lags[0] = T0;
1000       }
1001
1002
1003        *-----------------------------------------------------------------*
1004        * - Inovative codebook search (find index and gain)               *
1005        *-----------------------------------------------------------------*
1006       cbsearch(xn2, st->h1, T0, st->sharp, gain_pit, res2,
1007                code, y2, &ana, *usedMode, subfrNr);
1008
1009        *------------------------------------------------------*
1010        * - Quantization of gains.                             *
1011        *------------------------------------------------------*
1012       gainQuant(st->gainQuantSt, *usedMode, res, &st->exc[i_subfr], code,
1013                 xn, xn2,  y1, y2, gCoeff, evenSubfr, gp_limit,
1014                 &gain_pit_sf0, &gain_code_sf0,
1015                 &gain_pit, &gain_code, &ana);
1016
1017       // update gain history
1018       update_gp_clipping(st->tonStabSt, gain_pit);
1019
1020       if (sub(*usedMode, MR475) != 0)
1021       {
1022          // Subframe Post Porcessing
1023          subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
1024                           gain_code, Aq, synth, xn, code, y1, y2, st->mem_syn,
1025                           st->mem_err, st->mem_w0, st->exc, &st->sharp);
1026       }
1027       else
1028       {
1029          if (evenSubfr != 0)
1030          {
1031             i_subfr_sf0 = i_subfr;
1032             Copy(xn, xn_sf0, L_SUBFR);
1033             Copy(y2, y2_sf0, L_SUBFR);
1034             Copy(code, code_sf0, L_SUBFR);
1035             T0_sf0 = T0;
1036             T0_frac_sf0 = T0_frac;
1037
1038             // Subframe Post Porcessing
1039             subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
1040                              gain_code, Aq, synth, xn, code, y1, y2,
1041                              mem_syn_save, st->mem_err, mem_w0_save,
1042                              st->exc, &st->sharp);
1043             st->sharp = sharp_save;
1044          }
1045          else
1046          {
1047             // update both subframes for the MR475
1048
1049             // Restore states for the MR475 mode
1050             Copy(mem_err_save, st->mem_err, M);
1051
1052             // re-build excitation for sf 0
1053             Pred_lt_3or6(&st->exc[i_subfr_sf0], T0_sf0, T0_frac_sf0,
1054                          L_SUBFR, 1);
1055             Convolve(&st->exc[i_subfr_sf0], h1_sf0, y1, L_SUBFR);
1056
1057             Aq -= MP1;
1058             subframePostProc(st->speech, *usedMode, i_subfr_sf0,
1059                              gain_pit_sf0, gain_code_sf0, Aq,
1060                              synth, xn_sf0, code_sf0, y1, y2_sf0,
1061                              st->mem_syn, st->mem_err, st->mem_w0, st->exc,
1062                              &sharp_save); // overwrites sharp_save
1063             Aq += MP1;
1064
1065             // re-run pre-processing to get xn right (needed by postproc)
1066             // (this also reconstructs the unsharpened h1 for sf 1)
1067             subframePreProc(*usedMode, gamma1, gamma1_12k2,
1068                             gamma2, A, Aq, &st->speech[i_subfr],
1069                             st->mem_err, st->mem_w0, st->zero,
1070                             st->ai_zero, &st->exc[i_subfr],
1071                             st->h1, xn, res, st->error);
1072
1073             // re-build excitation sf 1 (changed if lag < L_SUBFR)
1074             Pred_lt_3or6(&st->exc[i_subfr], T0, T0_frac, L_SUBFR, 1);
1075             Convolve(&st->exc[i_subfr], st->h1, y1, L_SUBFR);
1076
1077             subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
1078                              gain_code, Aq, synth, xn, code, y1, y2,
1079                              st->mem_syn, st->mem_err, st->mem_w0,
1080                              st->exc, &st->sharp);
1081          }
1082       }
1083
1084
1085       A += MP1;    // interpolated LPC parameters for next subframe
1086       Aq += MP1;
1087    }
1088
1089    Copy(&st->old_exc[L_FRAME], &st->old_exc[0], PIT_MAX + L_INTERPOL);
1090
1091 the_end:
1092
1093     *--------------------------------------------------*
1094     * Update signal for next frame.                    *
1095     *--------------------------------------------------*
1096    Copy(&st->old_wsp[L_FRAME], &st->old_wsp[0], PIT_MAX);
1097
1098    Copy(&st->old_speech[L_FRAME], &st->old_speech[0], L_TOTAL - L_FRAME);
1099
1100    return 0;
1101 }
1102 ------------------------------------------------------------------------------
1103  CAUTION [optional]
1104  [State any special notes, constraints or cautions for users of this function]
1105
1106 ------------------------------------------------------------------------------
1107 */
1108
1109 Word16 cod_amr(
1110     cod_amrState *st,          /* i/o : State struct                   */
1111     enum Mode mode,            /* i   : AMR mode                       */
1112     Word16 new_speech[],       /* i   : speech input (L_FRAME)         */
1113     Word16 ana[],              /* o   : Analysis parameters            */
1114     enum Mode *usedMode,       /* o   : used mode                      */
1115     Word16 synth[]            /* o   : Local synthesis                */
1116 )
1117 {
1118     /* LPC coefficients */
1119     Word16 A_t[(MP1) * 4];      /* A(z) unquantized for the 4 subframes */
1120     Word16 Aq_t[(MP1) * 4];     /* A(z)   quantized for the 4 subframes */
1121     Word16 *A, *Aq;             /* Pointer on A_t and Aq_t              */
1122     Word16 lsp_new[M];
1123
1124     /* Other vectors */
1125     Word16 xn[L_SUBFR];         /* Target vector for pitch search       */
1126     Word16 xn2[L_SUBFR];        /* Target vector for codebook search    */
1127     Word16 code[L_SUBFR];       /* Fixed codebook excitation            */
1128     Word16 y1[L_SUBFR];         /* Filtered adaptive excitation         */
1129     Word16 y2[L_SUBFR];         /* Filtered fixed codebook excitation   */
1130     Word16 gCoeff[6];           /* Correlations between xn, y1, & y2:   */
1131     Word16 res[L_SUBFR];        /* Short term (LPC) prediction residual */
1132     Word16 res2[L_SUBFR];       /* Long term (LTP) prediction residual  */
1133
1134     /* Vector and scalars needed for the MR475 */
1135     Word16 xn_sf0[L_SUBFR];     /* Target vector for pitch search       */
1136     Word16 y2_sf0[L_SUBFR];     /* Filtered codebook innovation         */
1137     Word16 code_sf0[L_SUBFR];   /* Fixed codebook excitation            */
1138     Word16 h1_sf0[L_SUBFR];     /* The impulse response of sf0          */
1139     Word16 mem_syn_save[M];     /* Filter memory                        */
1140     Word16 mem_w0_save[M];      /* Filter memory                        */
1141     Word16 mem_err_save[M];     /* Filter memory                        */
1142     Word16 sharp_save;          /* Sharpening                           */
1143     Word16 evenSubfr;           /* Even subframe indicator              */
1144     Word16 T0_sf0 = 0;          /* Integer pitch lag of sf0             */
1145     Word16 T0_frac_sf0 = 0;     /* Fractional pitch lag of sf0          */
1146     Word16 i_subfr_sf0 = 0;     /* Position in exc[] for sf0            */
1147     Word16 gain_pit_sf0;        /* Quantized pitch gain for sf0         */
1148     Word16 gain_code_sf0;       /* Quantized codebook gain for sf0      */
1149
1150     /* Scalars */
1151     Word16 i_subfr, subfrNr;
1152     Word16 T_op[L_FRAME/L_FRAME_BY2];
1153     Word16 T0, T0_frac;
1154     Word16 gain_pit, gain_code;
1155
1156     /* Flags */
1157     Word16 lsp_flag = 0;        /* indicates resonance in LPC filter    */
1158     Word16 gp_limit;            /* pitch gain limit value               */
1159     Word16 vad_flag;            /* VAD decision flag                    */
1160     Word16 compute_sid_flag;    /* SID analysis  flag                   */
1161     Flag   *pOverflow = &(st->overflow);     /* Overflow flag            */
1162
1163
1164     oscl_memcpy(st->new_speech, new_speech, L_FRAME*sizeof(Word16));
1165
1166     *usedMode = mode;
1167
1168     /* DTX processing */
1169     if (st->dtx)
1170     {
1171         /* Find VAD decision */
1172 #ifdef  VAD2
1173         vad_flag = vad2(st->new_speech,    st->vadSt, pOverflow);
1174         vad_flag = vad2(st->new_speech + 80, st->vadSt, pOverflow) || vad_flag;
1175 #else
1176         vad_flag = vad1(st->vadSt, st->new_speech, pOverflow);
1177 #endif
1178
1179         /* NB! usedMode may change here */
1180         compute_sid_flag = tx_dtx_handler(st->dtx_encSt,
1181                                           vad_flag,
1182                                           usedMode, pOverflow);
1183     }
1184     else
1185     {
1186         compute_sid_flag = 0;
1187     }
1188
1189     /*------------------------------------------------------------------------*
1190     *  - Perform LPC analysis:                                               *
1191     *       * autocorrelation + lag windowing                                *
1192     *       * Levinson-durbin algorithm to find a[]                          *
1193     *       * convert a[] to lsp[]                                           *
1194     *       * quantize and code the LSPs                                     *
1195     *       * find the interpolated LSPs and convert to a[] for all          *
1196     *         subframes (both quantized and unquantized)                     *
1197     *------------------------------------------------------------------------*/
1198
1199     /* LP analysis */
1200     lpc(st->lpcSt, mode, st->p_window, st->p_window_12k2, A_t, &(st->common_amr_tbls), pOverflow);
1201
1202     /* From A(z) to lsp. LSP quantization and interpolation */
1203     lsp(st->lspSt, mode, *usedMode, A_t, Aq_t, lsp_new, &ana, pOverflow);
1204
1205     /* Buffer lsp's and energy */
1206     dtx_buffer(st->dtx_encSt,
1207                lsp_new,
1208                st->new_speech, pOverflow);
1209
1210     /* Check if in DTX mode */
1211
1212     if (*usedMode == MRDTX)
1213     {
1214         dtx_enc(st->dtx_encSt,
1215                 compute_sid_flag,
1216                 st->lspSt->qSt,
1217                 &(st->gainQuantSt->gc_predSt),
1218                 &ana, pOverflow);
1219
1220         oscl_memset(st->old_exc, 0,   sizeof(Word16)*(PIT_MAX + L_INTERPOL));
1221         oscl_memset(st->mem_w0,  0,   sizeof(Word16)*M);
1222         oscl_memset(st->mem_err, 0,   sizeof(Word16)*M);
1223         oscl_memset(st->zero,    0,   sizeof(Word16)*L_SUBFR);
1224         oscl_memset(st->hvec,    0,   sizeof(Word16)*L_SUBFR);    /* set to zero "h1[-L_SUBFR..-1]" */
1225         /* Reset lsp states */
1226         lsp_reset(st->lspSt);
1227
1228         oscl_memcpy(st->lspSt->lsp_old,   lsp_new, M*sizeof(Word16));
1229         oscl_memcpy(st->lspSt->lsp_old_q, lsp_new, M*sizeof(Word16));
1230
1231         /* Reset clLtp states */
1232         cl_ltp_reset(st->clLtpSt);
1233         st->sharp = SHARPMIN;
1234     }
1235     else
1236     {
1237         /* check resonance in the filter */
1238         lsp_flag = check_lsp(st->tonStabSt, st->lspSt->lsp_old, pOverflow);
1239     }
1240
1241     /*----------------------------------------------------------------------*
1242     * - Find the weighted input speech w_sp[] for the whole speech frame   *
1243     * - Find the open-loop pitch delay for first 2 subframes               *
1244     * - Set the range for searching closed-loop pitch in 1st subframe      *
1245     * - Find the open-loop pitch delay for last 2 subframes                *
1246     *----------------------------------------------------------------------*/
1247
1248 #ifdef VAD2
1249     if (st->dtx)
1250     {
1251         st->vadSt->L_Rmax = 0;
1252         st->vadSt->L_R0 = 0;
1253     }
1254 #endif
1255
1256     for (subfrNr = 0, i_subfr = 0;
1257             subfrNr < L_FRAME / L_FRAME_BY2;
1258             subfrNr++, i_subfr += L_FRAME_BY2)
1259     {
1260         /* Pre-processing on 80 samples */
1261         pre_big(mode, gamma1, gamma1_12k2, gamma2, A_t, i_subfr, st->speech,
1262                 st->mem_w, st->wsp, pOverflow);
1263
1264
1265         if ((mode != MR475) && (mode != MR515))
1266         {
1267             /* Find open loop pitch lag for two subframes */
1268             ol_ltp(st->pitchOLWghtSt, st->vadSt, mode, &st->wsp[i_subfr],
1269                    &T_op[subfrNr], st->old_lags, st->ol_gain_flg, subfrNr,
1270                    st->dtx, pOverflow);
1271         }
1272     }
1273
1274     if ((mode == MR475) || (mode == MR515))
1275     {
1276         /* Find open loop pitch lag for ONE FRAME ONLY */
1277         /* search on 160 samples */
1278
1279         ol_ltp(st->pitchOLWghtSt, st->vadSt, mode, &st->wsp[0], &T_op[0],
1280                st->old_lags, st->ol_gain_flg, 1, st->dtx, pOverflow);
1281         T_op[1] = T_op[0];
1282     }
1283
1284 #ifdef VAD2
1285     if (st->dtx)
1286     {
1287         LTP_flag_update(st->vadSt, (Word16) mode, pOverflow);
1288     }
1289 #endif
1290
1291 #ifndef VAD2
1292     /* run VAD pitch detection */
1293     if (st->dtx)
1294     {
1295         vad_pitch_detection(st->vadSt, T_op, pOverflow);
1296     }
1297 #endif
1298
1299     if (*usedMode == MRDTX)
1300     {
1301         goto the_end;
1302     }
1303
1304     /*------------------------------------------------------------------------*
1305     *          Loop for every subframe in the analysis frame                 *
1306     *------------------------------------------------------------------------*
1307     *  To find the pitch and innovation parameters. The subframe size is     *
1308     *  L_SUBFR and the loop is repeated L_FRAME/L_SUBFR times.               *
1309     *     - find the weighted LPC coefficients                               *
1310     *     - find the LPC residual signal res[]                               *
1311     *     - compute the target signal for pitch search                       *
1312     *     - compute impulse response of weighted synthesis filter (h1[])     *
1313     *     - find the closed-loop pitch parameters                            *
1314     *     - encode the pitch dealy                                           *
1315     *     - update the impulse response h1[] by including fixed-gain pitch   *
1316     *     - find target vector for codebook search                           *
1317     *     - codebook search                                                  *
1318     *     - encode codebook address                                          *
1319     *     - VQ of pitch and codebook gains                                   *
1320     *     - find synthesis speech                                            *
1321     *     - update states of weighting filter                                *
1322     *------------------------------------------------------------------------*/
1323
1324     A = A_t;      /* pointer to interpolated LPC parameters */
1325     Aq = Aq_t;    /* pointer to interpolated quantized LPC parameters */
1326
1327     evenSubfr = 0;
1328     subfrNr = -1;
1329     for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
1330     {
1331         subfrNr++;
1332         evenSubfr = 1 - evenSubfr;
1333
1334         /* Save states for the MR475 mode */
1335
1336         if ((evenSubfr != 0) && (*usedMode == MR475))
1337         {
1338             oscl_memcpy(mem_syn_save, st->mem_syn, M*sizeof(Word16));
1339             oscl_memcpy(mem_w0_save, st->mem_w0, M*sizeof(Word16));
1340             oscl_memcpy(mem_err_save, st->mem_err, M*sizeof(Word16));
1341
1342             sharp_save = st->sharp;
1343         }
1344
1345         /*-----------------------------------------------------------------*
1346         * - Preprocessing of subframe                                     *
1347         *-----------------------------------------------------------------*/
1348
1349         if (*usedMode != MR475)
1350         {
1351             subframePreProc(*usedMode, gamma1, gamma1_12k2,
1352                             gamma2, A, Aq, &st->speech[i_subfr],
1353                             st->mem_err, st->mem_w0, st->zero,
1354                             st->ai_zero, &st->exc[i_subfr],
1355                             st->h1, xn, res, st->error);
1356         }
1357         else
1358         { /* MR475 */
1359             subframePreProc(*usedMode, gamma1, gamma1_12k2,
1360                             gamma2, A, Aq, &st->speech[i_subfr],
1361                             st->mem_err, mem_w0_save, st->zero,
1362                             st->ai_zero, &st->exc[i_subfr],
1363                             st->h1, xn, res, st->error);
1364
1365             /* save impulse response (modified in cbsearch) */
1366
1367             if (evenSubfr != 0)
1368             {
1369                 oscl_memcpy(h1_sf0, st->h1, L_SUBFR*sizeof(Word16));
1370
1371             }
1372         }
1373
1374         /* copy the LP residual (res2 is modified in the CL LTP search)    */
1375         oscl_memcpy(res2, res, L_SUBFR*sizeof(Word16));
1376
1377         /*-----------------------------------------------------------------*
1378         * - Closed-loop LTP search                                        *
1379         *-----------------------------------------------------------------*/
1380         cl_ltp(st->clLtpSt, st->tonStabSt, *usedMode, i_subfr, T_op, st->h1,
1381                &st->exc[i_subfr], res2, xn, lsp_flag, xn2, y1,
1382                &T0, &T0_frac, &gain_pit, gCoeff, &ana,
1383                &gp_limit, st->common_amr_tbls.qua_gain_pitch_ptr, pOverflow);
1384
1385         /* update LTP lag history */
1386
1387         if ((subfrNr == 0) && (st->ol_gain_flg[0] > 0))
1388         {
1389             st->old_lags[1] = T0;
1390         }
1391
1392
1393         if ((subfrNr == 3) && (st->ol_gain_flg[1] > 0))
1394         {
1395             st->old_lags[0] = T0;
1396         }
1397
1398         /*-----------------------------------------------------------------*
1399         * - Inovative codebook search (find index and gain)               *
1400         *-----------------------------------------------------------------*/
1401         cbsearch(xn2, st->h1, T0, st->sharp, gain_pit, res2,
1402                  code, y2, &ana, *usedMode, subfrNr, &(st->common_amr_tbls), pOverflow);
1403
1404         /*------------------------------------------------------*
1405         * - Quantization of gains.                             *
1406         *------------------------------------------------------*/
1407         gainQuant(st->gainQuantSt, *usedMode, res, &st->exc[i_subfr], code,
1408                   xn, xn2,  y1, y2, gCoeff, evenSubfr, gp_limit,
1409                   &gain_pit_sf0, &gain_code_sf0,
1410                   &gain_pit, &gain_code, &ana, &(st->common_amr_tbls), pOverflow);
1411
1412         /* update gain history */
1413         update_gp_clipping(st->tonStabSt, gain_pit, pOverflow);
1414
1415
1416         if (*usedMode != MR475)
1417         {
1418             /* Subframe Post Porcessing */
1419             subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
1420                              gain_code, Aq, synth, xn, code, y1, y2, st->mem_syn,
1421                              st->mem_err, st->mem_w0, st->exc, &st->sharp, pOverflow);
1422         }
1423         else
1424         {
1425
1426             if (evenSubfr != 0)
1427             {
1428                 i_subfr_sf0 = i_subfr;
1429
1430                 oscl_memcpy(xn_sf0, xn, L_SUBFR*sizeof(Word16));
1431                 oscl_memcpy(y2_sf0, y2, L_SUBFR*sizeof(Word16));
1432                 oscl_memcpy(code_sf0, code, L_SUBFR*sizeof(Word16));
1433
1434                 T0_sf0 = T0;
1435                 T0_frac_sf0 = T0_frac;
1436
1437                 /* Subframe Post Porcessing */
1438                 subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
1439                                  gain_code, Aq, synth, xn, code, y1, y2,
1440                                  mem_syn_save, st->mem_err, mem_w0_save,
1441                                  st->exc, &st->sharp, pOverflow);
1442                 st->sharp = sharp_save;
1443             }
1444             else
1445             {
1446                 /* update both subframes for the MR475 */
1447
1448                 /* Restore states for the MR475 mode */
1449                 oscl_memcpy(st->mem_err, mem_err_save, M*sizeof(Word16));
1450
1451
1452                 /* re-build excitation for sf 0 */
1453                 Pred_lt_3or6(&st->exc[i_subfr_sf0], T0_sf0, T0_frac_sf0,
1454                              L_SUBFR, 1, pOverflow);
1455                 Convolve(&st->exc[i_subfr_sf0], h1_sf0, y1, L_SUBFR);
1456
1457                 Aq -= MP1;
1458                 subframePostProc(st->speech, *usedMode, i_subfr_sf0,
1459                                  gain_pit_sf0, gain_code_sf0, Aq,
1460                                  synth, xn_sf0, code_sf0, y1, y2_sf0,
1461                                  st->mem_syn, st->mem_err, st->mem_w0, st->exc,
1462                                  &sharp_save, pOverflow); /* overwrites sharp_save */
1463                 Aq += MP1;
1464
1465                 /* re-run pre-processing to get xn right (needed by postproc) */
1466                 /* (this also reconstructs the unsharpened h1 for sf 1)       */
1467                 subframePreProc(*usedMode, gamma1, gamma1_12k2,
1468                                 gamma2, A, Aq, &st->speech[i_subfr],
1469                                 st->mem_err, st->mem_w0, st->zero,
1470                                 st->ai_zero, &st->exc[i_subfr],
1471                                 st->h1, xn, res, st->error);
1472
1473                 /* re-build excitation sf 1 (changed if lag < L_SUBFR) */
1474                 Pred_lt_3or6(&st->exc[i_subfr], T0, T0_frac, L_SUBFR, 1, pOverflow);
1475                 Convolve(&st->exc[i_subfr], st->h1, y1, L_SUBFR);
1476
1477                 subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
1478                                  gain_code, Aq, synth, xn, code, y1, y2,
1479                                  st->mem_syn, st->mem_err, st->mem_w0,
1480                                  st->exc, &st->sharp, pOverflow);
1481             }
1482         }
1483
1484         A += MP1;    /* interpolated LPC parameters for next subframe */
1485         Aq += MP1;
1486     }
1487
1488     oscl_memcpy(&st->old_exc[0], &st->old_exc[L_FRAME], (PIT_MAX + L_INTERPOL)*sizeof(Word16));
1489
1490 the_end:
1491
1492     /*--------------------------------------------------*
1493     * Update signal for next frame.                    *
1494     *--------------------------------------------------*/
1495
1496     oscl_memcpy(&st->old_wsp[0], &st->old_wsp[L_FRAME], PIT_MAX*sizeof(Word16));
1497     oscl_memcpy(&st->old_speech[0], &st->old_speech[L_FRAME], (L_TOTAL - L_FRAME)*sizeof(Word16));
1498
1499     return(0);
1500 }
1501
1502