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