Merged revisions 316265 via svnmerge from
[asterisk/asterisk.git] / main / dsp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * Goertzel routines are borrowed from Steve Underwood's tremendous work on the
9  * DTMF detector.
10  *
11  * See http://www.asterisk.org for more information about
12  * the Asterisk project. Please do not directly contact
13  * any of the maintainers of this project for assistance;
14  * the project provides a web site, mailing lists and IRC
15  * channels for your use.
16  *
17  * This program is free software, distributed under the terms of
18  * the GNU General Public License Version 2. See the LICENSE file
19  * at the top of the source tree.
20  */
21
22 /*! \file
23  *
24  * \brief Convenience Signal Processing routines
25  *
26  * \author Mark Spencer <markster@digium.com>
27  * \author Steve Underwood <steveu@coppice.org>
28  */
29
30 /* Some routines from tone_detect.c by Steven Underwood as published under the zapata library */
31 /*
32         tone_detect.c - General telephony tone detection, and specific
33                                         detection of DTMF.
34
35         Copyright (C) 2001  Steve Underwood <steveu@coppice.org>
36
37         Despite my general liking of the GPL, I place this code in the
38         public domain for the benefit of all mankind - even the slimy
39         ones who might try to proprietize my work and use it to my
40         detriment.
41 */
42
43 #include "asterisk.h"
44
45 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
46
47 #include <math.h>
48
49 #include "asterisk/frame.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/dsp.h"
52 #include "asterisk/ulaw.h"
53 #include "asterisk/alaw.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/options.h"
56 #include "asterisk/config.h"
57
58 /*! Number of goertzels for progress detect */
59 enum gsamp_size {
60         GSAMP_SIZE_NA = 183,                    /*!< North America - 350, 440, 480, 620, 950, 1400, 1800 Hz */
61         GSAMP_SIZE_CR = 188,                    /*!< Costa Rica, Brazil - Only care about 425 Hz */
62         GSAMP_SIZE_UK = 160                     /*!< UK disconnect goertzel feed - should trigger 400hz */
63 };
64
65 enum prog_mode {
66         PROG_MODE_NA = 0,
67         PROG_MODE_CR,
68         PROG_MODE_UK
69 };
70
71 enum freq_index { 
72         /*! For US modes { */
73         HZ_350 = 0,
74         HZ_440,
75         HZ_480,
76         HZ_620,
77         HZ_950,
78         HZ_1400,
79         HZ_1800, /*!< } */
80
81         /*! For CR/BR modes */
82         HZ_425 = 0,
83
84         /*! For UK mode */
85         HZ_350UK = 0,
86         HZ_400UK,
87         HZ_440UK
88 };
89
90 static struct progalias {
91         char *name;
92         enum prog_mode mode;
93 } aliases[] = {
94         { "us", PROG_MODE_NA },
95         { "ca", PROG_MODE_NA },
96         { "cr", PROG_MODE_CR },
97         { "br", PROG_MODE_CR },
98         { "uk", PROG_MODE_UK },
99 };
100
101 static struct progress {
102         enum gsamp_size size;
103         int freqs[7];
104 } modes[] = {
105         { GSAMP_SIZE_NA, { 350, 440, 480, 620, 950, 1400, 1800 } },     /*!< North America */
106         { GSAMP_SIZE_CR, { 425 } },                                     /*!< Costa Rica, Brazil */
107         { GSAMP_SIZE_UK, { 350, 400, 440 } },                                   /*!< UK */
108 };
109
110 /*!\brief This value is the minimum threshold, calculated by averaging all
111  * of the samples within a frame, for which a frame is determined to either
112  * be silence (below the threshold) or noise (above the threshold).  Please
113  * note that while the default threshold is an even exponent of 2, there is
114  * no requirement that it be so.  The threshold will accept any value between
115  * 0 and 32767.
116  */
117 #define DEFAULT_THRESHOLD       512
118
119 enum busy_detect {
120         BUSY_PERCENT = 10,      /*!< The percentage difference between the two last silence periods */
121         BUSY_PAT_PERCENT = 7,   /*!< The percentage difference between measured and actual pattern */
122         BUSY_THRESHOLD = 100,   /*!< Max number of ms difference between max and min times in busy */
123         BUSY_MIN = 75,          /*!< Busy must be at least 80 ms in half-cadence */
124         BUSY_MAX =3100          /*!< Busy can't be longer than 3100 ms in half-cadence */
125 };
126
127 /*! Remember last 15 units */
128 #define DSP_HISTORY             15
129
130 #define TONE_THRESH             10.0    /*!< How much louder the tone should be than channel energy */
131 #define TONE_MIN_THRESH         1e8     /*!< How much tone there should be at least to attempt */
132
133 /*! All THRESH_XXX values are in GSAMP_SIZE chunks (us = 22ms) */
134 enum gsamp_thresh {
135         THRESH_RING = 8,                /*!< Need at least 150ms ring to accept */
136         THRESH_TALK = 2,                /*!< Talk detection does not work continuously */
137         THRESH_BUSY = 4,                /*!< Need at least 80ms to accept */
138         THRESH_CONGESTION = 4,          /*!< Need at least 80ms to accept */
139         THRESH_HANGUP = 60,             /*!< Need at least 1300ms to accept hangup */
140         THRESH_RING2ANSWER = 300        /*!< Timeout from start of ring to answer (about 6600 ms) */
141 };
142
143 #define MAX_DTMF_DIGITS         128
144
145 /* Basic DTMF specs:
146  *
147  * Minimum tone on = 40ms
148  * Minimum tone off = 50ms
149  * Maximum digit rate = 10 per second
150  * Normal twist <= 8dB accepted
151  * Reverse twist <= 4dB accepted
152  * S/N >= 15dB will detect OK
153  * Attenuation <= 26dB will detect OK
154  * Frequency tolerance +- 1.5% will detect, +-3.5% will reject
155  */
156
157 #define DTMF_THRESHOLD          8.0e7
158 #define FAX_THRESHOLD           8.0e7
159 #define FAX_2ND_HARMONIC        2.0     /* 4dB */
160 #define DTMF_NORMAL_TWIST       6.3     /* 8dB */
161 #ifdef  RADIO_RELAX
162 #define DTMF_REVERSE_TWIST          (relax ? 6.5 : 2.5)     /* 4dB normal */
163 #else
164 #define DTMF_REVERSE_TWIST          (relax ? 4.0 : 2.5)     /* 4dB normal */
165 #endif
166 #define DTMF_RELATIVE_PEAK_ROW  6.3     /* 8dB */
167 #define DTMF_RELATIVE_PEAK_COL  6.3     /* 8dB */
168 #define DTMF_2ND_HARMONIC_ROW       (relax ? 1.7 : 2.5)     /* 4dB normal */
169 #define DTMF_2ND_HARMONIC_COL   63.1    /* 18dB */
170 #define DTMF_TO_TOTAL_ENERGY    42.0
171
172 #define BELL_MF_THRESHOLD       1.6e9
173 #define BELL_MF_TWIST           4.0     /* 6dB */
174 #define BELL_MF_RELATIVE_PEAK   12.6    /* 11dB */
175
176 #if defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
177 #error You cant use BUSYDETECT_TONEONLY together with BUSYDETECT_COMPARE_TONE_AND_SILENCE
178 #endif
179
180 /* The CNG signal consists of the transmission of 1100 Hz for 1/2 second,
181  * followed by a 3 second silent (2100 Hz OFF) period.
182  */
183 #define FAX_TONE_CNG_FREQ       1100
184 #define FAX_TONE_CNG_DURATION   500
185 #define FAX_TONE_CNG_DB         16
186
187 /* This signal may be sent by the Terminating FAX machine anywhere between
188  * 1.8 to 2.5 seconds AFTER answering the call.  The CED signal consists
189  * of a 2100 Hz tone that is from 2.6 to 4 seconds in duration.
190 */
191 #define FAX_TONE_CED_FREQ       2100
192 #define FAX_TONE_CED_DURATION   2600
193 #define FAX_TONE_CED_DB         16
194
195 #define DEFAULT_SAMPLE_RATE             8000
196
197 /* MF goertzel size */
198 #define MF_GSIZE                120
199
200 /* DTMF goertzel size */
201 #define DTMF_GSIZE              102
202
203 /* How many successive hits needed to consider begin of a digit */
204 #define DTMF_HITS_TO_BEGIN      2
205 /* How many successive misses needed to consider end of a digit */
206 #define DTMF_MISSES_TO_END      3
207
208 /*!
209  * \brief The default silence threshold we will use if an alternate
210  * configured value is not present or is invalid.
211  */
212 static const int DEFAULT_SILENCE_THRESHOLD = 256;
213
214 #define CONFIG_FILE_NAME "dsp.conf"
215
216 typedef struct {
217         int v2;
218         int v3;
219         int chunky;
220         int fac;
221         int samples;
222 } goertzel_state_t;
223
224 typedef struct {
225         int value;
226         int power;
227 } goertzel_result_t;
228
229 typedef struct
230 {
231         int freq;
232         int block_size;
233         int squelch;            /* Remove (squelch) tone */
234         goertzel_state_t tone;
235         float energy;           /* Accumulated energy of the current block */
236         int samples_pending;    /* Samples remain to complete the current block */
237         int mute_samples;       /* How many additional samples needs to be muted to suppress already detected tone */
238
239         int hits_required;      /* How many successive blocks with tone we are looking for */
240         float threshold;        /* Energy of the tone relative to energy from all other signals to consider a hit */
241
242         int hit_count;          /* How many successive blocks we consider tone present */
243         int last_hit;           /* Indicates if the last processed block was a hit */
244
245 } tone_detect_state_t;
246
247 typedef struct
248 {
249         goertzel_state_t row_out[4];
250         goertzel_state_t col_out[4];
251         int hits_to_begin;              /* How many successive hits needed to consider begin of a digit */
252         int misses_to_end;              /* How many successive misses needed to consider end of a digit */
253         int hits;                       /* How many successive hits we have seen already */
254         int misses;                     /* How many successive misses we have seen already */
255         int lasthit;
256         int current_hit;
257         float energy;
258         int current_sample;
259         int mute_samples;
260 } dtmf_detect_state_t;
261
262 typedef struct
263 {
264         goertzel_state_t tone_out[6];
265         int current_hit;
266         int hits[5];
267         int current_sample;
268         int mute_samples;
269 } mf_detect_state_t;
270
271 typedef struct
272 {
273         char digits[MAX_DTMF_DIGITS + 1];
274         int digitlen[MAX_DTMF_DIGITS + 1];
275         int current_digits;
276         int detected_digits;
277         int lost_digits;
278
279         union {
280                 dtmf_detect_state_t dtmf;
281                 mf_detect_state_t mf;
282         } td;
283 } digit_detect_state_t;
284
285 static const float dtmf_row[] = {
286         697.0,  770.0,  852.0,  941.0
287 };
288 static const float dtmf_col[] = {
289         1209.0, 1336.0, 1477.0, 1633.0
290 };
291 static const float mf_tones[] = {
292         700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
293 };
294 static const char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
295 static const char bell_mf_positions[] = "1247C-358A--69*---0B----#";
296 static int thresholds[THRESHOLD_MAX];
297
298 static inline void goertzel_sample(goertzel_state_t *s, short sample)
299 {
300         int v1;
301         
302         v1 = s->v2;
303         s->v2 = s->v3;
304         
305         s->v3 = (s->fac * s->v2) >> 15;
306         s->v3 = s->v3 - v1 + (sample >> s->chunky);
307         if (abs(s->v3) > 32768) {
308                 s->chunky++;
309                 s->v3 = s->v3 >> 1;
310                 s->v2 = s->v2 >> 1;
311                 v1 = v1 >> 1;
312         }
313 }
314
315 static inline void goertzel_update(goertzel_state_t *s, short *samps, int count)
316 {
317         int i;
318         
319         for (i = 0; i < count; i++) {
320                 goertzel_sample(s, samps[i]);
321         }
322 }
323
324
325 static inline float goertzel_result(goertzel_state_t *s)
326 {
327         goertzel_result_t r;
328         r.value = (s->v3 * s->v3) + (s->v2 * s->v2);
329         r.value -= ((s->v2 * s->v3) >> 15) * s->fac;
330         r.power = s->chunky * 2;
331         return (float)r.value * (float)(1 << r.power);
332 }
333
334 static inline void goertzel_init(goertzel_state_t *s, float freq, int samples, unsigned int sample_rate)
335 {
336         s->v2 = s->v3 = s->chunky = 0.0;
337         s->fac = (int)(32768.0 * 2.0 * cos(2.0 * M_PI * freq / sample_rate));
338         s->samples = samples;
339 }
340
341 static inline void goertzel_reset(goertzel_state_t *s)
342 {
343         s->v2 = s->v3 = s->chunky = 0.0;
344 }
345
346 typedef struct {
347         int start;
348         int end;
349 } fragment_t;
350
351 /* Note on tone suppression (squelching). Individual detectors (DTMF/MF/generic tone)
352  * report fragmens of the frame in which detected tone resides and which needs
353  * to be "muted" in order to suppress the tone. To mark fragment for muting,
354  * detectors call mute_fragment passing fragment_t there. Multiple fragments
355  * can be marked and ast_dsp_process later will mute all of them.
356  *
357  * Note: When tone starts in the middle of a Goertzel block, it won't be properly
358  * detected in that block, only in the next. If we only mute the next block
359  * where tone is actually detected, the user will still hear beginning
360  * of the tone in preceeding block. This is why we usually want to mute some amount
361  * of samples preceeding and following the block where tone was detected.
362 */
363
364 struct ast_dsp {
365         struct ast_frame f;
366         int threshold;
367         int totalsilence;
368         int totalnoise;
369         int features;
370         int ringtimeout;
371         int busymaybe;
372         int busycount;
373         struct ast_dsp_busy_pattern busy_cadence;
374         int historicnoise[DSP_HISTORY];
375         int historicsilence[DSP_HISTORY];
376         goertzel_state_t freqs[7];
377         int freqcount;
378         int gsamps;
379         enum gsamp_size gsamp_size;
380         enum prog_mode progmode;
381         int tstate;
382         int tcount;
383         int digitmode;
384         int faxmode;
385         int dtmf_began;
386         int display_inband_dtmf_warning;
387         float genergy;
388         int mute_fragments;
389         unsigned int sample_rate;
390         fragment_t mute_data[5];
391         digit_detect_state_t digit_state;
392         tone_detect_state_t cng_tone_state;
393         tone_detect_state_t ced_tone_state;
394 };
395
396 static void mute_fragment(struct ast_dsp *dsp, fragment_t *fragment)
397 {
398         if (dsp->mute_fragments >= ARRAY_LEN(dsp->mute_data)) {
399                 ast_log(LOG_ERROR, "Too many fragments to mute. Ignoring\n");
400                 return;
401         }
402
403         dsp->mute_data[dsp->mute_fragments++] = *fragment;
404 }
405
406 static void ast_tone_detect_init(tone_detect_state_t *s, int freq, int duration, int amp, unsigned int sample_rate)
407 {
408         int duration_samples;
409         float x;
410         int periods_in_block;
411
412         s->freq = freq;
413
414         /* Desired tone duration in samples */
415         duration_samples = duration * sample_rate / 1000;
416         /* We want to allow 10% deviation of tone duration */
417         duration_samples = duration_samples * 9 / 10;
418
419         /* If we want to remove tone, it is important to have block size not
420            to exceed frame size. Otherwise by the moment tone is detected it is too late
421            to squelch it from previous frames. Block size is 20ms at the given sample rate.*/
422         s->block_size = (20 * sample_rate) / 1000;
423
424         periods_in_block = s->block_size * freq / sample_rate;
425
426         /* Make sure we will have at least 5 periods at target frequency for analisys.
427            This may make block larger than expected packet and will make squelching impossible
428            but at least we will be detecting the tone */
429         if (periods_in_block < 5)
430                 periods_in_block = 5;
431
432         /* Now calculate final block size. It will contain integer number of periods */
433         s->block_size = periods_in_block * sample_rate / freq;
434
435         /* tone_detect is currently only used to detect fax tones and we
436            do not need suqlching the fax tones */
437         s->squelch = 0;
438
439         /* Account for the first and the last block to be incomplete
440            and thus no tone will be detected in them */
441         s->hits_required = (duration_samples - (s->block_size - 1)) / s->block_size;
442
443         goertzel_init(&s->tone, freq, s->block_size, sample_rate);
444
445         s->samples_pending = s->block_size;
446         s->hit_count = 0;
447         s->last_hit = 0;
448         s->energy = 0.0;
449
450         /* We want tone energy to be amp decibels above the rest of the signal (the noise).
451            According to Parseval's theorem the energy computed in time domain equals to energy
452            computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
453            from the energy in the time domain we will get energy of the remaining signal (without the tone
454            we are detecting). We will be checking that
455                 10*log(Ew / (Et - Ew)) > amp
456            Calculate threshold so that we will be actually checking
457                 Ew > Et * threshold
458         */
459
460         x = pow(10.0, amp / 10.0);
461         s->threshold = x / (x + 1);
462
463         ast_debug(1, "Setup tone %d Hz, %d ms, block_size=%d, hits_required=%d\n", freq, duration, s->block_size, s->hits_required);
464 }
465
466 static void ast_fax_detect_init(struct ast_dsp *s)
467 {
468         ast_tone_detect_init(&s->cng_tone_state, FAX_TONE_CNG_FREQ, FAX_TONE_CNG_DURATION, FAX_TONE_CNG_DB, s->sample_rate);
469         ast_tone_detect_init(&s->ced_tone_state, FAX_TONE_CED_FREQ, FAX_TONE_CED_DURATION, FAX_TONE_CED_DB, s->sample_rate);
470 }
471
472 static void ast_dtmf_detect_init (dtmf_detect_state_t *s, unsigned int sample_rate)
473 {
474         int i;
475
476         s->lasthit = 0;
477         s->current_hit = 0;
478         for (i = 0;  i < 4;  i++) {
479                 goertzel_init(&s->row_out[i], dtmf_row[i], DTMF_GSIZE, sample_rate);
480                 goertzel_init(&s->col_out[i], dtmf_col[i], DTMF_GSIZE, sample_rate);
481                 s->energy = 0.0;
482         }
483         s->current_sample = 0;
484         s->hits = 0;
485         s->misses = 0;
486
487         s->hits_to_begin = DTMF_HITS_TO_BEGIN;
488         s->misses_to_end = DTMF_MISSES_TO_END;
489 }
490
491 static void ast_mf_detect_init (mf_detect_state_t *s, unsigned int sample_rate)
492 {
493         int i;
494         s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
495         for (i = 0;  i < 6;  i++) {
496                 goertzel_init (&s->tone_out[i], mf_tones[i], 160, sample_rate);
497         }
498         s->current_sample = 0;
499         s->current_hit = 0;
500 }
501
502 static void ast_digit_detect_init(digit_detect_state_t *s, int mf, unsigned int sample_rate)
503 {
504         s->current_digits = 0;
505         s->detected_digits = 0;
506         s->lost_digits = 0;
507         s->digits[0] = '\0';
508
509         if (mf) {
510                 ast_mf_detect_init(&s->td.mf, sample_rate);
511         } else {
512                 ast_dtmf_detect_init(&s->td.dtmf, sample_rate);
513         }
514 }
515
516 static int tone_detect(struct ast_dsp *dsp, tone_detect_state_t *s, int16_t *amp, int samples)
517 {
518         float tone_energy;
519         int i;
520         int hit = 0;
521         int limit;
522         int res = 0;
523         int16_t *ptr;
524         int start, end;
525         fragment_t mute = {0, 0};
526
527         if (s->squelch && s->mute_samples > 0) {
528                 mute.end = (s->mute_samples < samples) ? s->mute_samples : samples;
529                 s->mute_samples -= mute.end;
530         }
531
532         for (start = 0;  start < samples;  start = end) {
533                 /* Process in blocks. */
534                 limit = samples - start;
535                 if (limit > s->samples_pending) {
536                         limit = s->samples_pending;
537                 }
538                 end = start + limit;
539
540                 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
541                         /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
542                         s->energy += (int32_t) *ptr * (int32_t) *ptr;
543
544                         goertzel_sample(&s->tone, *ptr);
545                 }
546
547                 s->samples_pending -= limit;
548
549                 if (s->samples_pending) {
550                         /* Finished incomplete (last) block */
551                         break;
552                 }
553
554                 tone_energy = goertzel_result(&s->tone);
555
556                 /* Scale to make comparable */
557                 tone_energy *= 2.0;
558                 s->energy *= s->block_size;
559
560                 ast_debug(10, "tone %d, Ew=%.2E, Et=%.2E, s/n=%10.2f\n", s->freq, tone_energy, s->energy, tone_energy / (s->energy - tone_energy));
561                 hit = 0;
562                 if (tone_energy > s->energy * s->threshold) {
563                         ast_debug(10, "Hit! count=%d\n", s->hit_count);
564                         hit = 1;
565                 }
566
567                 if (s->hit_count) {
568                         s->hit_count++;
569                 }
570
571                 if (hit == s->last_hit) {
572                         if (!hit) {
573                                 /* Two successive misses. Tone ended */
574                                 s->hit_count = 0;
575                         } else if (!s->hit_count) {
576                                 s->hit_count++;
577                         }
578
579                 }
580
581                 if (s->hit_count == s->hits_required) {
582                         ast_debug(1, "%d Hz done detected\n", s->freq);
583                         res = 1;
584                 }
585
586                 s->last_hit = hit;
587
588                 /* If we had a hit in this block, include it into mute fragment */
589                 if (s->squelch && hit) {
590                         if (mute.end < start - s->block_size) {
591                                 /* There is a gap between fragments */
592                                 mute_fragment(dsp, &mute);
593                                 mute.start = (start > s->block_size) ? (start - s->block_size) : 0;
594                         }
595                         mute.end = end + s->block_size;
596                 }
597
598                 /* Reinitialise the detector for the next block */
599                 /* Reset for the next block */
600                 goertzel_reset(&s->tone);
601
602                 /* Advance to the next block */
603                 s->energy = 0.0;
604                 s->samples_pending = s->block_size;
605
606                 amp += limit;
607         }
608
609         if (s->squelch && mute.end) {
610                 if (mute.end > samples) {
611                         s->mute_samples = mute.end - samples;
612                         mute.end = samples;
613                 }
614                 mute_fragment(dsp, &mute);
615         }
616
617         return res;
618 }
619
620 static void store_digit(digit_detect_state_t *s, char digit)
621 {
622         s->detected_digits++;
623         if (s->current_digits < MAX_DTMF_DIGITS) {
624                 s->digitlen[s->current_digits] = 0;
625                 s->digits[s->current_digits++] = digit;
626                 s->digits[s->current_digits] = '\0';
627         } else {
628                 ast_log(LOG_WARNING, "Digit lost due to full buffer\n");
629                 s->lost_digits++;
630         }
631 }
632
633 static int dtmf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[], int samples, int squelch, int relax)
634 {
635         float row_energy[4];
636         float col_energy[4];
637         float famp;
638         int i;
639         int j;
640         int sample;
641         int best_row;
642         int best_col;
643         int hit;
644         int limit;
645         fragment_t mute = {0, 0};
646
647         if (squelch && s->td.dtmf.mute_samples > 0) {
648                 mute.end = (s->td.dtmf.mute_samples < samples) ? s->td.dtmf.mute_samples : samples;
649                 s->td.dtmf.mute_samples -= mute.end;
650         }
651
652         hit = 0;
653         for (sample = 0; sample < samples; sample = limit) {
654                 /* DTMF_GSIZE is optimised to meet the DTMF specs. */
655                 if ((samples - sample) >= (DTMF_GSIZE - s->td.dtmf.current_sample)) {
656                         limit = sample + (DTMF_GSIZE - s->td.dtmf.current_sample);
657                 } else {
658                         limit = samples;
659                 }
660                 /* The following unrolled loop takes only 35% (rough estimate) of the 
661                    time of a rolled loop on the machine on which it was developed */
662                 for (j = sample; j < limit; j++) {
663                         famp = amp[j];
664                         s->td.dtmf.energy += famp*famp;
665                         /* With GCC 2.95, the following unrolled code seems to take about 35%
666                            (rough estimate) as long as a neat little 0-3 loop */
667                         goertzel_sample(s->td.dtmf.row_out, amp[j]);
668                         goertzel_sample(s->td.dtmf.col_out, amp[j]);
669                         goertzel_sample(s->td.dtmf.row_out + 1, amp[j]);
670                         goertzel_sample(s->td.dtmf.col_out + 1, amp[j]);
671                         goertzel_sample(s->td.dtmf.row_out + 2, amp[j]);
672                         goertzel_sample(s->td.dtmf.col_out + 2, amp[j]);
673                         goertzel_sample(s->td.dtmf.row_out + 3, amp[j]);
674                         goertzel_sample(s->td.dtmf.col_out + 3, amp[j]);
675                 }
676                 s->td.dtmf.current_sample += (limit - sample);
677                 if (s->td.dtmf.current_sample < DTMF_GSIZE) {
678                         continue;
679                 }
680                 /* We are at the end of a DTMF detection block */
681                 /* Find the peak row and the peak column */
682                 row_energy[0] = goertzel_result (&s->td.dtmf.row_out[0]);
683                 col_energy[0] = goertzel_result (&s->td.dtmf.col_out[0]);
684
685                 for (best_row = best_col = 0, i = 1;  i < 4;  i++) {
686                         row_energy[i] = goertzel_result (&s->td.dtmf.row_out[i]);
687                         if (row_energy[i] > row_energy[best_row]) {
688                                 best_row = i;
689                         }
690                         col_energy[i] = goertzel_result (&s->td.dtmf.col_out[i]);
691                         if (col_energy[i] > col_energy[best_col]) {
692                                 best_col = i;
693                         }
694                 }
695                 hit = 0;
696                 /* Basic signal level test and the twist test */
697                 if (row_energy[best_row] >= DTMF_THRESHOLD && 
698                     col_energy[best_col] >= DTMF_THRESHOLD &&
699                     col_energy[best_col] < row_energy[best_row] * DTMF_REVERSE_TWIST &&
700                     col_energy[best_col] * DTMF_NORMAL_TWIST > row_energy[best_row]) {
701                         /* Relative peak test */
702                         for (i = 0;  i < 4;  i++) {
703                                 if ((i != best_col &&
704                                     col_energy[i] * DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
705                                     (i != best_row 
706                                      && row_energy[i] * DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
707                                         break;
708                                 }
709                         }
710                         /* ... and fraction of total energy test */
711                         if (i >= 4 &&
712                             (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY * s->td.dtmf.energy) {
713                                 /* Got a hit */
714                                 hit = dtmf_positions[(best_row << 2) + best_col];
715                         }
716                 } 
717
718                 if (s->td.dtmf.current_hit) {
719                         /* We are in the middle of a digit already */
720                         if (hit != s->td.dtmf.current_hit) {
721                                 s->td.dtmf.misses++;
722                                 if (s->td.dtmf.misses == s->td.dtmf.misses_to_end) {
723                                         /* There were enough misses to consider digit ended */
724                                         s->td.dtmf.current_hit = 0;
725                                 }
726                         } else {
727                                 s->td.dtmf.misses = 0;
728                                 /* Current hit was same as last, so increment digit duration (of last digit) */
729                                 s->digitlen[s->current_digits - 1] += DTMF_GSIZE;
730                         }
731                 }
732
733                 /* Look for a start of a new digit no matter if we are already in the middle of some
734                    digit or not. This is because hits_to_begin may be smaller than misses_to_end
735                    and we may find begin of new digit before we consider last one ended. */
736                 if (hit) {
737                         if (hit == s->td.dtmf.lasthit) {
738                                 s->td.dtmf.hits++;
739                         } else {
740                                 s->td.dtmf.hits = 1;
741                         }
742
743                         if (s->td.dtmf.hits == s->td.dtmf.hits_to_begin && hit != s->td.dtmf.current_hit) {
744                                 store_digit(s, hit);
745                                 s->td.dtmf.current_hit = hit;
746                                 s->td.dtmf.misses = 0;
747                         }
748                 } else {
749                         s->td.dtmf.hits = 0;
750                 }
751
752                 s->td.dtmf.lasthit = hit;
753
754                 /* If we had a hit in this block, include it into mute fragment */
755                 if (squelch && hit) {
756                         if (mute.end < sample - DTMF_GSIZE) {
757                                 /* There is a gap between fragments */
758                                 mute_fragment(dsp, &mute);
759                                 mute.start = (sample > DTMF_GSIZE) ? (sample - DTMF_GSIZE) : 0;
760                         }
761                         mute.end = limit + DTMF_GSIZE;
762                 }
763
764                 /* Reinitialise the detector for the next block */
765                 for (i = 0; i < 4; i++) {
766                         goertzel_reset(&s->td.dtmf.row_out[i]);
767                         goertzel_reset(&s->td.dtmf.col_out[i]);
768                 }
769                 s->td.dtmf.energy = 0.0;
770                 s->td.dtmf.current_sample = 0;
771         }
772
773         if (squelch && mute.end) {
774                 if (mute.end > samples) {
775                         s->td.dtmf.mute_samples = mute.end - samples;
776                         mute.end = samples;
777                 }
778                 mute_fragment(dsp, &mute);
779         }
780
781         return (s->td.dtmf.current_hit);        /* return the debounced hit */
782 }
783
784 static int mf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[],
785                  int samples, int squelch, int relax)
786 {
787         float energy[6];
788         int best;
789         int second_best;
790         int i;
791         int j;
792         int sample;
793         int hit;
794         int limit;
795         fragment_t mute = {0, 0};
796
797         if (squelch && s->td.mf.mute_samples > 0) {
798                 mute.end = (s->td.mf.mute_samples < samples) ? s->td.mf.mute_samples : samples;
799                 s->td.mf.mute_samples -= mute.end;
800         }
801
802         hit = 0;
803         for (sample = 0;  sample < samples;  sample = limit) {
804                 /* 80 is optimised to meet the MF specs. */
805                 /* XXX So then why is MF_GSIZE defined as 120? */
806                 if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample)) {
807                         limit = sample + (MF_GSIZE - s->td.mf.current_sample);
808                 } else {
809                         limit = samples;
810                 }
811                 /* The following unrolled loop takes only 35% (rough estimate) of the 
812                    time of a rolled loop on the machine on which it was developed */
813                 for (j = sample;  j < limit;  j++) {
814                         /* With GCC 2.95, the following unrolled code seems to take about 35%
815                            (rough estimate) as long as a neat little 0-3 loop */
816                         goertzel_sample(s->td.mf.tone_out, amp[j]);
817                         goertzel_sample(s->td.mf.tone_out + 1, amp[j]);
818                         goertzel_sample(s->td.mf.tone_out + 2, amp[j]);
819                         goertzel_sample(s->td.mf.tone_out + 3, amp[j]);
820                         goertzel_sample(s->td.mf.tone_out + 4, amp[j]);
821                         goertzel_sample(s->td.mf.tone_out + 5, amp[j]);
822                 }
823                 s->td.mf.current_sample += (limit - sample);
824                 if (s->td.mf.current_sample < MF_GSIZE) {
825                         continue;
826                 }
827                 /* We're at the end of an MF detection block.  */
828                 /* Find the two highest energies. The spec says to look for
829                    two tones and two tones only. Taking this literally -ie
830                    only two tones pass the minimum threshold - doesn't work
831                    well. The sinc function mess, due to rectangular windowing
832                    ensure that! Find the two highest energies and ensure they
833                    are considerably stronger than any of the others. */
834                 energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
835                 energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
836                 if (energy[0] > energy[1]) {
837                         best = 0;
838                         second_best = 1;
839                 } else {
840                         best = 1;
841                         second_best = 0;
842                 }
843                 /*endif*/
844                 for (i = 2; i < 6; i++) {
845                         energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
846                         if (energy[i] >= energy[best]) {
847                                 second_best = best;
848                                 best = i;
849                         } else if (energy[i] >= energy[second_best]) {
850                                 second_best = i;
851                         }
852                 }
853                 /* Basic signal level and twist tests */
854                 hit = 0;
855                 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
856                     && energy[best] < energy[second_best]*BELL_MF_TWIST
857                     && energy[best] * BELL_MF_TWIST > energy[second_best]) {
858                         /* Relative peak test */
859                         hit = -1;
860                         for (i = 0; i < 6; i++) {
861                                 if (i != best && i != second_best) {
862                                         if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
863                                                 /* The best two are not clearly the best */
864                                                 hit = 0;
865                                                 break;
866                                         }
867                                 }
868                         }
869                 }
870                 if (hit) {
871                         /* Get the values into ascending order */
872                         if (second_best < best) {
873                                 i = best;
874                                 best = second_best;
875                                 second_best = i;
876                         }
877                         best = best * 5 + second_best - 1;
878                         hit = bell_mf_positions[best];
879                         /* Look for two successive similar results */
880                         /* The logic in the next test is:
881                            For KP we need 4 successive identical clean detects, with
882                            two blocks of something different preceeding it. For anything
883                            else we need two successive identical clean detects, with
884                            two blocks of something different preceeding it. */
885                         if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
886                            ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
887                             (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] && 
888                             hit != s->td.mf.hits[0]))) {
889                                 store_digit(s, hit);
890                         }
891                 }
892
893
894                 if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
895                         /* Two successive block without a hit terminate current digit */
896                         s->td.mf.current_hit = 0;
897                 }
898
899                 s->td.mf.hits[0] = s->td.mf.hits[1];
900                 s->td.mf.hits[1] = s->td.mf.hits[2];
901                 s->td.mf.hits[2] = s->td.mf.hits[3];
902                 s->td.mf.hits[3] = s->td.mf.hits[4];
903                 s->td.mf.hits[4] = hit;
904
905                 /* If we had a hit in this block, include it into mute fragment */
906                 if (squelch && hit) {
907                         if (mute.end < sample - MF_GSIZE) {
908                                 /* There is a gap between fragments */
909                                 mute_fragment(dsp, &mute);
910                                 mute.start = (sample > MF_GSIZE) ? (sample - MF_GSIZE) : 0;
911                         }
912                         mute.end = limit + DTMF_GSIZE;
913                 }
914
915                 /* Reinitialise the detector for the next block */
916                 for (i = 0;  i < 6;  i++)
917                         goertzel_reset(&s->td.mf.tone_out[i]);
918                 s->td.mf.current_sample = 0;
919         }
920
921         if (squelch && mute.end) {
922                 if (mute.end > samples) {
923                         s->td.mf.mute_samples = mute.end - samples;
924                         mute.end = samples;
925                 }
926                 mute_fragment(dsp, &mute);
927         }
928
929         return (s->td.mf.current_hit); /* return the debounced hit */
930 }
931
932 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
933 {
934         /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
935         /* Make sure absolute levels are high enough */
936         if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH)) {
937                 return 0;
938         }
939         /* Amplify ignored stuff */
940         i2 *= TONE_THRESH;
941         i1 *= TONE_THRESH;
942         e *= TONE_THRESH;
943         /* Check first tone */
944         if ((p1 < i1) || (p1 < i2) || (p1 < e)) {
945                 return 0;
946         }
947         /* And second */
948         if ((p2 < i1) || (p2 < i2) || (p2 < e)) {
949                 return 0;
950         }
951         /* Guess it's there... */
952         return 1;
953 }
954
955 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
956 {
957         int x;
958         int y;
959         int pass;
960         int newstate = DSP_TONE_STATE_SILENCE;
961         int res = 0;
962         while (len) {
963                 /* Take the lesser of the number of samples we need and what we have */
964                 pass = len;
965                 if (pass > dsp->gsamp_size - dsp->gsamps) {
966                         pass = dsp->gsamp_size - dsp->gsamps;
967                 }
968                 for (x = 0; x < pass; x++) {
969                         for (y = 0; y < dsp->freqcount; y++) {
970                                 goertzel_sample(&dsp->freqs[y], s[x]);
971                         }
972                         dsp->genergy += s[x] * s[x];
973                 }
974                 s += pass;
975                 dsp->gsamps += pass;
976                 len -= pass;
977                 if (dsp->gsamps == dsp->gsamp_size) {
978                         float hz[7];
979                         for (y = 0; y < 7; y++) {
980                                 hz[y] = goertzel_result(&dsp->freqs[y]);
981                         }
982                         switch (dsp->progmode) {
983                         case PROG_MODE_NA:
984                                 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
985                                         newstate = DSP_TONE_STATE_BUSY;
986                                 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
987                                         newstate = DSP_TONE_STATE_RINGING;
988                                 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
989                                         newstate = DSP_TONE_STATE_DIALTONE;
990                                 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
991                                         newstate = DSP_TONE_STATE_SPECIAL1;
992                                 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
993                                         /* End of SPECIAL1 or middle of SPECIAL2 */
994                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL1 || dsp->tstate == DSP_TONE_STATE_SPECIAL2) {
995                                                 newstate = DSP_TONE_STATE_SPECIAL2;
996                                         }
997                                 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
998                                         /* End of SPECIAL2 or middle of SPECIAL3 */
999                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL2 || dsp->tstate == DSP_TONE_STATE_SPECIAL3) {
1000                                                 newstate = DSP_TONE_STATE_SPECIAL3;
1001                                         }
1002                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1003                                         newstate = DSP_TONE_STATE_TALKING;
1004                                 } else {
1005                                         newstate = DSP_TONE_STATE_SILENCE;
1006                                 }
1007                                 break;
1008                         case PROG_MODE_CR:
1009                                 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
1010                                         newstate = DSP_TONE_STATE_RINGING;
1011                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1012                                         newstate = DSP_TONE_STATE_TALKING;
1013                                 } else {
1014                                         newstate = DSP_TONE_STATE_SILENCE;
1015                                 }
1016                                 break;
1017                         case PROG_MODE_UK:
1018                                 if (hz[HZ_400UK] > TONE_MIN_THRESH * TONE_THRESH) {
1019                                         newstate = DSP_TONE_STATE_HUNGUP;
1020                                 } else if (pair_there(hz[HZ_350UK], hz[HZ_440UK], hz[HZ_400UK], hz[HZ_400UK], dsp->genergy)) {
1021                                         newstate = DSP_TONE_STATE_DIALTONE;
1022                                 }
1023                                 break;
1024                         default:
1025                                 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
1026                         }
1027                         if (newstate == dsp->tstate) {
1028                                 dsp->tcount++;
1029                                 if (dsp->ringtimeout) {
1030                                         dsp->ringtimeout++;
1031                                 }
1032                                 switch (dsp->tstate) {
1033                                 case DSP_TONE_STATE_RINGING:
1034                                         if ((dsp->features & DSP_PROGRESS_RINGING) &&
1035                                             (dsp->tcount == THRESH_RING)) {
1036                                                 res = AST_CONTROL_RINGING;
1037                                                 dsp->ringtimeout = 1;
1038                                         }
1039                                         break;
1040                                 case DSP_TONE_STATE_BUSY:
1041                                         if ((dsp->features & DSP_PROGRESS_BUSY) &&
1042                                             (dsp->tcount == THRESH_BUSY)) {
1043                                                 res = AST_CONTROL_BUSY;
1044                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1045                                         }
1046                                         break;
1047                                 case DSP_TONE_STATE_TALKING:
1048                                         if ((dsp->features & DSP_PROGRESS_TALK) &&
1049                                             (dsp->tcount == THRESH_TALK)) {
1050                                                 res = AST_CONTROL_ANSWER;
1051                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1052                                         }
1053                                         break;
1054                                 case DSP_TONE_STATE_SPECIAL3:
1055                                         if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
1056                                             (dsp->tcount == THRESH_CONGESTION)) {
1057                                                 res = AST_CONTROL_CONGESTION;
1058                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1059                                         }
1060                                         break;
1061                                 case DSP_TONE_STATE_HUNGUP:
1062                                         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
1063                                             (dsp->tcount == THRESH_HANGUP)) {
1064                                                 res = AST_CONTROL_HANGUP;
1065                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1066                                         }
1067                                         break;
1068                                 }
1069                                 if (dsp->ringtimeout == THRESH_RING2ANSWER) {
1070                                         ast_debug(1, "Consider call as answered because of timeout after last ring\n");
1071                                         res = AST_CONTROL_ANSWER;
1072                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1073                                 }
1074                         } else {
1075                                 ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
1076                                 ast_debug(5, "Start state %d\n", newstate);
1077                                 dsp->tstate = newstate;
1078                                 dsp->tcount = 1;
1079                         }
1080
1081                         /* Reset goertzel */
1082                         for (x = 0; x < 7; x++) {
1083                                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1084                         }
1085                         dsp->gsamps = 0;
1086                         dsp->genergy = 0.0;
1087                 }
1088         }
1089
1090         return res;
1091 }
1092
1093 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1094 {
1095         if (inf->frametype != AST_FRAME_VOICE) {
1096                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1097                 return 0;
1098         }
1099         if (!ast_format_is_slinear(&inf->subclass.format)) {
1100                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1101                 return 0;
1102         }
1103         return __ast_dsp_call_progress(dsp, inf->data.ptr, inf->datalen / 2);
1104 }
1105
1106 static int __ast_dsp_silence_noise(struct ast_dsp *dsp, short *s, int len, int *totalsilence, int *totalnoise)
1107 {
1108         int accum;
1109         int x;
1110         int res = 0;
1111
1112         if (!len) {
1113                 return 0;
1114         }
1115         accum = 0;
1116         for (x = 0; x < len; x++) {
1117                 accum += abs(s[x]);
1118         }
1119         accum /= len;
1120         if (accum < dsp->threshold) {
1121                 /* Silent */
1122                 dsp->totalsilence += len / (dsp->sample_rate / 1000);
1123                 if (dsp->totalnoise) {
1124                         /* Move and save history */
1125                         memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicnoise[0]));
1126                         dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1127 /* we don't want to check for busydetect that frequently */
1128 #if 0
1129                         dsp->busymaybe = 1;
1130 #endif
1131                 }
1132                 dsp->totalnoise = 0;
1133                 res = 1;
1134         } else {
1135                 /* Not silent */
1136                 dsp->totalnoise += len / (dsp->sample_rate / 1000);
1137                 if (dsp->totalsilence) {
1138                         int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1139                         int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1140                         /* Move and save history */
1141                         memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicsilence[0]));
1142                         dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1143                         /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1144                         if (silence1 < silence2) {
1145                                 if (silence1 + silence1 * BUSY_PERCENT / 100 >= silence2) {
1146                                         dsp->busymaybe = 1;
1147                                 } else {
1148                                         dsp->busymaybe = 0;
1149                                 }
1150                         } else {
1151                                 if (silence1 - silence1 * BUSY_PERCENT / 100 <= silence2) {
1152                                         dsp->busymaybe = 1;
1153                                 } else {
1154                                         dsp->busymaybe = 0;
1155                                 }
1156                         }
1157                 }
1158                 dsp->totalsilence = 0;
1159         }
1160         if (totalsilence) {
1161                 *totalsilence = dsp->totalsilence;
1162         }
1163         if (totalnoise) {
1164                 *totalnoise = dsp->totalnoise;
1165         }
1166         return res;
1167 }
1168
1169 int ast_dsp_busydetect(struct ast_dsp *dsp)
1170 {
1171         int res = 0, x;
1172 #ifndef BUSYDETECT_TONEONLY
1173         int avgsilence = 0, hitsilence = 0;
1174 #endif
1175         int avgtone = 0, hittone = 0;
1176
1177         /* if we have a 4 length pattern, the way busymaybe is set doesn't help us. */
1178         if (dsp->busy_cadence.length != 4) {
1179                 if (!dsp->busymaybe) {
1180                         return res;
1181                 }
1182         }
1183
1184         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1185 #ifndef BUSYDETECT_TONEONLY
1186                 avgsilence += dsp->historicsilence[x];
1187 #endif
1188                 avgtone += dsp->historicnoise[x];
1189         }
1190 #ifndef BUSYDETECT_TONEONLY
1191         avgsilence /= dsp->busycount;
1192 #endif
1193         avgtone /= dsp->busycount;
1194         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1195 #ifndef BUSYDETECT_TONEONLY
1196                 if (avgsilence > dsp->historicsilence[x]) {
1197                         if (avgsilence - (avgsilence * BUSY_PERCENT / 100) <= dsp->historicsilence[x]) {
1198                                 hitsilence++;
1199                         }
1200                 } else {
1201                         if (avgsilence + (avgsilence * BUSY_PERCENT / 100) >= dsp->historicsilence[x]) {
1202                                 hitsilence++;
1203                         }
1204                 }
1205 #endif
1206                 if (avgtone > dsp->historicnoise[x]) {
1207                         if (avgtone - (avgtone * BUSY_PERCENT / 100) <= dsp->historicnoise[x]) {
1208                                 hittone++;
1209                         }
1210                 } else {
1211                         if (avgtone + (avgtone * BUSY_PERCENT / 100) >= dsp->historicnoise[x]) {
1212                                 hittone++;
1213                         }
1214                 }
1215         }
1216 #ifndef BUSYDETECT_TONEONLY
1217         if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) && 
1218             (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) && 
1219             (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1220 #else
1221         if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1222 #endif
1223 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1224                 if (avgtone > avgsilence) {
1225                         if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence) {
1226                                 res = 1;
1227                         }
1228                 } else {
1229                         if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence) {
1230                                 res = 1;
1231                         }
1232                 }
1233 #else
1234                 res = 1;
1235 #endif
1236         }
1237
1238         /* If we have a 4-length pattern, we can go ahead and just check it in a different way. */
1239         if (dsp->busy_cadence.length == 4) {
1240                 int x;
1241                 int errors = 0;
1242                 int errors_max = ((4 * dsp->busycount) / 100.0) * BUSY_PAT_PERCENT;
1243
1244                 for (x = DSP_HISTORY - (dsp->busycount); x < DSP_HISTORY; x += 2) {
1245                         int temp_error;
1246                         temp_error = abs(dsp->historicnoise[x] - dsp->busy_cadence.pattern[0]);
1247                         if ((temp_error * 100) / dsp->busy_cadence.pattern[0] > BUSY_PERCENT) {
1248                                 errors++;
1249                         }
1250
1251                         temp_error = abs(dsp->historicnoise[x + 1] - dsp->busy_cadence.pattern[2]);
1252                         if ((temp_error * 100) / dsp->busy_cadence.pattern[2] > BUSY_PERCENT) {
1253                                 errors++;
1254                         }
1255
1256                         temp_error = abs(dsp->historicsilence[x] - dsp->busy_cadence.pattern[1]);
1257                         if ((temp_error * 100) / dsp->busy_cadence.pattern[1] > BUSY_PERCENT) {
1258                                 errors++;
1259                         }
1260
1261                         temp_error = abs(dsp->historicsilence[x + 1] - dsp->busy_cadence.pattern[3]);
1262                         if ((temp_error * 100) / dsp->busy_cadence.pattern[3] > BUSY_PERCENT) {
1263                                 errors++;
1264                         }
1265                 }
1266
1267                 ast_debug(5, "errors = %d  max = %d\n", errors, errors_max);
1268
1269                 if (errors <= errors_max) {
1270                         return 1;
1271                 }
1272         }
1273
1274         /* If we know the expected busy tone length, check we are in the range */
1275         if (res && (dsp->busy_cadence.pattern[0] > 0)) {
1276                 if (abs(avgtone - dsp->busy_cadence.pattern[0]) > (dsp->busy_cadence.pattern[0]*BUSY_PAT_PERCENT/100)) {
1277 #ifdef BUSYDETECT_DEBUG
1278                         ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
1279                                 avgtone, dsp->busy_cadence.pattern[0]);
1280 #endif
1281                         res = 0;
1282                 }
1283         }
1284 #ifndef BUSYDETECT_TONEONLY
1285         /* If we know the expected busy tone silent-period length, check we are in the range */
1286         if (res && (dsp->busy_cadence.pattern[1] > 0)) {
1287                 if (abs(avgsilence - dsp->busy_cadence.pattern[1]) > (dsp->busy_cadence.pattern[1] * BUSY_PAT_PERCENT / 100)) {
1288 #ifdef BUSYDETECT_DEBUG
1289                 ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
1290                         avgsilence, dsp->busy_cadence.pattern[1]);
1291 #endif
1292                         res = 0;
1293                 }
1294         }
1295 #endif
1296 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
1297         if (res) {
1298                 ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1299         } else {
1300                 ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1301         }
1302 #endif
1303         return res;
1304 }
1305
1306 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1307 {
1308         short *s;
1309         int len;
1310         
1311         if (f->frametype != AST_FRAME_VOICE) {
1312                 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1313                 return 0;
1314         }
1315         if (!ast_format_is_slinear(&f->subclass.format)) {
1316                 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear frames :(\n");
1317                 return 0;
1318         }
1319         s = f->data.ptr;
1320         len = f->datalen/2;
1321         return __ast_dsp_silence_noise(dsp, s, len, totalsilence, NULL);
1322 }
1323
1324 int ast_dsp_noise(struct ast_dsp *dsp, struct ast_frame *f, int *totalnoise)
1325 {
1326        short *s;
1327        int len;
1328
1329        if (f->frametype != AST_FRAME_VOICE) {
1330                ast_log(LOG_WARNING, "Can't calculate noise on a non-voice frame\n");
1331                return 0;
1332        }
1333        if (!ast_format_is_slinear(&f->subclass.format)) {
1334                ast_log(LOG_WARNING, "Can only calculate noise on signed-linear frames :(\n");
1335                return 0;
1336        }
1337        s = f->data.ptr;
1338        len = f->datalen/2;
1339        return __ast_dsp_silence_noise(dsp, s, len, NULL, totalnoise);
1340 }
1341
1342
1343 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1344 {
1345         int silence;
1346         int res;
1347         int digit = 0, fax_digit = 0;
1348         int x;
1349         short *shortdata;
1350         unsigned char *odata;
1351         int len;
1352         struct ast_frame *outf = NULL;
1353
1354         if (!af) {
1355                 return NULL;
1356         }
1357         if (af->frametype != AST_FRAME_VOICE) {
1358                 return af;
1359         }
1360
1361         odata = af->data.ptr;
1362         len = af->datalen;
1363         /* Make sure we have short data */
1364         if (ast_format_is_slinear(&af->subclass.format)) {
1365                 shortdata = af->data.ptr;
1366                 len = af->datalen / 2;
1367         } else {
1368                 switch (af->subclass.format.id) {
1369                 case AST_FORMAT_ULAW:
1370                 case AST_FORMAT_TESTLAW:
1371                         shortdata = alloca(af->datalen * 2);
1372                         for (x = 0;x < len; x++) {
1373                                 shortdata[x] = AST_MULAW(odata[x]);
1374                         }
1375                         break;
1376                 case AST_FORMAT_ALAW:
1377                         shortdata = alloca(af->datalen * 2);
1378                         for (x = 0; x < len; x++) {
1379                                 shortdata[x] = AST_ALAW(odata[x]);
1380                         }
1381                         break;
1382                 default:
1383                         /*Display warning only once. Otherwise you would get hundreds of warnings every second */
1384                         if (dsp->display_inband_dtmf_warning)
1385                                 ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(&af->subclass.format));
1386                         dsp->display_inband_dtmf_warning = 0;
1387                         return af;
1388                 }
1389         }
1390
1391         /* Initially we do not want to mute anything */
1392         dsp->mute_fragments = 0;
1393
1394         /* Need to run the silence detection stuff for silence suppression and busy detection */
1395         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) || (dsp->features & DSP_FEATURE_BUSY_DETECT)) {
1396                 res = __ast_dsp_silence_noise(dsp, shortdata, len, &silence, NULL);
1397         }
1398
1399         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1400                 memset(&dsp->f, 0, sizeof(dsp->f));
1401                 dsp->f.frametype = AST_FRAME_NULL;
1402                 ast_frfree(af);
1403                 return ast_frisolate(&dsp->f);
1404         }
1405         if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1406                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1407                 memset(&dsp->f, 0, sizeof(dsp->f));
1408                 dsp->f.frametype = AST_FRAME_CONTROL;
1409                 dsp->f.subclass.integer = AST_CONTROL_BUSY;
1410                 ast_frfree(af);
1411                 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", chan->name);
1412                 return ast_frisolate(&dsp->f);
1413         }
1414
1415         if ((dsp->features & DSP_FEATURE_FAX_DETECT)) {
1416                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CNG) && tone_detect(dsp, &dsp->cng_tone_state, shortdata, len)) {
1417                         fax_digit = 'f';
1418                 }
1419
1420                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CED) && tone_detect(dsp, &dsp->ced_tone_state, shortdata, len)) {
1421                         fax_digit = 'e';
1422                 }
1423         }
1424
1425         if (dsp->features & (DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_BUSY_DETECT)) {
1426                 if (dsp->digitmode & DSP_DIGITMODE_MF)
1427                         digit = mf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1428                 else
1429                         digit = dtmf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1430
1431                 if (dsp->digit_state.current_digits) {
1432                         int event = 0, event_len = 0;
1433                         char event_digit = 0;
1434
1435                         if (!dsp->dtmf_began) {
1436                                 /* We have not reported DTMF_BEGIN for anything yet */
1437
1438                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1439                                         event = AST_FRAME_DTMF_BEGIN;
1440                                         event_digit = dsp->digit_state.digits[0];
1441                                 }
1442                                 dsp->dtmf_began = 1;
1443
1444                         } else if (dsp->digit_state.current_digits > 1 || digit != dsp->digit_state.digits[0]) {
1445                                 /* Digit changed. This means digit we have reported with DTMF_BEGIN ended */
1446                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1447                                         event = AST_FRAME_DTMF_END;
1448                                         event_digit = dsp->digit_state.digits[0];
1449                                         event_len = dsp->digit_state.digitlen[0] * 1000 / dsp->sample_rate;
1450                                 }
1451                                 memmove(&dsp->digit_state.digits[0], &dsp->digit_state.digits[1], dsp->digit_state.current_digits);
1452                                 memmove(&dsp->digit_state.digitlen[0], &dsp->digit_state.digitlen[1], dsp->digit_state.current_digits * sizeof(dsp->digit_state.digitlen[0]));
1453                                 dsp->digit_state.current_digits--;
1454                                 dsp->dtmf_began = 0;
1455
1456                                 if (dsp->features & DSP_FEATURE_BUSY_DETECT) {
1457                                         /* Reset Busy Detector as we have some confirmed activity */ 
1458                                         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1459                                         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1460                                         ast_debug(1, "DTMF Detected - Reset busydetector\n");
1461                                 }
1462                         }
1463
1464                         if (event) {
1465                                 memset(&dsp->f, 0, sizeof(dsp->f));
1466                                 dsp->f.frametype = event;
1467                                 dsp->f.subclass.integer = event_digit;
1468                                 dsp->f.len = event_len;
1469                                 outf = &dsp->f;
1470                                 goto done;
1471                         }
1472                 }
1473         }
1474
1475         if (fax_digit) {
1476                 /* Fax was detected - digit is either 'f' or 'e' */
1477
1478                 memset(&dsp->f, 0, sizeof(dsp->f));
1479                 dsp->f.frametype = AST_FRAME_DTMF;
1480                 dsp->f.subclass.integer = fax_digit;
1481                 outf = &dsp->f;
1482                 goto done;
1483         }
1484
1485         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1486                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1487                 if (res) {
1488                         switch (res) {
1489                         case AST_CONTROL_ANSWER:
1490                         case AST_CONTROL_BUSY:
1491                         case AST_CONTROL_RINGING:
1492                         case AST_CONTROL_CONGESTION:
1493                         case AST_CONTROL_HANGUP:
1494                                 memset(&dsp->f, 0, sizeof(dsp->f));
1495                                 dsp->f.frametype = AST_FRAME_CONTROL;
1496                                 dsp->f.subclass.integer = res;
1497                                 dsp->f.src = "dsp_progress";
1498                                 if (chan) 
1499                                         ast_queue_frame(chan, &dsp->f);
1500                                 break;
1501                         default:
1502                                 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1503                         }
1504                 }
1505         } else if ((dsp->features & DSP_FEATURE_WAITDIALTONE)) {
1506                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1507         }
1508
1509 done:
1510         /* Mute fragment of the frame */
1511         for (x = 0; x < dsp->mute_fragments; x++) {
1512                 memset(shortdata + dsp->mute_data[x].start, 0, sizeof(int16_t) * (dsp->mute_data[x].end - dsp->mute_data[x].start));
1513         }
1514
1515         switch (af->subclass.format.id) {
1516         case AST_FORMAT_ULAW:
1517                 for (x = 0; x < len; x++) {
1518                         odata[x] = AST_LIN2MU((unsigned short) shortdata[x]);
1519                 }
1520                 break;
1521         case AST_FORMAT_ALAW:
1522                 for (x = 0; x < len; x++) {
1523                         odata[x] = AST_LIN2A((unsigned short) shortdata[x]);
1524                 }
1525                 /* fall through */
1526         default:
1527                 break;
1528         }
1529
1530         if (outf) {
1531                 if (chan) {
1532                         ast_queue_frame(chan, af);
1533                 }
1534                 ast_frfree(af);
1535                 return ast_frisolate(outf);
1536         } else {
1537                 return af;
1538         }
1539 }
1540
1541 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1542 {
1543         int max = 0;
1544         int x;
1545         
1546         dsp->gsamp_size = modes[dsp->progmode].size;
1547         dsp->gsamps = 0;
1548         for (x = 0; x < ARRAY_LEN(modes[dsp->progmode].freqs); x++) {
1549                 if (modes[dsp->progmode].freqs[x]) {
1550                         goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->gsamp_size, dsp->sample_rate);
1551                         max = x + 1;
1552                 }
1553         }
1554         dsp->freqcount = max;
1555         dsp->ringtimeout= 0;
1556 }
1557
1558 unsigned int ast_dsp_get_sample_rate(const struct ast_dsp *dsp)
1559 {
1560         return dsp->sample_rate;
1561 }
1562
1563 static struct ast_dsp *__ast_dsp_new(unsigned int sample_rate)
1564 {
1565         struct ast_dsp *dsp;
1566         
1567         if ((dsp = ast_calloc(1, sizeof(*dsp)))) {              
1568                 dsp->threshold = DEFAULT_THRESHOLD;
1569                 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1570                 dsp->busycount = DSP_HISTORY;
1571                 dsp->digitmode = DSP_DIGITMODE_DTMF;
1572                 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1573                 dsp->sample_rate = sample_rate;
1574                 /* Initialize digit detector */
1575                 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF, dsp->sample_rate);
1576                 dsp->display_inband_dtmf_warning = 1;
1577                 /* Initialize initial DSP progress detect parameters */
1578                 ast_dsp_prog_reset(dsp);
1579                 /* Initialize fax detector */
1580                 ast_fax_detect_init(dsp);
1581         }
1582         return dsp;
1583 }
1584
1585 struct ast_dsp *ast_dsp_new(void)
1586 {
1587         return __ast_dsp_new(DEFAULT_SAMPLE_RATE);
1588 }
1589
1590 struct ast_dsp *ast_dsp_new_with_rate(unsigned int sample_rate)
1591 {
1592         return __ast_dsp_new(sample_rate);
1593 }
1594
1595 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1596 {
1597         dsp->features = features;
1598 }
1599
1600 void ast_dsp_free(struct ast_dsp *dsp)
1601 {
1602         ast_free(dsp);
1603 }
1604
1605 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1606 {
1607         dsp->threshold = threshold;
1608 }
1609
1610 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1611 {
1612         if (cadences < 4) {
1613                 cadences = 4;
1614         }
1615         if (cadences > DSP_HISTORY) {
1616                 cadences = DSP_HISTORY;
1617         }
1618         dsp->busycount = cadences;
1619 }
1620
1621 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, const struct ast_dsp_busy_pattern *cadence)
1622 {
1623         dsp->busy_cadence = *cadence;
1624         ast_debug(1, "dsp busy pattern set to %d,%d,%d,%d\n", cadence->pattern[0], cadence->pattern[1], (cadence->length == 4) ? cadence->pattern[2] : 0, (cadence->length == 4) ? cadence->pattern[3] : 0);
1625 }
1626
1627 void ast_dsp_digitreset(struct ast_dsp *dsp)
1628 {
1629         int i;
1630         
1631         dsp->dtmf_began = 0;
1632         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1633                 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1634                 /* Reinitialise the detector for the next block */
1635                 for (i = 0;  i < 6;  i++) {
1636                         goertzel_reset(&s->tone_out[i]);
1637                 }
1638                 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = s->current_hit = 0;
1639                 s->current_sample = 0;
1640         } else {
1641                 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1642                 /* Reinitialise the detector for the next block */
1643                 for (i = 0;  i < 4;  i++) {
1644                         goertzel_reset(&s->row_out[i]);
1645                         goertzel_reset(&s->col_out[i]);
1646                 }
1647                 s->lasthit = s->current_hit = 0;
1648                 s->energy = 0.0;
1649                 s->current_sample = 0;
1650                 s->hits = 0;
1651                 s->misses = 0;
1652         }
1653
1654         dsp->digit_state.digits[0] = '\0';
1655         dsp->digit_state.current_digits = 0;
1656 }
1657
1658 void ast_dsp_reset(struct ast_dsp *dsp)
1659 {
1660         int x;
1661         
1662         dsp->totalsilence = 0;
1663         dsp->gsamps = 0;
1664         for (x = 0; x < 4; x++) {
1665                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1666         }
1667         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1668         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));      
1669         dsp->ringtimeout= 0;
1670 }
1671
1672 int ast_dsp_set_digitmode(struct ast_dsp *dsp, int digitmode)
1673 {
1674         int new;
1675         int old;
1676         
1677         old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1678         new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1679         if (old != new) {
1680                 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1681                 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF, dsp->sample_rate);
1682         }
1683         dsp->digitmode = digitmode;
1684         return 0;
1685 }
1686
1687 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1688 {
1689         if (dsp->faxmode != faxmode) {
1690                 ast_fax_detect_init(dsp);
1691         }
1692         dsp->faxmode = faxmode;
1693         return 0;
1694 }
1695
1696 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1697 {
1698         int x;
1699         
1700         for (x = 0; x < ARRAY_LEN(aliases); x++) {
1701                 if (!strcasecmp(aliases[x].name, zone)) {
1702                         dsp->progmode = aliases[x].mode;
1703                         ast_dsp_prog_reset(dsp);
1704                         return 0;
1705                 }
1706         }
1707         return -1;
1708 }
1709
1710 int ast_dsp_was_muted(struct ast_dsp *dsp)
1711 {
1712         return (dsp->mute_fragments > 0);
1713 }
1714
1715 int ast_dsp_get_tstate(struct ast_dsp *dsp) 
1716 {
1717         return dsp->tstate;
1718 }
1719
1720 int ast_dsp_get_tcount(struct ast_dsp *dsp) 
1721 {
1722         return dsp->tcount;
1723 }
1724
1725 static int _dsp_init(int reload)
1726 {
1727         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1728         struct ast_config *cfg;
1729
1730         cfg = ast_config_load2(CONFIG_FILE_NAME, "dsp", config_flags);
1731         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
1732                 ast_verb(5, "Can't find dsp config file %s. Assuming default silencethreshold of %d.\n", CONFIG_FILE_NAME, DEFAULT_SILENCE_THRESHOLD);
1733                 thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1734                 return 0;
1735         }
1736
1737         if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
1738                 return 0;
1739         }
1740
1741         if (cfg) {
1742                 const char *value;
1743
1744                 value = ast_variable_retrieve(cfg, "default", "silencethreshold");
1745                 if (value && sscanf(value, "%30d", &thresholds[THRESHOLD_SILENCE]) != 1) {
1746                         ast_verb(5, "%s: '%s' is not a valid silencethreshold value\n", CONFIG_FILE_NAME, value);
1747                         thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1748                 } else if (!value) {
1749                         thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1750                 }
1751
1752                 ast_config_destroy(cfg);
1753         }
1754         return 0;
1755 }
1756
1757 int ast_dsp_get_threshold_from_settings(enum threshold which)
1758 {
1759         return thresholds[which];
1760 }
1761
1762 int ast_dsp_init(void)
1763 {
1764         return _dsp_init(0);
1765 }
1766
1767 int ast_dsp_reload(void)
1768 {
1769         return _dsp_init(1);
1770 }
1771