Home | History | Annotate | Download | only in src
      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  Pathname: ./audio/gsm-amr/c/src/dec_amr.c
     33  Funtions: Decoder_amr_init
     34            Decoder_amr_reset
     35            Decoder_amr
     36 
     37 ------------------------------------------------------------------------------
     38  MODULE DESCRIPTION
     39 
     40  This file contains the function used to decode one speech frame using a given
     41  codec mode. The functions used to initialize, reset, and exit are also
     42  included in this file.
     43 
     44 ------------------------------------------------------------------------------
     45 */
     46 
     47 /*----------------------------------------------------------------------------
     48 ; INCLUDES
     49 ----------------------------------------------------------------------------*/
     50 #include <string.h>
     51 
     52 #include "dec_amr.h"
     53 #include "typedef.h"
     54 #include "cnst.h"
     55 #include "copy.h"
     56 #include "set_zero.h"
     57 #include "syn_filt.h"
     58 #include "d_plsf.h"
     59 #include "agc.h"
     60 #include "int_lpc.h"
     61 #include "dec_gain.h"
     62 #include "dec_lag3.h"
     63 #include "dec_lag6.h"
     64 #include "d2_9pf.h"
     65 #include "d2_11pf.h"
     66 #include "d3_14pf.h"
     67 #include "d4_17pf.h"
     68 #include "d8_31pf.h"
     69 #include "d1035pf.h"
     70 #include "pred_lt.h"
     71 #include "d_gain_p.h"
     72 #include "d_gain_c.h"
     73 #include "dec_gain.h"
     74 #include "ec_gains.h"
     75 #include "ph_disp.h"
     76 #include "c_g_aver.h"
     77 #include "int_lsf.h"
     78 #include "lsp_lsf.h"
     79 #include "lsp_avg.h"
     80 #include "bgnscd.h"
     81 #include "ex_ctrl.h"
     82 #include "sqrt_l.h"
     83 #include "frame.h"
     84 #include "bitno_tab.h"
     85 #include "b_cn_cod.h"
     86 #include "basic_op.h"
     87 
     88 /*----------------------------------------------------------------------------
     89 ; MACROS
     90 ; Define module specific macros here
     91 ----------------------------------------------------------------------------*/
     92 
     93 /*----------------------------------------------------------------------------
     94 ; DEFINES
     95 ; Include all pre-processor statements here. Include conditional
     96 ; compile variables also.
     97 ----------------------------------------------------------------------------*/
     98 
     99 /*----------------------------------------------------------------------------
    100 ; LOCAL FUNCTION DEFINITIONS
    101 ; Function Prototype declaration
    102 ----------------------------------------------------------------------------*/
    103 
    104 /*----------------------------------------------------------------------------
    105 ; LOCAL VARIABLE DEFINITIONS
    106 ; Variable declaration - defined here and used outside this module
    107 ----------------------------------------------------------------------------*/
    108 
    109 
    110 /*
    111 ------------------------------------------------------------------------------
    112  FUNCTION NAME: Decoder_amr_init
    113 ------------------------------------------------------------------------------
    114  INPUT AND OUTPUT DEFINITIONS
    115 
    116  Inputs:
    117     state = pointer to a pointer to structures of type Decoder_amrState
    118 
    119  Outputs:
    120     structure pointed to by the pointer which is pointed to by state is
    121       initialized to each field's initial values
    122 
    123     state pointer points to the address of the memory allocated by
    124       Decoder_amr_init function
    125 
    126  Returns:
    127     return_value = 0, if the initialization was successful; -1, otherwise (int)
    128 
    129  Global Variables Used:
    130     None
    131 
    132  Local Variables Needed:
    133     None
    134 
    135 ------------------------------------------------------------------------------
    136  FUNCTION DESCRIPTION
    137 
    138  This function allocates and initializes state memory used by the Decoder_amr
    139  function. It stores the pointer to the filter status structure in state. This
    140  pointer has to be passed to Decoder_amr in each call. The function returns
    141  0, if initialization was successful and -1, otherwise.
    142 
    143 ------------------------------------------------------------------------------
    144  REQUIREMENTS
    145 
    146  None
    147 
    148 ------------------------------------------------------------------------------
    149  REFERENCES
    150 
    151  dec_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
    152 
    153 ------------------------------------------------------------------------------
    154  PSEUDO-CODE
    155 
    156 int Decoder_amr_init (Decoder_amrState **state)
    157 {
    158   Decoder_amrState* s;
    159   Word16 i;
    160 
    161   if (state == (Decoder_amrState **) NULL){
    162       fprintf(stderr, "Decoder_amr_init: invalid parameter\n");
    163       return -1;
    164   }
    165   *state = NULL;
    166 
    167   // allocate memory
    168   if ((s= (Decoder_amrState *) malloc(sizeof(Decoder_amrState))) == NULL){
    169       fprintf(stderr, "Decoder_amr_init: can not malloc state structure\n");
    170       return -1;
    171   }
    172 
    173   s->T0_lagBuff = 40;
    174   s->inBackgroundNoise = 0;
    175   s->voicedHangover = 0;
    176   for (i = 0; i < 9; i++)
    177      s->ltpGainHistory[i] = 0;
    178 
    179   s->lsfState = NULL;
    180   s->ec_gain_p_st = NULL;
    181   s->ec_gain_c_st = NULL;
    182   s->pred_state = NULL;
    183   s->ph_disp_st = NULL;
    184   s->dtxDecoderState = NULL;
    185 
    186   if (D_plsf_init(&s->lsfState) ||
    187       ec_gain_pitch_init(&s->ec_gain_p_st) ||
    188       ec_gain_code_init(&s->ec_gain_c_st) ||
    189       gc_pred_init(&s->pred_state) ||
    190       Cb_gain_average_init(&s->Cb_gain_averState) ||
    191       lsp_avg_init(&s->lsp_avg_st) ||
    192       Bgn_scd_init(&s->background_state) ||
    193       ph_disp_init(&s->ph_disp_st) ||
    194       dtx_dec_init(&s->dtxDecoderState)) {
    195       Decoder_amr_exit(&s);
    196       return -1;
    197   }
    198 
    199   Decoder_amr_reset(s, (enum Mode)0);
    200   *state = s;
    201 
    202   return 0;
    203 }
    204 
    205 ------------------------------------------------------------------------------
    206  RESOURCES USED [optional]
    207 
    208  When the code is written for a specific target processor the
    209  the resources used should be documented below.
    210 
    211  HEAP MEMORY USED: x bytes
    212 
    213  STACK MEMORY USED: x bytes
    214 
    215  CLOCK CYCLES: (cycle count equation for this function) + (variable
    216                 used to represent cycle count for each subroutine
    217                 called)
    218      where: (cycle count variable) = cycle count for [subroutine
    219                                      name]
    220 
    221 ------------------------------------------------------------------------------
    222  CAUTION [optional]
    223  [State any special notes, constraints or cautions for users of this function]
    224 
    225 ------------------------------------------------------------------------------
    226 */
    227 
    228 Word16 Decoder_amr_init(Decoder_amrState *s)
    229 {
    230     Word16 i;
    231 
    232     if (s == (Decoder_amrState *) NULL)
    233     {
    234         /* fprint(stderr, "Decoder_amr_init: invalid parameter\n");  */
    235         return(-1);
    236     }
    237 
    238     s->T0_lagBuff = 40;
    239     s->inBackgroundNoise = 0;
    240     s->voicedHangover = 0;
    241 
    242     /* Initialize overflow Flag */
    243 
    244     s->overflow = 0;
    245 
    246     for (i = 0; i < LTP_GAIN_HISTORY_LEN; i++)
    247     {
    248         s->ltpGainHistory[i] = 0;
    249     }
    250 
    251     D_plsf_reset(&s->lsfState);
    252     ec_gain_pitch_reset(&s->ec_gain_p_st);
    253     ec_gain_code_reset(&s->ec_gain_c_st);
    254     Cb_gain_average_reset(&s->Cb_gain_averState);
    255     lsp_avg_reset(&s->lsp_avg_st);
    256     Bgn_scd_reset(&s->background_state);
    257     ph_disp_reset(&s->ph_disp_st);
    258     dtx_dec_reset(&s->dtxDecoderState);
    259     gc_pred_reset(&s->pred_state);
    260 
    261     Decoder_amr_reset(s, MR475);
    262 
    263     return(0);
    264 }
    265 
    266 /****************************************************************************/
    267 
    268 /*
    269 ------------------------------------------------------------------------------
    270  FUNCTION NAME: Decoder_amr_reset
    271 ------------------------------------------------------------------------------
    272  INPUT AND OUTPUT DEFINITIONS
    273 
    274  Inputs:
    275     state = pointer to a structure of type Decoder_amrState
    276     mode = codec mode (enum Mode)
    277 
    278  Outputs:
    279     structure pointed to by state is initialized to its reset value
    280 
    281  Returns:
    282     return_value = 0, if reset was successful; -1, otherwise (int)
    283 
    284  Global Variables Used:
    285     None
    286 
    287  Local Variables Needed:
    288     None
    289 
    290 ------------------------------------------------------------------------------
    291  FUNCTION DESCRIPTION
    292 
    293  This function resets the state memory used by the Decoder_amr function. It
    294  returns a 0, if reset was successful and -1, otherwise.
    295 
    296 ------------------------------------------------------------------------------
    297  REQUIREMENTS
    298 
    299  None
    300 
    301 ------------------------------------------------------------------------------
    302  REFERENCES
    303 
    304  dec_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
    305 
    306 ------------------------------------------------------------------------------
    307  PSEUDO-CODE
    308 
    309 int Decoder_amr_reset (Decoder_amrState *state, enum Mode mode)
    310 {
    311   Word16 i;
    312 
    313   if (state == (Decoder_amrState *) NULL){
    314       fprintf(stderr, "Decoder_amr_reset: invalid parameter\n");
    315       return -1;
    316   }
    317 
    318   // Initialize static pointer
    319   state->exc = state->old_exc + PIT_MAX + L_INTERPOL;
    320 
    321   // Static vectors to zero
    322   Set_zero (state->old_exc, PIT_MAX + L_INTERPOL);
    323 
    324   if (mode != MRDTX)
    325      Set_zero (state->mem_syn, M);
    326 
    327   // initialize pitch sharpening
    328   state->sharp = SHARPMIN;
    329   state->old_T0 = 40;
    330 
    331   // Initialize state->lsp_old []
    332 
    333   if (mode != MRDTX) {
    334       Copy(lsp_init_data, &state->lsp_old[0], M);
    335   }
    336 
    337   // Initialize memories of bad frame handling
    338   state->prev_bf = 0;
    339   state->prev_pdf = 0;
    340   state->state = 0;
    341 
    342   state->T0_lagBuff = 40;
    343   state->inBackgroundNoise = 0;
    344   state->voicedHangover = 0;
    345   if (mode != MRDTX) {
    346       for (i=0;i<9;i++)
    347           state->excEnergyHist[i] = 0;
    348   }
    349 
    350   for (i = 0; i < 9; i++)
    351      state->ltpGainHistory[i] = 0;
    352 
    353   Cb_gain_average_reset(state->Cb_gain_averState);
    354   if (mode != MRDTX)
    355      lsp_avg_reset(state->lsp_avg_st);
    356   D_plsf_reset(state->lsfState);
    357   ec_gain_pitch_reset(state->ec_gain_p_st);
    358   ec_gain_code_reset(state->ec_gain_c_st);
    359 
    360   if (mode != MRDTX)
    361      gc_pred_reset(state->pred_state);
    362 
    363   Bgn_scd_reset(state->background_state);
    364   state->nodataSeed = 21845;
    365   ph_disp_reset(state->ph_disp_st);
    366   if (mode != MRDTX)
    367      dtx_dec_reset(state->dtxDecoderState);
    368 
    369   return 0;
    370 }
    371 
    372 ------------------------------------------------------------------------------
    373  RESOURCES USED [optional]
    374 
    375  When the code is written for a specific target processor the
    376  the resources used should be documented below.
    377 
    378  HEAP MEMORY USED: x bytes
    379 
    380  STACK MEMORY USED: x bytes
    381 
    382  CLOCK CYCLES: (cycle count equation for this function) + (variable
    383                 used to represent cycle count for each subroutine
    384                 called)
    385      where: (cycle count variable) = cycle count for [subroutine
    386                                      name]
    387 
    388 ------------------------------------------------------------------------------
    389  CAUTION [optional]
    390  [State any special notes, constraints or cautions for users of this function]
    391 
    392 ------------------------------------------------------------------------------
    393 */
    394 
    395 Word16 Decoder_amr_reset(Decoder_amrState *state, enum Mode mode)
    396 {
    397     Word16 i;
    398 
    399     if (state == (Decoder_amrState *) NULL)
    400     {
    401         /* fprint(stderr, "Decoder_amr_reset: invalid parameter\n");  */
    402         return(-1);
    403     }
    404 
    405     /* Initialize static pointer */
    406     state->exc = state->old_exc + PIT_MAX + L_INTERPOL;
    407 
    408     /* Static vectors to zero */
    409     memset(state->old_exc, 0, sizeof(Word16)*(PIT_MAX + L_INTERPOL));
    410 
    411     if (mode != MRDTX)
    412     {
    413         memset(state->mem_syn, 0, sizeof(Word16)*M);
    414     }
    415     /* initialize pitch sharpening */
    416     state->sharp = SHARPMIN;
    417     state->old_T0 = 40;
    418 
    419     /* Initialize overflow Flag */
    420 
    421     state->overflow = 0;
    422 
    423     /* Initialize state->lsp_old [] */
    424 
    425     if (mode != MRDTX)
    426     {
    427         state->lsp_old[0] = 30000;
    428         state->lsp_old[1] = 26000;
    429         state->lsp_old[2] = 21000;
    430         state->lsp_old[3] = 15000;
    431         state->lsp_old[4] = 8000;
    432         state->lsp_old[5] = 0;
    433         state->lsp_old[6] = -8000;
    434         state->lsp_old[7] = -15000;
    435         state->lsp_old[8] = -21000;
    436         state->lsp_old[9] = -26000;
    437     }
    438 
    439     /* Initialize memories of bad frame handling */
    440     state->prev_bf = 0;
    441     state->prev_pdf = 0;
    442     state->state = 0;
    443 
    444     state->T0_lagBuff = 40;
    445     state->inBackgroundNoise = 0;
    446     state->voicedHangover = 0;
    447     if (mode != MRDTX)
    448     {
    449         for (i = 0; i < EXC_ENERGY_HIST_LEN; i++)
    450         {
    451             state->excEnergyHist[i] = 0;
    452         }
    453     }
    454 
    455     for (i = 0; i < LTP_GAIN_HISTORY_LEN; i++)
    456     {
    457         state->ltpGainHistory[i] = 0;
    458     }
    459 
    460     Cb_gain_average_reset(&(state->Cb_gain_averState));
    461     if (mode != MRDTX)
    462     {
    463         lsp_avg_reset(&(state->lsp_avg_st));
    464     }
    465     D_plsf_reset(&(state->lsfState));
    466     ec_gain_pitch_reset(&(state->ec_gain_p_st));
    467     ec_gain_code_reset(&(state->ec_gain_c_st));
    468 
    469     if (mode != MRDTX)
    470     {
    471         gc_pred_reset(&(state->pred_state));
    472     }
    473 
    474     Bgn_scd_reset(&(state->background_state));
    475     state->nodataSeed = 21845;
    476     ph_disp_reset(&(state->ph_disp_st));
    477     if (mode != MRDTX)
    478     {
    479         dtx_dec_reset(&(state->dtxDecoderState));
    480     }
    481 
    482     return(0);
    483 }
    484 
    485 /****************************************************************************/
    486 
    487 /*
    488 ------------------------------------------------------------------------------
    489  FUNCTION NAME: Decoder_amr
    490 ------------------------------------------------------------------------------
    491  INPUT AND OUTPUT DEFINITIONS
    492 
    493  Inputs:
    494     st = pointer to a structure of type Decoder_amrState
    495     mode = codec mode (enum Mode)
    496     parm = buffer of synthesis parameters (Word16)
    497     frame_type = received frame type (enum RXFrameType)
    498     synth = buffer containing synthetic speech (Word16)
    499     A_t = buffer containing decoded LP filter in 4 subframes (Word16)
    500 
    501  Outputs:
    502     structure pointed to by st contains the newly calculated decoder
    503       parameters
    504     synth buffer contains the decoded speech samples
    505     A_t buffer contains the decoded LP filter parameters
    506 
    507  Returns:
    508     return_value = 0 (int)
    509 
    510  Global Variables Used:
    511     None
    512 
    513  Local Variables Needed:
    514     None
    515 
    516 ------------------------------------------------------------------------------
    517  FUNCTION DESCRIPTION
    518 
    519  This function performs the decoding of one speech frame for a given codec
    520  mode.
    521 
    522 ------------------------------------------------------------------------------
    523  REQUIREMENTS
    524 
    525  None
    526 
    527 ------------------------------------------------------------------------------
    528  REFERENCES
    529 
    530  dec_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
    531 
    532 ------------------------------------------------------------------------------
    533  PSEUDO-CODE
    534 
    535 int Decoder_amr (
    536     Decoder_amrState *st,      // i/o : State variables
    537     enum Mode mode,            // i   : AMR mode
    538     Word16 parm[],             // i   : vector of synthesis parameters
    539                                         (PRM_SIZE)
    540     enum RXFrameType frame_type, // i   : received frame type
    541     Word16 synth[],            // o   : synthesis speech (L_FRAME)
    542     Word16 A_t[]               // o   : decoded LP filter in 4 subframes
    543                                         (AZ_SIZE)
    544 )
    545 {
    546     // LPC coefficients
    547 
    548     Word16 *Az;                // Pointer on A_t
    549 
    550     // LSPs
    551 
    552     Word16 lsp_new[M];
    553     Word16 lsp_mid[M];
    554 
    555     // LSFs
    556 
    557     Word16 prev_lsf[M];
    558     Word16 lsf_i[M];
    559 
    560     // Algebraic codevector
    561 
    562     Word16 code[L_SUBFR];
    563 
    564     // excitation
    565 
    566     Word16 excp[L_SUBFR];
    567     Word16 exc_enhanced[L_SUBFR];
    568 
    569     // Scalars
    570 
    571     Word16 i, i_subfr;
    572     Word16 T0, T0_frac, index, index_mr475 = 0;
    573     Word16 gain_pit, gain_code, gain_code_mix, pit_sharp, pit_flag, pitch_fac;
    574     Word16 t0_min, t0_max;
    575     Word16 delta_frc_low, delta_frc_range;
    576     Word16 tmp_shift;
    577     Word16 temp;
    578     Word32 L_temp;
    579     Word16 flag4;
    580     Word16 carefulFlag;
    581     Word16 excEnergy;
    582     Word16 subfrNr;
    583     Word16 evenSubfr = 0;
    584 
    585     Word16 bfi = 0;   // bad frame indication flag
    586     Word16 pdfi = 0;  // potential degraded bad frame flag
    587 
    588     enum DTXStateType newDTXState;  // SPEECH , DTX, DTX_MUTE
    589 
    590     // find the new  DTX state  SPEECH OR DTX
    591     newDTXState = rx_dtx_handler(st->dtxDecoderState, frame_type);
    592 
    593     // DTX actions
    594     if (sub(newDTXState, SPEECH) != 0 )
    595     {
    596        Decoder_amr_reset (st, MRDTX);
    597 
    598        dtx_dec(st->dtxDecoderState,
    599                st->mem_syn,
    600                st->lsfState,
    601                st->pred_state,
    602                st->Cb_gain_averState,
    603                newDTXState,
    604                mode,
    605                parm, synth, A_t);
    606        // update average lsp
    607 
    608        Lsf_lsp(st->lsfState->past_lsf_q, st->lsp_old, M);
    609        lsp_avg(st->lsp_avg_st, st->lsfState->past_lsf_q);
    610        goto the_end;
    611     }
    612 
    613     // SPEECH action state machine
    614     if ((sub(frame_type, RX_SPEECH_BAD) == 0) ||
    615         (sub(frame_type, RX_NO_DATA) == 0) ||
    616         (sub(frame_type, RX_ONSET) == 0))
    617     {
    618        bfi = 1;
    619        if ((sub(frame_type, RX_NO_DATA) == 0) ||
    620            (sub(frame_type, RX_ONSET) == 0))
    621        {
    622       build_CN_param(&st->nodataSeed,
    623              prmno[mode],
    624              bitno[mode],
    625              parm);
    626        }
    627     }
    628     else if (sub(frame_type, RX_SPEECH_DEGRADED) == 0)
    629     {
    630        pdfi = 1;
    631     }
    632 
    633     if (bfi != 0)
    634     {
    635         st->state = add (st->state, 1);
    636     }
    637     else if (sub (st->state, 6) == 0)
    638 
    639     {
    640         st->state = 5;
    641     }
    642     else
    643     {
    644         st->state = 0;
    645     }
    646 
    647     if (sub (st->state, 6) > 0)
    648     {
    649         st->state = 6;
    650     }
    651 
    652     // If this frame is the first speech frame after CNI period,
    653     // set the BFH state machine to an appropriate state depending
    654     // on whether there was DTX muting before start of speech or not
    655     // If there was DTX muting, the first speech frame is muted.
    656     // If there was no DTX muting, the first speech frame is not
    657     // muted. The BFH state machine starts from state 5, however, to
    658     // keep the audible noise resulting from a SID frame which is
    659     // erroneously interpreted as a good speech frame as small as
    660     // possible (the decoder output in this case is quickly muted)
    661 
    662     if (sub(st->dtxDecoderState->dtxGlobalState, DTX) == 0)
    663     {
    664        st->state = 5;
    665        st->prev_bf = 0;
    666     }
    667     else if (sub(st->dtxDecoderState->dtxGlobalState, DTX_MUTE) == 0)
    668     {
    669        st->state = 5;
    670        st->prev_bf = 1;
    671     }
    672 
    673     // save old LSFs for CB gain smoothing
    674     Copy (st->lsfState->past_lsf_q, prev_lsf, M);
    675 
    676     // decode LSF parameters and generate interpolated lpc coefficients
    677        for the 4 subframes
    678     if (sub (mode, MR122) != 0)
    679     {
    680        D_plsf_3(st->lsfState, mode, bfi, parm, lsp_new);
    681 
    682        // Advance synthesis parameters pointer
    683        parm += 3;
    684 
    685        Int_lpc_1to3(st->lsp_old, lsp_new, A_t);
    686     }
    687     else
    688     {
    689        D_plsf_5 (st->lsfState, bfi, parm, lsp_mid, lsp_new);
    690 
    691        // Advance synthesis parameters pointer
    692        parm += 5;
    693 
    694        Int_lpc_1and3 (st->lsp_old, lsp_mid, lsp_new, A_t);
    695     }
    696 
    697     // update the LSPs for the next frame
    698     for (i = 0; i < M; i++)
    699     {
    700        st->lsp_old[i] = lsp_new[i];
    701     }
    702 
    703     *------------------------------------------------------------------------*
    704     *          Loop for every subframe in the analysis frame                 *
    705     *------------------------------------------------------------------------*
    706     * The subframe size is L_SUBFR and the loop is repeated L_FRAME/L_SUBFR  *
    707     *  times                                                                 *
    708     *     - decode the pitch delay                                           *
    709     *     - decode algebraic code                                            *
    710     *     - decode pitch and codebook gains                                  *
    711     *     - find the excitation and compute synthesis speech                 *
    712     *------------------------------------------------------------------------*
    713 
    714     // pointer to interpolated LPC parameters
    715     Az = A_t;
    716 
    717     evenSubfr = 0;
    718     subfrNr = -1;
    719     for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
    720     {
    721        subfrNr = add(subfrNr, 1);
    722        evenSubfr = sub(1, evenSubfr);
    723 
    724        // flag for first and 3th subframe
    725        pit_flag = i_subfr;
    726 
    727        if (sub (i_subfr, L_FRAME_BY2) == 0)
    728        {
    729           if (sub(mode, MR475) != 0 && sub(mode, MR515) != 0)
    730           {
    731              pit_flag = 0;
    732           }
    733        }
    734 
    735        // pitch index
    736        index = *parm++;
    737 
    738         *-------------------------------------------------------*
    739         * - decode pitch lag and find adaptive codebook vector. *
    740         *-------------------------------------------------------*
    741 
    742        if (sub(mode, MR122) != 0)
    743        {
    744           // flag4 indicates encoding with 4 bit resolution;
    745           // this is needed for mode MR475, MR515, MR59 and MR67
    746 
    747           flag4 = 0;
    748           if ((sub (mode, MR475) == 0) ||
    749               (sub (mode, MR515) == 0) ||
    750               (sub (mode, MR59) == 0) ||
    751               (sub (mode, MR67) == 0) ) {
    752              flag4 = 1;
    753           }
    754 
    755            *-------------------------------------------------------*
    756            * - get ranges for the t0_min and t0_max                *
    757            * - only needed in delta decoding                       *
    758            *-------------------------------------------------------*
    759 
    760           delta_frc_low = 5;
    761           delta_frc_range = 9;
    762 
    763           if ( sub(mode, MR795) == 0 )
    764           {
    765              delta_frc_low = 10;
    766              delta_frc_range = 19;
    767           }
    768 
    769           t0_min = sub(st->old_T0, delta_frc_low);
    770           if (sub(t0_min, PIT_MIN) < 0)
    771           {
    772              t0_min = PIT_MIN;
    773           }
    774           t0_max = add(t0_min, delta_frc_range);
    775           if (sub(t0_max, PIT_MAX) > 0)
    776           {
    777              t0_max = PIT_MAX;
    778              t0_min = sub(t0_max, delta_frc_range);
    779           }
    780 
    781           Dec_lag3 (index, t0_min, t0_max, pit_flag, st->old_T0,
    782                     &T0, &T0_frac, flag4);
    783 
    784           st->T0_lagBuff = T0;
    785 
    786           if (bfi != 0)
    787           {
    788              if (sub (st->old_T0, PIT_MAX) < 0)
    789              {                                      // Graceful pitch
    790                 st->old_T0 = add(st->old_T0, 1);    // degradation
    791              }
    792              T0 = st->old_T0;
    793              T0_frac = 0;
    794 
    795              if ( st->inBackgroundNoise != 0 &&
    796                   sub(st->voicedHangover, 4) > 0 &&
    797                   ((sub(mode, MR475) == 0 ) ||
    798                    (sub(mode, MR515) == 0 ) ||
    799                    (sub(mode, MR59) == 0) )
    800                   )
    801              {
    802                 T0 = st->T0_lagBuff;
    803              }
    804           }
    805 
    806           Pred_lt_3or6 (st->exc, T0, T0_frac, L_SUBFR, 1);
    807        }
    808        else
    809        {
    810           Dec_lag6 (index, PIT_MIN_MR122,
    811                     PIT_MAX, pit_flag, &T0, &T0_frac);
    812 
    813           if ( bfi == 0 && (pit_flag == 0 || sub (index, 61) < 0))
    814           {
    815           }
    816           else
    817           {
    818              st->T0_lagBuff = T0;
    819              T0 = st->old_T0;
    820              T0_frac = 0;
    821           }
    822 
    823           Pred_lt_3or6 (st->exc, T0, T0_frac, L_SUBFR, 0);
    824        }
    825 
    826         *-------------------------------------------------------*
    827         * - (MR122 only: Decode pitch gain.)                    *
    828         * - Decode innovative codebook.                         *
    829         * - set pitch sharpening factor                         *
    830         *-------------------------------------------------------*
    831 
    832         if (sub (mode, MR475) == 0 || sub (mode, MR515) == 0)
    833         {   // MR475, MR515
    834            index = *parm++;        // index of position
    835            i = *parm++;            // signs
    836 
    837            decode_2i40_9bits (subfrNr, i, index, code);
    838 
    839            pit_sharp = shl (st->sharp, 1);
    840         }
    841         else if (sub (mode, MR59) == 0)
    842         {   // MR59
    843            index = *parm++;        // index of position
    844            i = *parm++;            // signs
    845 
    846            decode_2i40_11bits (i, index, code);
    847 
    848            pit_sharp = shl (st->sharp, 1);
    849         }
    850         else if (sub (mode, MR67) == 0)
    851         {   // MR67
    852            index = *parm++;        // index of position
    853            i = *parm++;            // signs
    854 
    855            decode_3i40_14bits (i, index, code);
    856 
    857            pit_sharp = shl (st->sharp, 1);
    858         }
    859         else if (sub (mode, MR795) <= 0)
    860         {   // MR74, MR795
    861            index = *parm++;        // index of position
    862            i = *parm++;            // signs
    863 
    864            decode_4i40_17bits (i, index, code);
    865 
    866            pit_sharp = shl (st->sharp, 1);
    867         }
    868         else if (sub (mode, MR102) == 0)
    869         {  // MR102
    870            dec_8i40_31bits (parm, code);
    871            parm += 7;
    872 
    873            pit_sharp = shl (st->sharp, 1);
    874         }
    875         else
    876         {  // MR122
    877            index = *parm++;
    878            if (bfi != 0)
    879            {
    880               ec_gain_pitch (st->ec_gain_p_st, st->state, &gain_pit);
    881            }
    882            else
    883            {
    884               gain_pit = d_gain_pitch (mode, index);
    885            }
    886            ec_gain_pitch_update (st->ec_gain_p_st, bfi, st->prev_bf,
    887                                  &gain_pit);
    888 
    889            dec_10i40_35bits (parm, code);
    890            parm += 10;
    891 
    892            // pit_sharp = gain_pit;
    893            // if (pit_sharp > 1.0) pit_sharp = 1.0;
    894 
    895            pit_sharp = shl (gain_pit, 1);
    896         }
    897 
    898          *-------------------------------------------------------*
    899          * - Add the pitch contribution to code[].               *
    900          *-------------------------------------------------------*
    901         for (i = T0; i < L_SUBFR; i++)
    902         {
    903            temp = mult (code[i - T0], pit_sharp);
    904            code[i] = add (code[i], temp);
    905         }
    906 
    907          *------------------------------------------------------------*
    908          * - Decode codebook gain (MR122) or both pitch               *
    909          *   gain and codebook gain (all others)                      *
    910          * - Update pitch sharpening "sharp" with quantized gain_pit  *
    911          *------------------------------------------------------------*
    912 
    913         if (sub (mode, MR475) == 0)
    914         {
    915            // read and decode pitch and code gain
    916            if (evenSubfr != 0)
    917            {
    918               index_mr475 = *parm++; // index of gain(s)
    919            }
    920 
    921            if (bfi == 0)
    922            {
    923               Dec_gain(st->pred_state, mode, index_mr475, code,
    924                        evenSubfr, &gain_pit, &gain_code);
    925            }
    926            else
    927            {
    928               ec_gain_pitch (st->ec_gain_p_st, st->state, &gain_pit);
    929               ec_gain_code (st->ec_gain_c_st, st->pred_state, st->state,
    930                             &gain_code);
    931            }
    932            ec_gain_pitch_update (st->ec_gain_p_st, bfi, st->prev_bf,
    933                                  &gain_pit);
    934            ec_gain_code_update (st->ec_gain_c_st, bfi, st->prev_bf,
    935                                 &gain_code);
    936 
    937            pit_sharp = gain_pit;
    938            if (sub (pit_sharp, SHARPMAX) > 0)
    939            {
    940                pit_sharp = SHARPMAX;
    941            }
    942 
    943         }
    944         else if ((sub (mode, MR74) <= 0) ||
    945                  (sub (mode, MR102) == 0))
    946         {
    947             // read and decode pitch and code gain
    948             index = *parm++; // index of gain(s)
    949 
    950             if (bfi == 0)
    951             {
    952                Dec_gain(st->pred_state, mode, index, code,
    953                         evenSubfr, &gain_pit, &gain_code);
    954             }
    955             else
    956             {
    957                ec_gain_pitch (st->ec_gain_p_st, st->state, &gain_pit);
    958                ec_gain_code (st->ec_gain_c_st, st->pred_state, st->state,
    959                              &gain_code);
    960             }
    961             ec_gain_pitch_update (st->ec_gain_p_st, bfi, st->prev_bf,
    962                                   &gain_pit);
    963             ec_gain_code_update (st->ec_gain_c_st, bfi, st->prev_bf,
    964                                  &gain_code);
    965 
    966             pit_sharp = gain_pit;
    967             if (sub (pit_sharp, SHARPMAX) > 0)
    968             {
    969                pit_sharp = SHARPMAX;
    970             }
    971 
    972             if (sub (mode, MR102) == 0)
    973             {
    974                if (sub (st->old_T0, add(L_SUBFR, 5)) > 0)
    975                {
    976                   pit_sharp = shr(pit_sharp, 2);
    977                }
    978             }
    979         }
    980         else
    981         {
    982            // read and decode pitch gain
    983            index = *parm++; // index of gain(s)
    984 
    985            if (sub (mode, MR795) == 0)
    986            {
    987               // decode pitch gain
    988               if (bfi != 0)
    989               {
    990                  ec_gain_pitch (st->ec_gain_p_st, st->state, &gain_pit);
    991               }
    992               else
    993               {
    994                  gain_pit = d_gain_pitch (mode, index);
    995               }
    996               ec_gain_pitch_update (st->ec_gain_p_st, bfi, st->prev_bf,
    997                                     &gain_pit);
    998 
    999               // read and decode code gain
   1000               index = *parm++;
   1001               if (bfi == 0)
   1002               {
   1003                  d_gain_code (st->pred_state, mode, index, code, &gain_code);
   1004               }
   1005               else
   1006               {
   1007                  ec_gain_code (st->ec_gain_c_st, st->pred_state, st->state,
   1008                                &gain_code);
   1009               }
   1010               ec_gain_code_update (st->ec_gain_c_st, bfi, st->prev_bf,
   1011                                    &gain_code);
   1012 
   1013               pit_sharp = gain_pit;
   1014               if (sub (pit_sharp, SHARPMAX) > 0)
   1015               {
   1016                  pit_sharp = SHARPMAX;
   1017               }
   1018            }
   1019            else
   1020            { // MR122
   1021               if (bfi == 0)
   1022               {
   1023                  d_gain_code (st->pred_state, mode, index, code, &gain_code);
   1024               }
   1025               else
   1026               {
   1027                  ec_gain_code (st->ec_gain_c_st, st->pred_state, st->state,
   1028                                &gain_code);
   1029               }
   1030               ec_gain_code_update (st->ec_gain_c_st, bfi, st->prev_bf,
   1031                                    &gain_code);
   1032 
   1033               pit_sharp = gain_pit;
   1034            }
   1035         }
   1036 
   1037         // store pitch sharpening for next subframe
   1038         // (for modes which use the previous pitch gain for
   1039         // pitch sharpening in the search phase)
   1040         // do not update sharpening in even subframes for MR475
   1041         if (sub(mode, MR475) != 0 || evenSubfr == 0)
   1042         {
   1043             st->sharp = gain_pit;
   1044             if (sub (st->sharp, SHARPMAX) > 0)
   1045             {
   1046                 st->sharp = SHARPMAX;
   1047             }
   1048         }
   1049 
   1050         pit_sharp = shl (pit_sharp, 1);
   1051         if (sub (pit_sharp, 16384) > 0)
   1052         {
   1053            for (i = 0; i < L_SUBFR; i++)
   1054             {
   1055                temp = mult (st->exc[i], pit_sharp);
   1056                L_temp = L_mult (temp, gain_pit);
   1057                if (sub(mode, MR122)==0)
   1058                {
   1059                   L_temp = L_shr (L_temp, 1);
   1060                }
   1061                excp[i] = pv_round (L_temp);
   1062             }
   1063         }
   1064 
   1065          *-------------------------------------------------------*
   1066          * - Store list of LTP gains needed in the source        *
   1067          *   characteristic detector (SCD)                       *
   1068          *-------------------------------------------------------*
   1069         if ( bfi == 0 )
   1070         {
   1071            for (i = 0; i < 8; i++)
   1072            {
   1073               st->ltpGainHistory[i] = st->ltpGainHistory[i+1];
   1074            }
   1075            st->ltpGainHistory[8] = gain_pit;
   1076         }
   1077 
   1078          *-------------------------------------------------------*
   1079          * - Limit gain_pit if in background noise and BFI       *
   1080          *   for MR475, MR515, MR59                              *
   1081          *-------------------------------------------------------*
   1082 
   1083         if ( (st->prev_bf != 0 || bfi != 0) && st->inBackgroundNoise != 0 &&
   1084              ((sub(mode, MR475) == 0) ||
   1085               (sub(mode, MR515) == 0) ||
   1086               (sub(mode, MR59) == 0))
   1087              )
   1088         {
   1089            if ( sub (gain_pit, 12288) > 0)    // if (gain_pit > 0.75) in Q14
   1090               gain_pit = add( shr( sub(gain_pit, 12288), 1 ), 12288 );
   1091               // gain_pit = (gain_pit-0.75)/2.0 + 0.75;
   1092 
   1093            if ( sub (gain_pit, 14745) > 0)    // if (gain_pit > 0.90) in Q14
   1094            {
   1095               gain_pit = 14745;
   1096            }
   1097         }
   1098 
   1099          *-------------------------------------------------------*
   1100          *  Calculate CB mixed gain                              *
   1101          *-------------------------------------------------------*
   1102         Int_lsf(prev_lsf, st->lsfState->past_lsf_q, i_subfr, lsf_i);
   1103         gain_code_mix = Cb_gain_average(
   1104             st->Cb_gain_averState, mode, gain_code,
   1105             lsf_i, st->lsp_avg_st->lsp_meanSave, bfi,
   1106             st->prev_bf, pdfi, st->prev_pdf,
   1107             st->inBackgroundNoise, st->voicedHangover);
   1108 
   1109         // make sure that MR74, MR795, MR122 have original code_gain
   1110         if ((sub(mode, MR67) > 0) && (sub(mode, MR102) != 0) )
   1111            // MR74, MR795, MR122
   1112         {
   1113            gain_code_mix = gain_code;
   1114         }
   1115 
   1116          *-------------------------------------------------------*
   1117          * - Find the total excitation.                          *
   1118          * - Find synthesis speech corresponding to st->exc[].   *
   1119          *-------------------------------------------------------*
   1120         if (sub(mode, MR102) <= 0) // MR475, MR515, MR59, MR67, MR74, MR795, MR102
   1121         {
   1122            pitch_fac = gain_pit;
   1123            tmp_shift = 1;
   1124         }
   1125         else       // MR122
   1126         {
   1127            pitch_fac = shr (gain_pit, 1);
   1128            tmp_shift = 2;
   1129         }
   1130 
   1131         // copy unscaled LTP excitation to exc_enhanced (used in phase
   1132          * dispersion below) and compute total excitation for LTP feedback
   1133 
   1134         for (i = 0; i < L_SUBFR; i++)
   1135         {
   1136            exc_enhanced[i] = st->exc[i];
   1137 
   1138            // st->exc[i] = gain_pit*st->exc[i] + gain_code*code[i];
   1139            L_temp = L_mult (st->exc[i], pitch_fac);
   1140                                                       // 12.2: Q0 * Q13
   1141                                                       //  7.4: Q0 * Q14
   1142            L_temp = L_mac (L_temp, code[i], gain_code);
   1143                                                       // 12.2: Q12 * Q1
   1144                                                       //  7.4: Q13 * Q1
   1145            L_temp = L_shl (L_temp, tmp_shift);                   // Q16
   1146            st->exc[i] = pv_round (L_temp);
   1147         }
   1148 
   1149          *-------------------------------------------------------*
   1150          * - Adaptive phase dispersion                           *
   1151          *-------------------------------------------------------*
   1152         ph_disp_release(st->ph_disp_st); // free phase dispersion adaption
   1153 
   1154         if ( ((sub(mode, MR475) == 0) ||
   1155               (sub(mode, MR515) == 0) ||
   1156               (sub(mode, MR59) == 0))   &&
   1157              sub(st->voicedHangover, 3) > 0 &&
   1158              st->inBackgroundNoise != 0 &&
   1159              bfi != 0 )
   1160         {
   1161            ph_disp_lock(st->ph_disp_st); // Always Use full Phase Disp.
   1162         }                                // if error in bg noise
   1163 
   1164         // apply phase dispersion to innovation (if enabled) and
   1165            compute total excitation for synthesis part
   1166         ph_disp(st->ph_disp_st, mode,
   1167                 exc_enhanced, gain_code_mix, gain_pit, code,
   1168                 pitch_fac, tmp_shift);
   1169 
   1170          *-------------------------------------------------------*
   1171          * - The Excitation control module are active during BFI.*
   1172          * - Conceal drops in signal energy if in bg noise.      *
   1173          *-------------------------------------------------------*
   1174 
   1175         L_temp = 0;
   1176         for (i = 0; i < L_SUBFR; i++)
   1177         {
   1178             L_temp = L_mac (L_temp, exc_enhanced[i], exc_enhanced[i] );
   1179         }
   1180 
   1181         L_temp = L_shr (L_temp, 1);     // excEnergy = sqrt(L_temp) in Q0
   1182         L_temp = sqrt_l_exp(L_temp, &temp); // function result
   1183         L_temp = L_shr(L_temp, add( shr(temp, 1), 15));
   1184         L_temp = L_shr(L_temp, 2);       // To cope with 16-bit and
   1185         excEnergy = extract_l(L_temp);   // scaling in ex_ctrl()
   1186 
   1187         if ( ((sub (mode, MR475) == 0) ||
   1188               (sub (mode, MR515) == 0) ||
   1189               (sub (mode, MR59) == 0))  &&
   1190              sub(st->voicedHangover, 5) > 0 &&
   1191              st->inBackgroundNoise != 0 &&
   1192              sub(st->state, 4) < 0 &&
   1193              ( (pdfi != 0 && st->prev_pdf != 0) ||
   1194                 bfi != 0 ||
   1195                 st->prev_bf != 0) )
   1196         {
   1197            carefulFlag = 0;
   1198            if ( pdfi != 0 && bfi == 0 )
   1199            {
   1200               carefulFlag = 1;
   1201            }
   1202 
   1203            Ex_ctrl(exc_enhanced,
   1204                    excEnergy,
   1205                    st->excEnergyHist,
   1206                    st->voicedHangover,
   1207                    st->prev_bf,
   1208                    carefulFlag);
   1209         }
   1210 
   1211         if ( st->inBackgroundNoise != 0 &&
   1212              ( bfi != 0 || st->prev_bf != 0 ) &&
   1213              sub(st->state, 4) < 0 )
   1214         {
   1215            ; // do nothing!
   1216         }
   1217         else
   1218         {
   1219            // Update energy history for all modes
   1220            for (i = 0; i < 8; i++)
   1221            {
   1222               st->excEnergyHist[i] = st->excEnergyHist[i+1];
   1223            }
   1224            st->excEnergyHist[8] = excEnergy;
   1225         }
   1226          *-------------------------------------------------------*
   1227          * Excitation control module end.                        *
   1228          *-------------------------------------------------------*
   1229 
   1230         if (sub (pit_sharp, 16384) > 0)
   1231         {
   1232            for (i = 0; i < L_SUBFR; i++)
   1233            {
   1234               excp[i] = add (excp[i], exc_enhanced[i]);
   1235            }
   1236            agc2 (exc_enhanced, excp, L_SUBFR);
   1237            Overflow = 0;
   1238            Syn_filt (Az, excp, &synth[i_subfr], L_SUBFR,
   1239                      st->mem_syn, 0);
   1240         }
   1241         else
   1242         {
   1243            Overflow = 0;
   1244            Syn_filt (Az, exc_enhanced, &synth[i_subfr], L_SUBFR,
   1245                      st->mem_syn, 0);
   1246         }
   1247 
   1248         if (Overflow != 0)    // Test for overflow
   1249         {
   1250            for (i = 0; i < PIT_MAX + L_INTERPOL + L_SUBFR; i++)
   1251            {
   1252               st->old_exc[i] = shr(st->old_exc[i], 2);
   1253            }
   1254            for (i = 0; i < L_SUBFR; i++)
   1255            {
   1256               exc_enhanced[i] = shr(exc_enhanced[i], 2);
   1257            }
   1258            Syn_filt(Az, exc_enhanced, &synth[i_subfr], L_SUBFR, st->mem_syn, 1);
   1259         }
   1260         else
   1261         {
   1262            Copy(&synth[i_subfr+L_SUBFR-M], st->mem_syn, M);
   1263         }
   1264 
   1265          *--------------------------------------------------*
   1266          * Update signal for next frame.                    *
   1267          * -> shift to the left by L_SUBFR  st->exc[]       *
   1268          *--------------------------------------------------*
   1269 
   1270         Copy (&st->old_exc[L_SUBFR], &st->old_exc[0], PIT_MAX + L_INTERPOL);
   1271 
   1272         // interpolated LPC parameters for next subframe
   1273         Az += MP1;
   1274 
   1275         // store T0 for next subframe
   1276         st->old_T0 = T0;
   1277     }
   1278 
   1279      *-------------------------------------------------------*
   1280      * Call the Source Characteristic Detector which updates *
   1281      * st->inBackgroundNoise and st->voicedHangover.         *
   1282      *-------------------------------------------------------*
   1283 
   1284     st->inBackgroundNoise = Bgn_scd(st->background_state,
   1285                                     &(st->ltpGainHistory[0]),
   1286                                     &(synth[0]),
   1287                                     &(st->voicedHangover) );
   1288 
   1289     dtx_dec_activity_update(st->dtxDecoderState,
   1290                             st->lsfState->past_lsf_q,
   1291                             synth);
   1292 
   1293     // store bfi for next subframe
   1294     st->prev_bf = bfi;
   1295     st->prev_pdf = pdfi;
   1296 
   1297      *--------------------------------------------------*
   1298      * Calculate the LSF averages on the eight          *
   1299      * previous frames                                  *
   1300      *--------------------------------------------------*
   1301 
   1302     lsp_avg(st->lsp_avg_st, st->lsfState->past_lsf_q);
   1303 
   1304 the_end:
   1305     st->dtxDecoderState->dtxGlobalState = newDTXState;
   1306 
   1307     return 0;
   1308 }
   1309 
   1310 ------------------------------------------------------------------------------
   1311  RESOURCES USED [optional]
   1312 
   1313  When the code is written for a specific target processor the
   1314  the resources used should be documented below.
   1315 
   1316  HEAP MEMORY USED: x bytes
   1317 
   1318  STACK MEMORY USED: x bytes
   1319 
   1320  CLOCK CYCLES: (cycle count equation for this function) + (variable
   1321                 used to represent cycle count for each subroutine
   1322                 called)
   1323      where: (cycle count variable) = cycle count for [subroutine
   1324                                      name]
   1325 
   1326 ------------------------------------------------------------------------------
   1327  CAUTION [optional]
   1328  [State any special notes, constraints or cautions for users of this function]
   1329 
   1330 ------------------------------------------------------------------------------
   1331 */
   1332 
   1333 void Decoder_amr(
   1334     Decoder_amrState *st,      /* i/o : State variables                   */
   1335     enum Mode mode,            /* i   : AMR mode                          */
   1336     Word16 parm[],             /* i   : vector of synthesis parameters
   1337                                         (PRM_SIZE)                        */
   1338     enum RXFrameType frame_type, /* i   : received frame type             */
   1339     Word16 synth[],            /* o   : synthesis speech (L_FRAME)        */
   1340     Word16 A_t[]               /* o   : decoded LP filter in 4 subframes
   1341                                         (AZ_SIZE)                         */
   1342 )
   1343 {
   1344     /* LPC coefficients */
   1345 
   1346     Word16 *Az;                /* Pointer on A_t */
   1347 
   1348     /* LSPs */
   1349 
   1350     Word16 lsp_new[M];
   1351     Word16 lsp_mid[M];
   1352 
   1353     /* LSFs */
   1354 
   1355     Word16 prev_lsf[M];
   1356     Word16 lsf_i[M];
   1357 
   1358     /* Algebraic codevector */
   1359 
   1360     Word16 code[L_SUBFR];
   1361 
   1362     /* excitation */
   1363 
   1364     Word16 excp[L_SUBFR];
   1365     Word16 exc_enhanced[L_SUBFR];
   1366 
   1367     /* Scalars */
   1368 
   1369     Word16 i;
   1370     Word16 i_subfr;
   1371     Word16 T0;
   1372     Word16 T0_frac;
   1373     Word16 index;
   1374     Word16 index_mr475 = 0;
   1375     Word16 gain_pit;
   1376     Word16 gain_code;
   1377     Word16 gain_code_mix;
   1378     Word16 pit_sharp;
   1379     Word16 pit_flag;
   1380     Word16 pitch_fac;
   1381     Word16 t0_min;
   1382     Word16 t0_max;
   1383     Word16 delta_frc_low;
   1384     Word16 delta_frc_range;
   1385     Word16 tmp_shift;
   1386     Word16 temp;
   1387     Word32 L_temp;
   1388     Word16 flag4;
   1389     Word16 carefulFlag;
   1390     Word16 excEnergy;
   1391     Word16 subfrNr;
   1392     Word16 evenSubfr = 0;
   1393 
   1394     Word16 bfi = 0;   /* bad frame indication flag                          */
   1395     Word16 pdfi = 0;  /* potential degraded bad frame flag                  */
   1396 
   1397     enum DTXStateType newDTXState;  /* SPEECH , DTX, DTX_MUTE */
   1398     Flag   *pOverflow = &(st->overflow);     /* Overflow flag            */
   1399 
   1400 
   1401     /* find the new  DTX state  SPEECH OR DTX */
   1402     newDTXState = rx_dtx_handler(&(st->dtxDecoderState), frame_type, pOverflow);
   1403 
   1404     /* DTX actions */
   1405 
   1406     if (newDTXState != SPEECH)
   1407     {
   1408         Decoder_amr_reset(st, MRDTX);
   1409 
   1410         dtx_dec(&(st->dtxDecoderState),
   1411                 st->mem_syn,
   1412                 &(st->lsfState),
   1413                 &(st->pred_state),
   1414                 &(st->Cb_gain_averState),
   1415                 newDTXState,
   1416                 mode,
   1417                 parm, synth, A_t, pOverflow);
   1418 
   1419         /* update average lsp */
   1420         Lsf_lsp(
   1421             st->lsfState.past_lsf_q,
   1422             st->lsp_old,
   1423             M,
   1424             pOverflow);
   1425 
   1426         lsp_avg(
   1427             &(st->lsp_avg_st),
   1428             st->lsfState.past_lsf_q,
   1429             pOverflow);
   1430 
   1431         goto the_end;
   1432     }
   1433 
   1434     /* SPEECH action state machine  */
   1435     if ((frame_type == RX_SPEECH_BAD) || (frame_type == RX_NO_DATA) ||
   1436             (frame_type == RX_ONSET))
   1437     {
   1438         bfi = 1;
   1439 
   1440         if ((frame_type == RX_NO_DATA) || (frame_type == RX_ONSET))
   1441         {
   1442             build_CN_param(&st->nodataSeed,
   1443                            prmno[mode],
   1444                            bitno[mode],
   1445                            parm,
   1446                            pOverflow);
   1447         }
   1448     }
   1449     else if (frame_type == RX_SPEECH_DEGRADED)
   1450     {
   1451         pdfi = 1;
   1452     }
   1453 
   1454     if (bfi != 0)
   1455     {
   1456         st->state += 1;
   1457     }
   1458     else if (st->state == 6)
   1459 
   1460     {
   1461         st->state = 5;
   1462     }
   1463     else
   1464     {
   1465         st->state = 0;
   1466     }
   1467 
   1468 
   1469     if (st->state > 6)
   1470     {
   1471         st->state = 6;
   1472     }
   1473 
   1474     /* If this frame is the first speech frame after CNI period,     */
   1475     /* set the BFH state machine to an appropriate state depending   */
   1476     /* on whether there was DTX muting before start of speech or not */
   1477     /* If there was DTX muting, the first speech frame is muted.     */
   1478     /* If there was no DTX muting, the first speech frame is not     */
   1479     /* muted. The BFH state machine starts from state 5, however, to */
   1480     /* keep the audible noise resulting from a SID frame which is    */
   1481     /* erroneously interpreted as a good speech frame as small as    */
   1482     /* possible (the decoder output in this case is quickly muted)   */
   1483 
   1484     if (st->dtxDecoderState.dtxGlobalState == DTX)
   1485     {
   1486         st->state = 5;
   1487         st->prev_bf = 0;
   1488     }
   1489     else if (st->dtxDecoderState.dtxGlobalState == DTX_MUTE)
   1490     {
   1491         st->state = 5;
   1492         st->prev_bf = 1;
   1493     }
   1494 
   1495     /* save old LSFs for CB gain smoothing */
   1496     Copy(st->lsfState.past_lsf_q, prev_lsf, M);
   1497 
   1498     /* decode LSF parameters and generate interpolated lpc coefficients
   1499        for the 4 subframes */
   1500 
   1501     if (mode != MR122)
   1502     {
   1503         D_plsf_3(
   1504             &(st->lsfState),
   1505             mode,
   1506             bfi,
   1507             parm,
   1508             lsp_new,
   1509             pOverflow);
   1510 
   1511         /* Advance synthesis parameters pointer */
   1512         parm += 3;
   1513 
   1514         Int_lpc_1to3(
   1515             st->lsp_old,
   1516             lsp_new,
   1517             A_t,
   1518             pOverflow);
   1519     }
   1520     else
   1521     {
   1522         D_plsf_5(
   1523             &(st->lsfState),
   1524             bfi,
   1525             parm,
   1526             lsp_mid,
   1527             lsp_new,
   1528             pOverflow);
   1529 
   1530         /* Advance synthesis parameters pointer */
   1531         parm += 5;
   1532 
   1533         Int_lpc_1and3(
   1534             st->lsp_old,
   1535             lsp_mid,
   1536             lsp_new,
   1537             A_t,
   1538             pOverflow);
   1539     }
   1540 
   1541     /* update the LSPs for the next frame */
   1542     for (i = 0; i < M; i++)
   1543     {
   1544         st->lsp_old[i] = lsp_new[i];
   1545     }
   1546 
   1547     /*------------------------------------------------------------------------*
   1548      *          Loop for every subframe in the analysis frame                 *
   1549      *------------------------------------------------------------------------*
   1550      * The subframe size is L_SUBFR and the loop is repeated L_FRAME/L_SUBFR  *
   1551      *  times                                                                 *
   1552      *     - decode the pitch delay                                           *
   1553      *     - decode algebraic code                                            *
   1554      *     - decode pitch and codebook gains                                  *
   1555      *     - find the excitation and compute synthesis speech                 *
   1556      *------------------------------------------------------------------------*/
   1557 
   1558     /* pointer to interpolated LPC parameters */
   1559     Az = A_t;
   1560 
   1561     evenSubfr = 0;
   1562     subfrNr = -1;
   1563     for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
   1564     {
   1565         subfrNr += 1;
   1566         evenSubfr = 1 - evenSubfr;
   1567 
   1568         /* flag for first and 3th subframe */
   1569         pit_flag = i_subfr;
   1570 
   1571 
   1572         if (i_subfr == L_FRAME_BY2)
   1573         {
   1574             if ((mode != MR475) && (mode != MR515))
   1575             {
   1576                 pit_flag = 0;
   1577             }
   1578         }
   1579 
   1580         /* pitch index */
   1581         index = *parm++;
   1582 
   1583         /*-------------------------------------------------------*
   1584         * - decode pitch lag and find adaptive codebook vector. *
   1585         *-------------------------------------------------------*/
   1586 
   1587         if (mode != MR122)
   1588         {
   1589             /* flag4 indicates encoding with 4 bit resolution;     */
   1590             /* this is needed for mode MR475, MR515, MR59 and MR67 */
   1591 
   1592             flag4 = 0;
   1593 
   1594             if ((mode == MR475) || (mode == MR515) || (mode == MR59) ||
   1595                     (mode == MR67))
   1596             {
   1597                 flag4 = 1;
   1598             }
   1599 
   1600             /*-------------------------------------------------------*
   1601             * - get ranges for the t0_min and t0_max                *
   1602             * - only needed in delta decoding                       *
   1603             *-------------------------------------------------------*/
   1604 
   1605             delta_frc_low = 5;
   1606             delta_frc_range = 9;
   1607 
   1608             if (mode == MR795)
   1609             {
   1610                 delta_frc_low = 10;
   1611                 delta_frc_range = 19;
   1612             }
   1613 
   1614             t0_min = sub(st->old_T0, delta_frc_low, pOverflow);
   1615 
   1616             if (t0_min < PIT_MIN)
   1617             {
   1618                 t0_min = PIT_MIN;
   1619             }
   1620             t0_max = add(t0_min, delta_frc_range, pOverflow);
   1621 
   1622             if (t0_max > PIT_MAX)
   1623             {
   1624                 t0_max = PIT_MAX;
   1625                 t0_min = t0_max - delta_frc_range;
   1626             }
   1627 
   1628             Dec_lag3(index, t0_min, t0_max, pit_flag, st->old_T0,
   1629                      &T0, &T0_frac, flag4, pOverflow);
   1630 
   1631             st->T0_lagBuff = T0;
   1632 
   1633             if (bfi != 0)
   1634             {
   1635                 if (st->old_T0 < PIT_MAX)
   1636                 {                               /* Graceful pitch */
   1637                     st->old_T0 += 0;            /* degradation    */
   1638                 }
   1639                 T0 = st->old_T0;
   1640                 T0_frac = 0;
   1641 
   1642                 if ((st->inBackgroundNoise != 0) && (st->voicedHangover > 4) &&
   1643                         ((mode == MR475) || (mode == MR515) || (mode == MR59)))
   1644                 {
   1645                     T0 = st->T0_lagBuff;
   1646                 }
   1647             }
   1648 
   1649             Pred_lt_3or6(st->exc, T0, T0_frac, L_SUBFR, 1, pOverflow);
   1650         }
   1651         else
   1652         {
   1653             Dec_lag6(index, PIT_MIN_MR122,
   1654                      PIT_MAX, pit_flag, &T0, &T0_frac, pOverflow);
   1655 
   1656 
   1657             if (!(bfi == 0 && (pit_flag == 0 || index < 61)))
   1658             {
   1659                 st->T0_lagBuff = T0;
   1660                 T0 = st->old_T0;
   1661                 T0_frac = 0;
   1662             }
   1663 
   1664             Pred_lt_3or6(st->exc, T0, T0_frac, L_SUBFR, 0, pOverflow);
   1665         }
   1666 
   1667         /*-------------------------------------------------------*
   1668          * - (MR122 only: Decode pitch gain.)                    *
   1669          * - Decode innovative codebook.                         *
   1670          * - set pitch sharpening factor                         *
   1671          *-------------------------------------------------------*/
   1672         if ((mode == MR475) || (mode == MR515))
   1673         {   /* MR475, MR515 */
   1674             index = *parm++;        /* index of position */
   1675             i = *parm++;            /* signs             */
   1676 
   1677             decode_2i40_9bits(subfrNr, i, index, code, pOverflow);
   1678 
   1679             L_temp = (Word32)st->sharp << 1;
   1680             if (L_temp != (Word32)((Word16) L_temp))
   1681             {
   1682                 pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
   1683             }
   1684             else
   1685             {
   1686                 pit_sharp = (Word16) L_temp;
   1687             }
   1688         }
   1689         else if (mode == MR59)
   1690         {   /* MR59 */
   1691             index = *parm++;        /* index of position */
   1692             i = *parm++;            /* signs             */
   1693 
   1694             decode_2i40_11bits(i, index, code);
   1695 
   1696             L_temp = (Word32)st->sharp << 1;
   1697             if (L_temp != (Word32)((Word16) L_temp))
   1698             {
   1699                 pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
   1700             }
   1701             else
   1702             {
   1703                 pit_sharp = (Word16) L_temp;
   1704             }
   1705         }
   1706         else if (mode == MR67)
   1707         {   /* MR67 */
   1708             index = *parm++;        /* index of position */
   1709             i = *parm++;            /* signs             */
   1710 
   1711             decode_3i40_14bits(i, index, code);
   1712 
   1713             L_temp = (Word32)st->sharp << 1;
   1714             if (L_temp != (Word32)((Word16) L_temp))
   1715             {
   1716                 pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
   1717             }
   1718             else
   1719             {
   1720                 pit_sharp = (Word16) L_temp;
   1721             }
   1722         }
   1723         else if (mode <= MR795)
   1724         {   /* MR74, MR795 */
   1725             index = *parm++;        /* index of position */
   1726             i = *parm++;            /* signs             */
   1727 
   1728             decode_4i40_17bits(i, index, code);
   1729 
   1730             L_temp = (Word32)st->sharp << 1;
   1731             if (L_temp != (Word32)((Word16) L_temp))
   1732             {
   1733                 pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
   1734             }
   1735             else
   1736             {
   1737                 pit_sharp = (Word16) L_temp;
   1738             }
   1739         }
   1740         else if (mode == MR102)
   1741         {  /* MR102 */
   1742             dec_8i40_31bits(parm, code, pOverflow);
   1743             parm += 7;
   1744 
   1745             L_temp = (Word32)st->sharp << 1;
   1746             if (L_temp != (Word32)((Word16) L_temp))
   1747             {
   1748                 pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
   1749             }
   1750             else
   1751             {
   1752                 pit_sharp = (Word16) L_temp;
   1753             }
   1754         }
   1755         else
   1756         {  /* MR122 */
   1757             index = *parm++;
   1758 
   1759             if (bfi != 0)
   1760             {
   1761                 ec_gain_pitch(
   1762                     &(st->ec_gain_p_st),
   1763                     st->state,
   1764                     &gain_pit,
   1765                     pOverflow);
   1766             }
   1767             else
   1768             {
   1769                 gain_pit = d_gain_pitch(mode, index);
   1770             }
   1771             ec_gain_pitch_update(
   1772                 &(st->ec_gain_p_st),
   1773                 bfi,
   1774                 st->prev_bf,
   1775                 &gain_pit,
   1776                 pOverflow);
   1777 
   1778 
   1779             dec_10i40_35bits(parm, code);
   1780             parm += 10;
   1781 
   1782             /* pit_sharp = gain_pit;                   */
   1783             /* if (pit_sharp > 1.0) pit_sharp = 1.0;   */
   1784 
   1785             L_temp = (Word32)gain_pit << 1;
   1786             if (L_temp != (Word32)((Word16) L_temp))
   1787             {
   1788                 pit_sharp = (gain_pit > 0) ? MAX_16 : MIN_16;
   1789             }
   1790             else
   1791             {
   1792                 pit_sharp = (Word16) L_temp;
   1793             }
   1794         }
   1795         /*-------------------------------------------------------*
   1796          * - Add the pitch contribution to code[].               *
   1797          *-------------------------------------------------------*/
   1798         for (i = T0; i < L_SUBFR; i++)
   1799         {
   1800             temp = mult(*(code + i - T0), pit_sharp, pOverflow);
   1801             *(code + i) = add(*(code + i), temp, pOverflow);
   1802 
   1803         }
   1804 
   1805         /*------------------------------------------------------------*
   1806          * - Decode codebook gain (MR122) or both pitch               *
   1807          *   gain and codebook gain (all others)                      *
   1808          * - Update pitch sharpening "sharp" with quantized gain_pit  *
   1809          *------------------------------------------------------------*/
   1810         if (mode == MR475)
   1811         {
   1812             /* read and decode pitch and code gain */
   1813 
   1814             if (evenSubfr != 0)
   1815             {
   1816                 index_mr475 = *parm++;         /* index of gain(s) */
   1817             }
   1818 
   1819             if (bfi == 0)
   1820             {
   1821                 Dec_gain(
   1822                     &(st->pred_state),
   1823                     mode,
   1824                     index_mr475,
   1825                     code,
   1826                     evenSubfr,
   1827                     &gain_pit,
   1828                     &gain_code,
   1829                     pOverflow);
   1830             }
   1831             else
   1832             {
   1833                 ec_gain_pitch(
   1834                     &(st->ec_gain_p_st),
   1835                     st->state,
   1836                     &gain_pit,
   1837                     pOverflow);
   1838 
   1839                 ec_gain_code(
   1840                     &(st->ec_gain_c_st),
   1841                     &(st->pred_state),
   1842                     st->state,
   1843                     &gain_code,
   1844                     pOverflow);
   1845             }
   1846             ec_gain_pitch_update(
   1847                 &st->ec_gain_p_st,
   1848                 bfi,
   1849                 st->prev_bf,
   1850                 &gain_pit,
   1851                 pOverflow);
   1852 
   1853             ec_gain_code_update(
   1854                 &st->ec_gain_c_st,
   1855                 bfi,
   1856                 st->prev_bf,
   1857                 &gain_code,
   1858                 pOverflow);
   1859 
   1860             pit_sharp = gain_pit;
   1861 
   1862             if (pit_sharp > SHARPMAX)
   1863             {
   1864                 pit_sharp = SHARPMAX;
   1865             }
   1866 
   1867         }
   1868         else if ((mode <= MR74) || (mode == MR102))
   1869         {
   1870             /* read and decode pitch and code gain */
   1871             index = *parm++;                 /* index of gain(s) */
   1872 
   1873             if (bfi == 0)
   1874             {
   1875                 Dec_gain(
   1876                     &(st->pred_state),
   1877                     mode,
   1878                     index,
   1879                     code,
   1880                     evenSubfr,
   1881                     &gain_pit,
   1882                     &gain_code,
   1883                     pOverflow);
   1884             }
   1885             else
   1886             {
   1887                 ec_gain_pitch(
   1888                     &(st->ec_gain_p_st),
   1889                     st->state,
   1890                     &gain_pit,
   1891                     pOverflow);
   1892 
   1893                 ec_gain_code(
   1894                     &(st->ec_gain_c_st),
   1895                     &(st->pred_state),
   1896                     st->state,
   1897                     &gain_code,
   1898                     pOverflow);
   1899             }
   1900 
   1901             ec_gain_pitch_update(
   1902                 &(st->ec_gain_p_st),
   1903                 bfi,
   1904                 st->prev_bf,
   1905                 &gain_pit,
   1906                 pOverflow);
   1907 
   1908             ec_gain_code_update(
   1909                 &(st->ec_gain_c_st),
   1910                 bfi,
   1911                 st->prev_bf,
   1912                 &gain_code,
   1913                 pOverflow);
   1914 
   1915             pit_sharp = gain_pit;
   1916 
   1917             if (pit_sharp > SHARPMAX)
   1918             {
   1919                 pit_sharp = SHARPMAX;
   1920             }
   1921 
   1922             if (mode == MR102)
   1923             {
   1924                 if (st->old_T0 > (L_SUBFR + 5))
   1925                 {
   1926                     if (pit_sharp < 0)
   1927                     {
   1928                         pit_sharp = ~((~pit_sharp) >> 2);
   1929                     }
   1930                     else
   1931                     {
   1932                         pit_sharp = pit_sharp >> 2;
   1933                     }
   1934                 }
   1935             }
   1936         }
   1937         else
   1938         {
   1939             /* read and decode pitch gain */
   1940             index = *parm++;                 /* index of gain(s) */
   1941 
   1942             if (mode == MR795)
   1943             {
   1944                 /* decode pitch gain */
   1945                 if (bfi != 0)
   1946                 {
   1947                     ec_gain_pitch(
   1948                         &(st->ec_gain_p_st),
   1949                         st->state,
   1950                         &gain_pit,
   1951                         pOverflow);
   1952                 }
   1953                 else
   1954                 {
   1955                     gain_pit = d_gain_pitch(mode, index);
   1956                 }
   1957                 ec_gain_pitch_update(
   1958                     &(st->ec_gain_p_st),
   1959                     bfi,
   1960                     st->prev_bf,
   1961                     &gain_pit,
   1962                     pOverflow);
   1963 
   1964                 /* read and decode code gain */
   1965                 index = *parm++;
   1966 
   1967                 if (bfi == 0)
   1968                 {
   1969                     d_gain_code(
   1970                         &(st->pred_state),
   1971                         mode,
   1972                         index,
   1973                         code,
   1974                         &gain_code,
   1975                         pOverflow);
   1976                 }
   1977                 else
   1978                 {
   1979                     ec_gain_code(
   1980                         &(st->ec_gain_c_st),
   1981                         &(st->pred_state),
   1982                         st->state,
   1983                         &gain_code,
   1984                         pOverflow);
   1985                 }
   1986 
   1987                 ec_gain_code_update(
   1988                     &(st->ec_gain_c_st),
   1989                     bfi,
   1990                     st->prev_bf,
   1991                     &gain_code,
   1992                     pOverflow);
   1993 
   1994                 pit_sharp = gain_pit;
   1995 
   1996                 if (pit_sharp > SHARPMAX)
   1997                 {
   1998                     pit_sharp = SHARPMAX;
   1999                 }
   2000             }
   2001             else
   2002             { /* MR122 */
   2003 
   2004                 if (bfi == 0)
   2005                 {
   2006                     d_gain_code(
   2007                         &(st->pred_state),
   2008                         mode,
   2009                         index,
   2010                         code,
   2011                         &gain_code,
   2012                         pOverflow);
   2013                 }
   2014                 else
   2015                 {
   2016                     ec_gain_code(
   2017                         &(st->ec_gain_c_st),
   2018                         &(st->pred_state),
   2019                         st->state,
   2020                         &gain_code,
   2021                         pOverflow);
   2022                 }
   2023 
   2024                 ec_gain_code_update(
   2025                     &(st->ec_gain_c_st),
   2026                     bfi,
   2027                     st->prev_bf,
   2028                     &gain_code,
   2029                     pOverflow);
   2030 
   2031                 pit_sharp = gain_pit;
   2032             }
   2033         }
   2034 
   2035         /* store pitch sharpening for next subframe             */
   2036         /* (for modes which use the previous pitch gain for     */
   2037         /* pitch sharpening in the search phase)                */
   2038         /* do not update sharpening in even subframes for MR475 */
   2039         if ((mode != MR475) || (evenSubfr == 0))
   2040         {
   2041             st->sharp = gain_pit;
   2042 
   2043             if (st->sharp > SHARPMAX)
   2044             {
   2045                 st->sharp = SHARPMAX;
   2046             }
   2047         }
   2048 
   2049         pit_sharp = shl(pit_sharp, 1, pOverflow);
   2050 
   2051         if (pit_sharp > 16384)
   2052         {
   2053             for (i = 0; i < L_SUBFR; i++)
   2054             {
   2055                 temp = mult(st->exc[i], pit_sharp, pOverflow);
   2056                 L_temp = L_mult(temp, gain_pit, pOverflow);
   2057 
   2058                 if (mode == MR122)
   2059                 {
   2060                     if (L_temp < 0)
   2061                     {
   2062                         L_temp = ~((~L_temp) >> 1);
   2063                     }
   2064                     else
   2065                     {
   2066                         L_temp = L_temp >> 1;
   2067                     }
   2068                 }
   2069                 *(excp + i) = pv_round(L_temp, pOverflow);
   2070             }
   2071         }
   2072 
   2073         /*-------------------------------------------------------*
   2074          * - Store list of LTP gains needed in the source        *
   2075          *   characteristic detector (SCD)                       *
   2076          *-------------------------------------------------------*/
   2077 
   2078         if (bfi == 0)
   2079         {
   2080             for (i = 0; i < 8; i++)
   2081             {
   2082                 st->ltpGainHistory[i] = st->ltpGainHistory[i+1];
   2083             }
   2084             st->ltpGainHistory[8] = gain_pit;
   2085         }
   2086 
   2087         /*-------------------------------------------------------*
   2088         * - Limit gain_pit if in background noise and BFI       *
   2089         *   for MR475, MR515, MR59                              *
   2090         *-------------------------------------------------------*/
   2091 
   2092 
   2093         if ((st->prev_bf != 0 || bfi != 0) && st->inBackgroundNoise != 0 &&
   2094                 ((mode == MR475) || (mode == MR515) || (mode == MR59)))
   2095         {
   2096 
   2097             if (gain_pit > 12288)    /* if (gain_pit > 0.75) in Q14*/
   2098             {
   2099                 gain_pit = ((gain_pit - 12288) >> 1) + 12288;
   2100                 /* gain_pit = (gain_pit-0.75)/2.0 + 0.75; */
   2101             }
   2102 
   2103             if (gain_pit > 14745)    /* if (gain_pit > 0.90) in Q14*/
   2104             {
   2105                 gain_pit = 14745;
   2106             }
   2107         }
   2108 
   2109         /*-------------------------------------------------------*
   2110          *  Calculate CB mixed gain                              *
   2111          *-------------------------------------------------------*/
   2112         Int_lsf(
   2113             prev_lsf,
   2114             st->lsfState.past_lsf_q,
   2115             i_subfr,
   2116             lsf_i,
   2117             pOverflow);
   2118 
   2119         gain_code_mix =
   2120             Cb_gain_average(
   2121                 &(st->Cb_gain_averState),
   2122                 mode,
   2123                 gain_code,
   2124                 lsf_i,
   2125                 st->lsp_avg_st.lsp_meanSave,
   2126                 bfi,
   2127                 st->prev_bf,
   2128                 pdfi,
   2129                 st->prev_pdf,
   2130                 st->inBackgroundNoise,
   2131                 st->voicedHangover,
   2132                 pOverflow);
   2133 
   2134         /* make sure that MR74, MR795, MR122 have original code_gain*/
   2135         if ((mode > MR67) && (mode != MR102))
   2136             /* MR74, MR795, MR122 */
   2137         {
   2138             gain_code_mix = gain_code;
   2139         }
   2140 
   2141         /*-------------------------------------------------------*
   2142          * - Find the total excitation.                          *
   2143          * - Find synthesis speech corresponding to st->exc[].   *
   2144          *-------------------------------------------------------*/
   2145         if (mode <= MR102) /* MR475, MR515, MR59, MR67, MR74, MR795, MR102*/
   2146         {
   2147             pitch_fac = gain_pit;
   2148             tmp_shift = 1;
   2149         }
   2150         else       /* MR122 */
   2151         {
   2152             if (gain_pit < 0)
   2153             {
   2154                 pitch_fac = ~((~gain_pit) >> 1);
   2155             }
   2156             else
   2157             {
   2158                 pitch_fac = gain_pit >> 1;
   2159             }
   2160             tmp_shift = 2;
   2161         }
   2162 
   2163         /* copy unscaled LTP excitation to exc_enhanced (used in phase
   2164          * dispersion below) and compute total excitation for LTP feedback
   2165          */
   2166         for (i = 0; i < L_SUBFR; i++)
   2167         {
   2168             exc_enhanced[i] = st->exc[i];
   2169 
   2170             /* st->exc[i] = gain_pit*st->exc[i] + gain_code*code[i]; */
   2171             L_temp = L_mult(st->exc[i], pitch_fac, pOverflow);
   2172             /* 12.2: Q0 * Q13 */
   2173             /*  7.4: Q0 * Q14 */
   2174             L_temp = L_mac(L_temp, code[i], gain_code, pOverflow);
   2175             /* 12.2: Q12 * Q1 */
   2176             /*  7.4: Q13 * Q1 */
   2177             L_temp = L_shl(L_temp, tmp_shift, pOverflow);     /* Q16 */
   2178             st->exc[i] = pv_round(L_temp, pOverflow);
   2179         }
   2180 
   2181         /*-------------------------------------------------------*
   2182          * - Adaptive phase dispersion                           *
   2183          *-------------------------------------------------------*/
   2184         ph_disp_release(&(st->ph_disp_st)); /* free phase dispersion adaption */
   2185 
   2186 
   2187         if (((mode == MR475) || (mode == MR515) || (mode == MR59)) &&
   2188                 (st->voicedHangover > 3) && (st->inBackgroundNoise != 0) &&
   2189                 (bfi != 0))
   2190         {
   2191             ph_disp_lock(&(st->ph_disp_st)); /* Always Use full Phase Disp. */
   2192         }                                 /* if error in bg noise       */
   2193 
   2194         /* apply phase dispersion to innovation (if enabled) and
   2195            compute total excitation for synthesis part           */
   2196         ph_disp(
   2197             &(st->ph_disp_st),
   2198             mode,
   2199             exc_enhanced,
   2200             gain_code_mix,
   2201             gain_pit,
   2202             code,
   2203             pitch_fac,
   2204             tmp_shift,
   2205             pOverflow);
   2206 
   2207         /*-------------------------------------------------------*
   2208          * - The Excitation control module are active during BFI.*
   2209          * - Conceal drops in signal energy if in bg noise.      *
   2210          *-------------------------------------------------------*/
   2211         L_temp = 0;
   2212         for (i = 0; i < L_SUBFR; i++)
   2213         {
   2214             L_temp = L_mac(L_temp, *(exc_enhanced + i), *(exc_enhanced + i), pOverflow);
   2215         }
   2216 
   2217         /* excEnergy = sqrt(L_temp) in Q0 */
   2218         if (L_temp < 0)
   2219         {
   2220             L_temp = ~((~L_temp) >> 1);
   2221         }
   2222         else
   2223         {
   2224             L_temp = L_temp >> 1;
   2225         }
   2226 
   2227         L_temp = sqrt_l_exp(L_temp, &temp, pOverflow);
   2228         /* To cope with 16-bit and scaling in ex_ctrl() */
   2229         L_temp = L_shr(L_temp, (Word16)((temp >> 1) + 15), pOverflow);
   2230         if (L_temp < 0)
   2231         {
   2232             excEnergy = (Word16)(~((~L_temp) >> 2));
   2233         }
   2234         else
   2235         {
   2236             excEnergy = (Word16)(L_temp >> 2);
   2237         }
   2238 
   2239         if (((mode == MR475) || (mode == MR515) || (mode == MR59))  &&
   2240                 (st->voicedHangover > 5) && (st->inBackgroundNoise != 0) &&
   2241                 (st->state < 4) &&
   2242                 ((pdfi != 0 && st->prev_pdf != 0) || bfi != 0 || st->prev_bf != 0))
   2243         {
   2244             carefulFlag = 0;
   2245 
   2246             if (pdfi != 0 && bfi == 0)
   2247             {
   2248                 carefulFlag = 1;
   2249             }
   2250 
   2251             Ex_ctrl(exc_enhanced,
   2252                     excEnergy,
   2253                     st->excEnergyHist,
   2254                     st->voicedHangover,
   2255                     st->prev_bf,
   2256                     carefulFlag, pOverflow);
   2257         }
   2258 
   2259         if (!((st->inBackgroundNoise != 0) && (bfi != 0 || st->prev_bf != 0) &&
   2260                 (st->state < 4)))
   2261         {
   2262             /* Update energy history for all modes */
   2263             for (i = 0; i < 8; i++)
   2264             {
   2265                 st->excEnergyHist[i] = st->excEnergyHist[i+1];
   2266             }
   2267             st->excEnergyHist[8] = excEnergy;
   2268         }
   2269         /*-------------------------------------------------------*
   2270          * Excitation control module end.                        *
   2271          *-------------------------------------------------------*/
   2272         if (pit_sharp > 16384)
   2273         {
   2274             for (i = 0; i < L_SUBFR; i++)
   2275             {
   2276                 *(excp + i) = add(*(excp + i), *(exc_enhanced + i), pOverflow);
   2277 
   2278             }
   2279             agc2(exc_enhanced, excp, L_SUBFR, pOverflow);
   2280             *pOverflow = 0;
   2281             Syn_filt(Az, excp, &synth[i_subfr], L_SUBFR,
   2282                      st->mem_syn, 0);
   2283         }
   2284         else
   2285         {
   2286             *pOverflow = 0;
   2287             Syn_filt(Az, exc_enhanced, &synth[i_subfr], L_SUBFR,
   2288                      st->mem_syn, 0);
   2289         }
   2290 
   2291         if (*pOverflow != 0)    /* Test for overflow */
   2292         {
   2293             for (i = PIT_MAX + L_INTERPOL + L_SUBFR - 1; i >= 0; i--)
   2294             {
   2295                 if (st->old_exc[i] < 0)
   2296                 {
   2297                     st->old_exc[i] = ~((~st->old_exc[i]) >> 2);
   2298                 }
   2299                 else
   2300                 {
   2301                     st->old_exc[i] = st->old_exc[i] >> 2;
   2302                 }
   2303 
   2304             }
   2305 
   2306             for (i = L_SUBFR - 1; i >= 0; i--)
   2307             {
   2308                 if (*(exc_enhanced + i) < 0)
   2309                 {
   2310                     *(exc_enhanced + i) = ~((~(*(exc_enhanced + i))) >> 2);
   2311                 }
   2312                 else
   2313                 {
   2314                     *(exc_enhanced + i) = *(exc_enhanced + i) >> 2;
   2315                 }
   2316             }
   2317             Syn_filt(Az, exc_enhanced, &synth[i_subfr], L_SUBFR, st->mem_syn, 1);
   2318         }
   2319         else
   2320         {
   2321             Copy(&synth[i_subfr+L_SUBFR-M], st->mem_syn, M);
   2322         }
   2323 
   2324         /*--------------------------------------------------*
   2325          * Update signal for next frame.                    *
   2326          * -> shift to the left by L_SUBFR  st->exc[]       *
   2327          *--------------------------------------------------*/
   2328 
   2329         Copy(&st->old_exc[L_SUBFR], &st->old_exc[0], PIT_MAX + L_INTERPOL);
   2330 
   2331         /* interpolated LPC parameters for next subframe */
   2332         Az += MP1;
   2333 
   2334         /* store T0 for next subframe */
   2335         st->old_T0 = T0;
   2336     }
   2337 
   2338     /*-------------------------------------------------------*
   2339      * Call the Source Characteristic Detector which updates *
   2340      * st->inBackgroundNoise and st->voicedHangover.         *
   2341      *-------------------------------------------------------*/
   2342 
   2343     st->inBackgroundNoise =
   2344         Bgn_scd(
   2345             &(st->background_state),
   2346             &(st->ltpGainHistory[0]),
   2347             &(synth[0]),
   2348             &(st->voicedHangover),
   2349             pOverflow);
   2350 
   2351     dtx_dec_activity_update(
   2352         &(st->dtxDecoderState),
   2353         st->lsfState.past_lsf_q,
   2354         synth,
   2355         pOverflow);
   2356 
   2357     /* store bfi for next subframe */
   2358     st->prev_bf = bfi;
   2359     st->prev_pdf = pdfi;
   2360 
   2361     /*--------------------------------------------------*
   2362      * Calculate the LSF averages on the eight          *
   2363      * previous frames                                  *
   2364      *--------------------------------------------------*/
   2365     lsp_avg(
   2366         &(st->lsp_avg_st),
   2367         st->lsfState.past_lsf_q,
   2368         pOverflow);
   2369 
   2370 the_end:
   2371     st->dtxDecoderState.dtxGlobalState = newDTXState;
   2372 
   2373 //    return(0);
   2374 }
   2375