Initialize Tizen 2.3
[external/opencore-amr.git] / opencore / codecs_v2 / audio / gsm_amr / amr_wb / dec / src / dtx_decoder_amr_wb.cpp
1 /* ------------------------------------------------------------------
2  * Copyright (C) 1998-2009 PacketVideo
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13  * express or implied.
14  * See the License for the specific language governing permissions
15  * and limitations under the License.
16  * -------------------------------------------------------------------
17  */
18 /****************************************************************************************
19 Portions of this file are derived from the following 3GPP standard:
20
21     3GPP TS 26.173
22     ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
23     Available from http://www.3gpp.org
24
25 (C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
26 Permission to distribute, modify and use this file under the standard license
27 terms listed above has been obtained from the copyright holder.
28 ****************************************************************************************/
29 /*
30 ------------------------------------------------------------------------------
31
32
33
34  Filename: dtx_decoder_amr_wb.cpp
35
36 ------------------------------------------------------------------------------
37  INPUT AND OUTPUT DEFINITIONS
38
39
40 ------------------------------------------------------------------------------
41  FUNCTION DESCRIPTION
42
43     DTX functions
44
45 ------------------------------------------------------------------------------
46  REQUIREMENTS
47
48
49 ------------------------------------------------------------------------------
50  REFERENCES
51
52 ------------------------------------------------------------------------------
53  PSEUDO-CODE
54
55 ------------------------------------------------------------------------------
56 */
57
58
59 /*----------------------------------------------------------------------------
60 ; INCLUDES
61 ----------------------------------------------------------------------------*/
62
63 #include "pv_amr_wb_type_defs.h"
64 #include "pvamrwbdecoder_basic_op.h"
65 #include "pvamrwb_math_op.h"
66 #include "pvamrwbdecoder_cnst.h"
67 #include "pvamrwbdecoder_acelp.h"  /* prototype of functions    */
68 #include "get_amr_wb_bits.h"
69 #include "dtx.h"
70
71 /*----------------------------------------------------------------------------
72 ; MACROS
73 ; Define module specific macros here
74 ----------------------------------------------------------------------------*/
75
76
77 /*----------------------------------------------------------------------------
78 ; DEFINES
79 ; Include all pre-processor statements here. Include conditional
80 ; compile variables also.
81 ----------------------------------------------------------------------------*/
82
83 /*----------------------------------------------------------------------------
84 ; LOCAL FUNCTION DEFINITIONS
85 ; Function Prototype declaration
86 ----------------------------------------------------------------------------*/
87
88 /*----------------------------------------------------------------------------
89 ; LOCAL STORE/BUFFER/POINTER DEFINITIONS
90 ; Variable declaration - defined here and used outside this module
91 ----------------------------------------------------------------------------*/
92
93 /*----------------------------------------------------------------------------
94 ; EXTERNAL FUNCTION REFERENCES
95 ; Declare functions defined elsewhere and referenced in this module
96 ----------------------------------------------------------------------------*/
97
98 /*----------------------------------------------------------------------------
99 ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
100 ; Declare variables used in this module but defined elsewhere
101 ----------------------------------------------------------------------------*/
102
103 /*----------------------------------------------------------------------------
104 ; FUNCTION CODE
105 ----------------------------------------------------------------------------*/
106 /*
107  * Function    : dtx_dec_amr_wb_reset
108  */
109 int16 dtx_dec_amr_wb_reset(dtx_decState * st, const int16 isf_init[])
110 {
111     int16 i;
112
113
114     if (st == (dtx_decState *) NULL)
115     {
116         /* dtx_dec_amr_wb_reset invalid parameter */
117         return (-1);
118     }
119     st->since_last_sid = 0;
120     st->true_sid_period_inv = (1 << 13);      /* 0.25 in Q15 */
121
122     st->log_en = 3500;
123     st->old_log_en = 3500;
124     /* low level noise for better performance in  DTX handover cases */
125
126     st->cng_seed = RANDOM_INITSEED;
127
128     st->hist_ptr = 0;
129
130     /* Init isf_hist[] and decoder log frame energy */
131     pv_memcpy((void *)st->isf, (void *)isf_init, M*sizeof(*isf_init));
132
133     pv_memcpy((void *)st->isf_old, (void *)isf_init, M*sizeof(*isf_init));
134
135     for (i = 0; i < DTX_HIST_SIZE; i++)
136     {
137         pv_memcpy((void *)&st->isf_hist[i * M], (void *)isf_init, M*sizeof(*isf_init));
138         st->log_en_hist[i] = st->log_en;
139     }
140
141     st->dtxHangoverCount = DTX_HANG_CONST;
142     st->decAnaElapsedCount = 32767;
143
144     st->sid_frame = 0;
145     st->valid_data = 0;
146     st->dtxHangoverAdded = 0;
147
148     st->dtxGlobalState = SPEECH;
149     st->data_updated = 0;
150
151     st->dither_seed = RANDOM_INITSEED;
152     st->CN_dith = 0;
153
154     return 0;
155 }
156
157
158 /*
159      Table of new SPD synthesis states
160
161                            |     previous SPD_synthesis_state
162      Incoming              |
163      frame_type            | SPEECH       | DTX           | DTX_MUTE
164      ---------------------------------------------------------------
165      RX_SPEECH_GOOD ,      |              |               |
166      RX_SPEECH_PR_DEGRADED | SPEECH       | SPEECH        | SPEECH
167      ----------------------------------------------------------------
168      RX_SPEECH_BAD,        | SPEECH       | DTX           | DTX_MUTE
169      ----------------------------------------------------------------
170      RX_SID_FIRST,         | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
171      ----------------------------------------------------------------
172      RX_SID_UPDATE,        | DTX          | DTX           | DTX
173      ----------------------------------------------------------------
174      RX_SID_BAD,           | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
175      ----------------------------------------------------------------
176      RX_NO_DATA,           | SPEECH       | DTX/(DTX_MUTE)| DTX_MUTE
177      RX_SPARE              |(class2 garb.)|               |
178      ----------------------------------------------------------------
179 */
180
181 /*----------------------------------------------------------------------------
182 ; FUNCTION CODE
183 ----------------------------------------------------------------------------*/
184
185 /*
186  * Function    : dtx_dec_amr_wb
187  */
188 int16 dtx_dec_amr_wb(
189     dtx_decState * st,                    /* i/o : State struct         */
190     int16 * exc2,                        /* o   : CN excitation        */
191     int16 new_state,                     /* i   : New DTX state        */
192     int16 isf[],                         /* o   : CN ISF vector        */
193     int16 ** prms
194 )
195 {
196     int16 log_en_index;
197     int16 ind[7];
198     int16 i, j;
199     int16 int_fac;
200     int16 gain;
201
202     int32 L_isf[M], L_log_en_int, level32, ener32;
203     int16 ptr;
204     int16 tmp_int_length;
205     int16 tmp, exp, exp0, log_en_int_e, log_en_int_m, level;
206
207     /* This function is called if synthesis state is not SPEECH the globally passed  inputs to this function
208      * are st->sid_frame st->valid_data st->dtxHangoverAdded new_state  (SPEECH, DTX, DTX_MUTE) */
209
210     if ((st->dtxHangoverAdded != 0) &&
211             (st->sid_frame != 0))
212     {
213         /* sid_first after dtx hangover period */
214         /* or sid_upd after dtxhangover        */
215
216         /* consider  twice the last frame */
217         ptr = st->hist_ptr + 1;
218
219         if (ptr == DTX_HIST_SIZE)
220             ptr = 0;
221
222         pv_memcpy((void *)&st->isf_hist[ptr * M], (void *)&st->isf_hist[st->hist_ptr * M], M*sizeof(*st->isf_hist));
223
224         st->log_en_hist[ptr] = st->log_en_hist[st->hist_ptr];
225
226         /* compute mean log energy and isf from decoded signal (SID_FIRST) */
227         st->log_en = 0;
228         for (i = 0; i < M; i++)
229         {
230             L_isf[i] = 0;
231         }
232
233         /* average energy and isf */
234         for (i = 0; i < DTX_HIST_SIZE; i++)
235         {
236             /* Division by DTX_HIST_SIZE = 8 has been done in dtx_buffer log_en is in Q10 */
237             st->log_en = add_int16(st->log_en, st->log_en_hist[i]);
238
239             for (j = 0; j < M; j++)
240             {
241                 L_isf[j] = add_int32(L_isf[j], (int32)(st->isf_hist[i * M + j]));
242             }
243         }
244
245         /* st->log_en in Q9 */
246         st->log_en >>=  1;
247
248         /* Add 2 in Q9, in order to have only positive values for Pow2 */
249         /* this value is subtracted back after Pow2 function */
250         st->log_en += 1024;
251
252         if (st->log_en < 0)
253             st->log_en = 0;
254
255         for (j = 0; j < M; j++)
256         {
257             st->isf[j] = (int16)(L_isf[j] >> 3);  /* divide by 8 */
258         }
259
260     }
261
262     if (st->sid_frame != 0)
263     {
264         /* Set old SID parameters, always shift */
265         /* even if there is no new valid_data   */
266
267         pv_memcpy((void *)st->isf_old, (void *)st->isf, M*sizeof(*st->isf));
268
269         st->old_log_en = st->log_en;
270
271         if (st->valid_data != 0)           /* new data available (no CRC) */
272         {
273             /* st->true_sid_period_inv = 1.0f/st->since_last_sid; */
274             /* Compute interpolation factor, since the division only works * for values of since_last_sid <
275              * 32 we have to limit the      * interpolation to 32 frames                                  */
276             tmp_int_length = st->since_last_sid;
277
278
279             if (tmp_int_length > 32)
280             {
281                 tmp_int_length = 32;
282             }
283
284             if (tmp_int_length >= 2)
285             {
286                 st->true_sid_period_inv = div_16by16(1 << 10, shl_int16(tmp_int_length, 10));
287             }
288             else
289             {
290                 st->true_sid_period_inv = 1 << 14;      /* 0.5 it Q15 */
291             }
292
293             ind[0] = Serial_parm(6, prms);
294             ind[1] = Serial_parm(6, prms);
295             ind[2] = Serial_parm(6, prms);
296             ind[3] = Serial_parm(5, prms);
297             ind[4] = Serial_parm(5, prms);
298
299             Disf_ns(ind, st->isf);
300
301             log_en_index = Serial_parm(6, prms);
302
303             /* read background noise stationarity information */
304             st->CN_dith = Serial_parm_1bit(prms);
305
306             /* st->log_en = (float)log_en_index / 2.625 - 2.0;  */
307             /* log2(E) in Q9 (log2(E) lies in between -2:22) */
308             st->log_en = shl_int16(log_en_index, 15 - 6);
309
310             /* Divide by 2.625  */
311             st->log_en = mult_int16(st->log_en, 12483);
312             /* Subtract 2 in Q9 is done later, after Pow2 function  */
313
314             /* no interpolation at startup after coder reset        */
315             /* or when SID_UPD has been received right after SPEECH */
316
317             if ((st->data_updated == 0) || (st->dtxGlobalState == SPEECH))
318             {
319                 pv_memcpy((void *)st->isf_old, (void *)st->isf, M*sizeof(*st->isf));
320
321                 st->old_log_en = st->log_en;
322             }
323         }                                  /* endif valid_data */
324     }                                      /* endif sid_frame */
325
326
327     if ((st->sid_frame != 0) && (st->valid_data != 0))
328     {
329         st->since_last_sid = 0;
330     }
331     /* Interpolate SID info */
332     int_fac = shl_int16(st->since_last_sid, 10); /* Q10 */
333     int_fac = mult_int16(int_fac, st->true_sid_period_inv);   /* Q10 * Q15 -> Q10 */
334
335     /* Maximize to 1.0 in Q10 */
336
337     if (int_fac > 1024)
338     {
339         int_fac = 1024;
340     }
341     int_fac = shl_int16(int_fac, 4);             /* Q10 -> Q14 */
342
343     L_log_en_int = mul_16by16_to_int32(int_fac, st->log_en); /* Q14 * Q9 -> Q24 */
344
345     for (i = 0; i < M; i++)
346     {
347         isf[i] = mult_int16(int_fac, st->isf[i]);/* Q14 * Q15 -> Q14 */
348     }
349
350     int_fac = 16384 - int_fac;         /* 1-k in Q14 */
351
352     /* ( Q14 * Q9 -> Q24 ) + Q24 -> Q24 */
353     L_log_en_int = mac_16by16_to_int32(L_log_en_int, int_fac, st->old_log_en);
354
355     for (i = 0; i < M; i++)
356     {
357         /* Q14 + (Q14 * Q15 -> Q14) -> Q14 */
358         isf[i] = add_int16(isf[i], mult_int16(int_fac, st->isf_old[i]));
359         isf[i] = shl_int16(isf[i], 1);           /* Q14 -> Q15 */
360     }
361
362     /* If background noise is non-stationary, insert comfort noise dithering */
363     if (st->CN_dith != 0)
364     {
365         CN_dithering(isf, &L_log_en_int, &st->dither_seed);
366     }
367     /* L_log_en_int corresponds to log2(E)+2 in Q24, i.e log2(gain)+1 in Q25 */
368     /* Q25 -> Q16 */
369     L_log_en_int >>= 9;
370
371     /* Find integer part  */
372     log_en_int_e = extract_h(L_log_en_int);
373
374     /* Find fractional part */
375     log_en_int_m = (int16)(sub_int32(L_log_en_int, L_deposit_h(log_en_int_e)) >> 1);
376
377     /* Subtract 2 from L_log_en_int in Q9, i.e divide the gain by 2 (energy by 4) */
378     /* Add 16 in order to have the result of pow2 in Q16 */
379     log_en_int_e += 15;
380
381     /* level = (float)( pow( 2.0f, log_en ) );  */
382     level32 = power_of_2(log_en_int_e, log_en_int_m); /* Q16 */
383
384     exp0 = normalize_amr_wb(level32);
385     level32 <<= exp0;        /* level in Q31 */
386     exp0 = 15 - exp0;
387     level = (int16)(level32 >> 16);          /* level in Q15 */
388
389     /* generate white noise vector */
390     for (i = 0; i < L_FRAME; i++)
391     {
392         exc2[i] = noise_gen_amrwb(&(st->cng_seed)) >> 4;
393     }
394
395     /* gain = level / sqrt(ener) * sqrt(L_FRAME) */
396
397     /* energy of generated excitation */
398     ener32 = Dot_product12(exc2, exc2, L_FRAME, &exp);
399
400     one_ov_sqrt_norm(&ener32, &exp);
401
402     gain = extract_h(ener32);
403
404     gain = mult_int16(level, gain);              /* gain in Q15 */
405
406     exp += exp0;
407
408     /* Multiply by sqrt(L_FRAME)=16, i.e. shift left by 4 */
409     exp += 4;
410
411     for (i = 0; i < L_FRAME; i++)
412     {
413         tmp = mult_int16(exc2[i], gain);         /* Q0 * Q15 */
414         exc2[i] = shl_int16(tmp, exp);
415     }
416
417
418     if (new_state == DTX_MUTE)
419     {
420         /* mute comfort noise as it has been quite a long time since last SID update  was performed                            */
421
422         tmp_int_length = st->since_last_sid;
423
424         if (tmp_int_length > 32)
425         {
426             tmp_int_length = 32;
427         }
428
429         st->true_sid_period_inv = div_16by16(1 << 10, shl_int16(tmp_int_length, 10));
430
431         st->since_last_sid = 0;
432         st->old_log_en = st->log_en;
433         /* subtract 1/8 in Q9 (energy), i.e -3/8 dB */
434         st->log_en -= 64;
435     }
436     /* reset interpolation length timer if data has been updated.        */
437
438     if ((st->sid_frame != 0) &&
439             ((st->valid_data != 0) ||
440              ((st->valid_data == 0) && (st->dtxHangoverAdded) != 0)))
441     {
442         st->since_last_sid = 0;
443         st->data_updated = 1;
444     }
445     return 0;
446 }
447
448
449 /*----------------------------------------------------------------------------
450 ; FUNCTION CODE
451 ----------------------------------------------------------------------------*/
452
453 void dtx_dec_amr_wb_activity_update(
454     dtx_decState * st,
455     int16 isf[],
456     int16 exc[])
457 {
458     int16 i;
459
460     int32 L_frame_en;
461     int16 log_en_e, log_en_m, log_en;
462
463
464     st->hist_ptr++;
465
466     if (st->hist_ptr == DTX_HIST_SIZE)
467     {
468         st->hist_ptr = 0;
469     }
470     pv_memcpy((void *)&st->isf_hist[st->hist_ptr * M], (void *)isf, M*sizeof(*isf));
471
472
473     /* compute log energy based on excitation frame energy in Q0 */
474     L_frame_en = 0;
475     for (i = 0; i < L_FRAME; i++)
476     {
477         L_frame_en = mac_16by16_to_int32(L_frame_en, exc[i], exc[i]);
478     }
479     L_frame_en >>= 1;
480
481     /* log_en = (float)log10(L_frame_en/(float)L_FRAME)/(float)log10(2.0f); */
482     amrwb_log_2(L_frame_en, &log_en_e, &log_en_m);
483
484     /* convert exponent and mantissa to int16 Q7. Q7 is used to simplify averaging in dtx_enc */
485     log_en = shl_int16(log_en_e, 7);             /* Q7 */
486     log_en += log_en_m >> 8;
487
488     /* Divide by L_FRAME = 256, i.e subtract 8 in Q7 = 1024 */
489     log_en -= 1024;
490
491     /* insert into log energy buffer */
492     st->log_en_hist[st->hist_ptr] = log_en;
493
494     return;
495 }
496
497
498 /*
499      Table of new SPD synthesis states
500
501                            |     previous SPD_synthesis_state
502      Incoming              |
503      frame_type            | SPEECH       | DTX           | DTX_MUTE
504      ---------------------------------------------------------------
505      RX_SPEECH_GOOD ,      |              |               |
506      RX_SPEECH_PR_DEGRADED | SPEECH       | SPEECH        | SPEECH
507      ----------------------------------------------------------------
508      RX_SPEECH_BAD,        | SPEECH       | DTX           | DTX_MUTE
509      ----------------------------------------------------------------
510      RX_SID_FIRST,         | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
511      ----------------------------------------------------------------
512      RX_SID_UPDATE,        | DTX          | DTX           | DTX
513      ----------------------------------------------------------------
514      RX_SID_BAD,           | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
515      ----------------------------------------------------------------
516      RX_NO_DATA,           | SPEECH       | DTX/(DTX_MUTE)| DTX_MUTE
517      RX_SPARE              |(class2 garb.)|               |
518      ----------------------------------------------------------------
519 */
520
521
522 /*----------------------------------------------------------------------------
523 ; FUNCTION CODE
524 ----------------------------------------------------------------------------*/
525
526 int16 rx_amr_wb_dtx_handler(
527     dtx_decState * st,                    /* i/o : State struct     */
528     int16 frame_type                     /* i   : Frame type       */
529 )
530 {
531     int16 newState;
532     int16 encState;
533
534     /* DTX if SID frame or previously in DTX{_MUTE} and (NO_RX OR BAD_SPEECH) */
535
536
537
538     if ((frame_type == RX_SID_FIRST)  ||
539             (frame_type == RX_SID_UPDATE) ||
540             (frame_type == RX_SID_BAD)    ||
541             (((st->dtxGlobalState == DTX) ||
542               (st->dtxGlobalState == DTX_MUTE)) &&
543              ((frame_type == RX_NO_DATA)    ||
544               (frame_type == RX_SPEECH_BAD) ||
545               (frame_type == RX_SPEECH_LOST))))
546     {
547         newState = DTX;
548
549         /* stay in mute for these input types */
550
551         if ((st->dtxGlobalState == DTX_MUTE) &&
552                 ((frame_type == RX_SID_BAD) ||
553                  (frame_type == RX_SID_FIRST) ||
554                  (frame_type == RX_SPEECH_LOST) ||
555                  (frame_type == RX_NO_DATA)))
556         {
557             newState = DTX_MUTE;
558         }
559         /* evaluate if noise parameters are too old                     */
560         /* since_last_sid is reset when CN parameters have been updated */
561         st->since_last_sid = add_int16(st->since_last_sid, 1);
562
563         /* no update of sid parameters in DTX for a long while */
564
565         if (st->since_last_sid > DTX_MAX_EMPTY_THRESH)
566         {
567             newState = DTX_MUTE;
568         }
569     }
570     else
571     {
572         newState = SPEECH;
573         st->since_last_sid = 0;
574     }
575
576     /* reset the decAnaElapsed Counter when receiving CNI data the first time, to robustify counter missmatch
577      * after handover this might delay the bwd CNI analysis in the new decoder slightly. */
578
579     if ((st->data_updated == 0) &&
580             (frame_type == RX_SID_UPDATE))
581     {
582         st->decAnaElapsedCount = 0;
583     }
584     /* update the SPE-SPD DTX hangover synchronization */
585     /* to know when SPE has added dtx hangover         */
586     st->decAnaElapsedCount = add_int16(st->decAnaElapsedCount, 1);
587     st->dtxHangoverAdded = 0;
588
589
590     if ((frame_type == RX_SID_FIRST) ||
591             (frame_type == RX_SID_UPDATE) ||
592             (frame_type == RX_SID_BAD) ||
593             (frame_type == RX_NO_DATA))
594     {
595         encState = DTX;
596     }
597     else
598     {
599         encState = SPEECH;
600     }
601
602
603     if (encState == SPEECH)
604     {
605         st->dtxHangoverCount = DTX_HANG_CONST;
606     }
607     else
608     {
609
610         if (st->decAnaElapsedCount > DTX_ELAPSED_FRAMES_THRESH)
611         {
612             st->dtxHangoverAdded = 1;
613             st->decAnaElapsedCount = 0;
614             st->dtxHangoverCount = 0;
615         }
616         else if (st->dtxHangoverCount == 0)
617         {
618             st->decAnaElapsedCount = 0;
619         }
620         else
621         {
622             st->dtxHangoverCount--;
623         }
624     }
625
626     if (newState != SPEECH)
627     {
628         /* DTX or DTX_MUTE CN data is not in a first SID, first SIDs are marked as SID_BAD but will do
629          * backwards analysis if a hangover period has been added according to the state machine above */
630
631         st->sid_frame = 0;
632         st->valid_data = 0;
633
634
635         if (frame_type == RX_SID_FIRST)
636         {
637             st->sid_frame = 1;
638         }
639         else if (frame_type == RX_SID_UPDATE)
640         {
641             st->sid_frame = 1;
642             st->valid_data = 1;
643         }
644         else if (frame_type == RX_SID_BAD)
645         {
646             st->sid_frame = 1;
647             st->dtxHangoverAdded = 0;      /* use old data */
648         }
649     }
650     return newState;
651     /* newState is used by both SPEECH AND DTX synthesis routines */
652 }
653
654
655 /*----------------------------------------------------------------------------
656 ; FUNCTION CODE
657 ----------------------------------------------------------------------------*/
658
659 void aver_isf_history(
660     int16 isf_old[],
661     int16 indices[],
662     int32 isf_aver[]
663 )
664 {
665     int16 i, j, k;
666     int16 isf_tmp[2 * M];
667     int32 L_tmp;
668
669     /* Memorize in isf_tmp[][] the ISF vectors to be replaced by */
670     /* the median ISF vector prior to the averaging               */
671     for (k = 0; k < 2; k++)
672     {
673
674         if (indices[k] + 1 != 0)
675         {
676             for (i = 0; i < M; i++)
677             {
678                 isf_tmp[k * M + i] = isf_old[indices[k] * M + i];
679                 isf_old[indices[k] * M + i] = isf_old[indices[2] * M + i];
680             }
681         }
682     }
683
684     /* Perform the ISF averaging */
685     for (j = 0; j < M; j++)
686     {
687         L_tmp = 0;
688
689         for (i = 0; i < DTX_HIST_SIZE; i++)
690         {
691             L_tmp = add_int32(L_tmp, (int32)(isf_old[i * M + j]));
692         }
693         isf_aver[j] = L_tmp;
694     }
695
696     /* Retrieve from isf_tmp[][] the ISF vectors saved prior to averaging */
697     for (k = 0; k < 2; k++)
698     {
699
700         if (indices[k] + 1 != 0)
701         {
702             for (i = 0; i < M; i++)
703             {
704                 isf_old[indices[k] * M + i] = isf_tmp[k * M + i];
705             }
706         }
707     }
708
709     return;
710 }
711
712
713 /*----------------------------------------------------------------------------
714 ; FUNCTION CODE
715 ----------------------------------------------------------------------------*/
716
717 void find_frame_indices(
718     int16 isf_old_tx[],
719     int16 indices[],
720     dtx_encState * st
721 )
722 {
723     int32 L_tmp, summin, summax, summax2nd;
724     int16 i, j, tmp;
725     int16 ptr;
726
727     /* Remove the effect of the oldest frame from the column */
728     /* sum sumD[0..DTX_HIST_SIZE-1]. sumD[DTX_HIST_SIZE] is    */
729     /* not updated since it will be removed later.           */
730
731     tmp = DTX_HIST_SIZE_MIN_ONE;
732     j = -1;
733     for (i = 0; i < DTX_HIST_SIZE_MIN_ONE; i++)
734     {
735         j += tmp;
736         st->sumD[i] = sub_int32(st->sumD[i], st->D[j]);
737         tmp--;
738     }
739
740     /* Shift the column sum sumD. The element sumD[DTX_HIST_SIZE-1]    */
741     /* corresponding to the oldest frame is removed. The sum of     */
742     /* the distances between the latest isf and other isfs, */
743     /* i.e. the element sumD[0], will be computed during this call. */
744     /* Hence this element is initialized to zero.                   */
745
746     for (i = DTX_HIST_SIZE_MIN_ONE; i > 0; i--)
747     {
748         st->sumD[i] = st->sumD[i - 1];
749     }
750     st->sumD[0] = 0;
751
752     /* Remove the oldest frame from the distance matrix.           */
753     /* Note that the distance matrix is replaced by a one-         */
754     /* dimensional array to save static memory.                    */
755
756     tmp = 0;
757     for (i = 27; i >= 12; i -= tmp)
758     {
759         tmp++;
760         for (j = tmp; j > 0; j--)
761         {
762             st->D[i - j + 1] = st->D[i - j - tmp];
763         }
764     }
765
766     /* Compute the first column of the distance matrix D            */
767     /* (squared Euclidean distances from isf1[] to isf_old_tx[][]). */
768
769     ptr = st->hist_ptr;
770     for (i = 1; i < DTX_HIST_SIZE; i++)
771     {
772         /* Compute the distance between the latest isf and the other isfs. */
773         ptr--;
774
775         if (ptr < 0)
776         {
777             ptr = DTX_HIST_SIZE_MIN_ONE;
778         }
779         L_tmp = 0;
780         for (j = 0; j < M; j++)
781         {
782             tmp = sub_int16(isf_old_tx[st->hist_ptr * M + j], isf_old_tx[ptr * M + j]);
783             L_tmp = mac_16by16_to_int32(L_tmp, tmp, tmp);
784         }
785         st->D[i - 1] = L_tmp;
786
787         /* Update also the column sums. */
788         st->sumD[0] = add_int32(st->sumD[0], st->D[i - 1]);
789         st->sumD[i] = add_int32(st->sumD[i], st->D[i - 1]);
790     }
791
792     /* Find the minimum and maximum distances */
793     summax = st->sumD[0];
794     summin = st->sumD[0];
795     indices[0] = 0;
796     indices[2] = 0;
797     for (i = 1; i < DTX_HIST_SIZE; i++)
798     {
799
800         if (st->sumD[i] > summax)
801         {
802             indices[0] = i;
803             summax = st->sumD[i];
804         }
805
806         if (st->sumD[i] < summin)
807         {
808             indices[2] = i;
809             summin = st->sumD[i];
810         }
811     }
812
813     /* Find the second largest distance */
814     summax2nd = -2147483647L;
815     indices[1] = -1;
816     for (i = 0; i < DTX_HIST_SIZE; i++)
817     {
818
819         if ((st->sumD[i] > summax2nd) && (i != indices[0]))
820         {
821             indices[1] = i;
822             summax2nd = st->sumD[i];
823         }
824     }
825
826     for (i = 0; i < 3; i++)
827     {
828         indices[i] = sub_int16(st->hist_ptr, indices[i]);
829
830         if (indices[i] < 0)
831         {
832             indices[i] = add_int16(indices[i], DTX_HIST_SIZE);
833         }
834     }
835
836     /* If maximum distance/MED_THRESH is smaller than minimum distance */
837     /* then the median ISF vector replacement is not performed         */
838     tmp = normalize_amr_wb(summax);
839     summax <<= tmp;
840     summin <<= tmp;
841     L_tmp = mul_16by16_to_int32(amr_wb_round(summax), INV_MED_THRESH);
842
843     if (L_tmp <= summin)
844     {
845         indices[0] = -1;
846     }
847     /* If second largest distance/MED_THRESH is smaller than     */
848     /* minimum distance then the median ISF vector replacement is    */
849     /* not performed                                                 */
850     summax2nd = shl_int32(summax2nd, tmp);
851     L_tmp = mul_16by16_to_int32(amr_wb_round(summax2nd), INV_MED_THRESH);
852
853     if (L_tmp <= summin)
854     {
855         indices[1] = -1;
856     }
857     return;
858 }
859
860
861 /*----------------------------------------------------------------------------
862 ; FUNCTION CODE
863 ----------------------------------------------------------------------------*/
864
865 int16 dithering_control(dtx_encState * st)
866 {
867     int16 i, tmp, mean, CN_dith, gain_diff;
868     int32 ISF_diff;
869
870     /* determine how stationary the spectrum of background noise is */
871     ISF_diff = 0;
872     for (i = 0; i < 8; i++)
873     {
874         ISF_diff = add_int32(ISF_diff, st->sumD[i]);
875     }
876     if ((ISF_diff >> 26) > 0)
877     {
878         CN_dith = 1;
879     }
880     else
881     {
882         CN_dith = 0;
883     }
884
885     /* determine how stationary the energy of background noise is */
886     mean = 0;
887     for (i = 0; i < DTX_HIST_SIZE; i++)
888     {
889         mean = add_int16(mean, st->log_en_hist[i]);
890     }
891     mean >>= 3;
892     gain_diff = 0;
893     for (i = 0; i < DTX_HIST_SIZE; i++)
894     {
895         tmp = sub_int16(st->log_en_hist[i], mean);
896         tmp = tmp - (tmp < 0);
897
898         gain_diff += tmp ^(tmp >> 15);    /*  tmp ^sign(tmp)  */;
899     }
900     if (gain_diff > GAIN_THR)
901     {
902         CN_dith = 1;
903     }
904     return CN_dith;
905 }
906
907
908 /*----------------------------------------------------------------------------
909 ; FUNCTION CODE
910 ----------------------------------------------------------------------------*/
911
912 void CN_dithering(
913     int16 isf[M],
914     int32 * L_log_en_int,
915     int16 * dither_seed
916 )
917 {
918     int16 temp, temp1, i, dither_fac, rand_dith;
919     int16 rand_dith2;
920
921     /* Insert comfort noise dithering for energy parameter */
922     rand_dith = noise_gen_amrwb(dither_seed) >> 1;
923     rand_dith2 = noise_gen_amrwb(dither_seed) >> 1;
924     rand_dith += rand_dith2;
925     *L_log_en_int = add_int32(*L_log_en_int, mul_16by16_to_int32(rand_dith, GAIN_FACTOR));
926
927     if (*L_log_en_int < 0)
928     {
929         *L_log_en_int = 0;
930     }
931     /* Insert comfort noise dithering for spectral parameters (ISF-vector) */
932     dither_fac = ISF_FACTOR_LOW;
933
934     rand_dith = noise_gen_amrwb(dither_seed) >> 1;
935     rand_dith2 = noise_gen_amrwb(dither_seed) >> 1;
936     rand_dith +=  rand_dith2;
937     temp = add_int16(isf[0], mult_int16_r(rand_dith, dither_fac));
938
939     /* Make sure that isf[0] will not get negative values */
940     if (temp < ISF_GAP)
941     {
942         isf[0] = ISF_GAP;
943     }
944     else
945     {
946         isf[0] = temp;
947     }
948
949     for (i = 1; i < M - 1; i++)
950     {
951         dither_fac = add_int16(dither_fac, ISF_FACTOR_STEP);
952
953         rand_dith = noise_gen_amrwb(dither_seed) >> 1;
954         rand_dith2 = noise_gen_amrwb(dither_seed) >> 1;
955         rand_dith +=  rand_dith2;
956         temp = add_int16(isf[i], mult_int16_r(rand_dith, dither_fac));
957         temp1 = sub_int16(temp, isf[i - 1]);
958
959         /* Make sure that isf spacing remains at least ISF_DITH_GAP Hz */
960         if (temp1 < ISF_DITH_GAP)
961         {
962             isf[i] = isf[i - 1] + ISF_DITH_GAP;
963         }
964         else
965         {
966             isf[i] = temp;
967         }
968     }
969
970     /* Make sure that isf[M-2] will not get values above 16384 */
971     if (isf[M - 2] > 16384)
972     {
973         isf[M - 2] = 16384;
974     }
975     return;
976 }