Fix an issue where dsp.c would interpret multiple dtmf events from a single key press.
[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      4
205 /* How many successive misses needed to consider end of a digit */
206 #define DTMF_MISSES_TO_END      4
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
433         /* Now calculate final block size. It will contain integer number of periods */
434         s->block_size = periods_in_block * sample_rate / freq;
435
436         /* tone_detect is currently only used to detect fax tones and we
437            do not need suqlching the fax tones */
438         s->squelch = 0;
439
440         /* Account for the first and the last block to be incomplete
441            and thus no tone will be detected in them */
442         s->hits_required = (duration_samples - (s->block_size - 1)) / s->block_size;
443
444         goertzel_init(&s->tone, freq, s->block_size, sample_rate);
445
446         s->samples_pending = s->block_size;
447         s->hit_count = 0;
448         s->last_hit = 0;
449         s->energy = 0.0;
450
451         /* We want tone energy to be amp decibels above the rest of the signal (the noise).
452            According to Parseval's theorem the energy computed in time domain equals to energy
453            computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
454            from the energy in the time domain we will get energy of the remaining signal (without the tone
455            we are detecting). We will be checking that
456                 10*log(Ew / (Et - Ew)) > amp
457            Calculate threshold so that we will be actually checking
458                 Ew > Et * threshold
459         */
460
461         x = pow(10.0, amp / 10.0);
462         s->threshold = x / (x + 1);
463
464         ast_debug(1, "Setup tone %d Hz, %d ms, block_size=%d, hits_required=%d\n", freq, duration, s->block_size, s->hits_required);
465 }
466
467 static void ast_fax_detect_init(struct ast_dsp *s)
468 {
469         ast_tone_detect_init(&s->cng_tone_state, FAX_TONE_CNG_FREQ, FAX_TONE_CNG_DURATION, FAX_TONE_CNG_DB, s->sample_rate);
470         ast_tone_detect_init(&s->ced_tone_state, FAX_TONE_CED_FREQ, FAX_TONE_CED_DURATION, FAX_TONE_CED_DB, s->sample_rate);
471         if (s->faxmode & DSP_FAXMODE_DETECT_SQUELCH) {
472                 s->cng_tone_state.squelch = 1;
473                 s->ced_tone_state.squelch = 1;
474         }
475
476 }
477
478 static void ast_dtmf_detect_init (dtmf_detect_state_t *s, unsigned int sample_rate)
479 {
480         int i;
481
482         s->lasthit = 0;
483         s->current_hit = 0;
484         for (i = 0;  i < 4;  i++) {
485                 goertzel_init(&s->row_out[i], dtmf_row[i], DTMF_GSIZE, sample_rate);
486                 goertzel_init(&s->col_out[i], dtmf_col[i], DTMF_GSIZE, sample_rate);
487                 s->energy = 0.0;
488         }
489         s->current_sample = 0;
490         s->hits = 0;
491         s->misses = 0;
492
493         s->hits_to_begin = DTMF_HITS_TO_BEGIN;
494         s->misses_to_end = DTMF_MISSES_TO_END;
495 }
496
497 static void ast_mf_detect_init (mf_detect_state_t *s, unsigned int sample_rate)
498 {
499         int i;
500         s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
501         for (i = 0;  i < 6;  i++) {
502                 goertzel_init (&s->tone_out[i], mf_tones[i], 160, sample_rate);
503         }
504         s->current_sample = 0;
505         s->current_hit = 0;
506 }
507
508 static void ast_digit_detect_init(digit_detect_state_t *s, int mf, unsigned int sample_rate)
509 {
510         s->current_digits = 0;
511         s->detected_digits = 0;
512         s->lost_digits = 0;
513         s->digits[0] = '\0';
514
515         if (mf) {
516                 ast_mf_detect_init(&s->td.mf, sample_rate);
517         } else {
518                 ast_dtmf_detect_init(&s->td.dtmf, sample_rate);
519         }
520 }
521
522 static int tone_detect(struct ast_dsp *dsp, tone_detect_state_t *s, int16_t *amp, int samples)
523 {
524         float tone_energy;
525         int i;
526         int hit = 0;
527         int limit;
528         int res = 0;
529         int16_t *ptr;
530         int start, end;
531         fragment_t mute = {0, 0};
532
533         if (s->squelch && s->mute_samples > 0) {
534                 mute.end = (s->mute_samples < samples) ? s->mute_samples : samples;
535                 s->mute_samples -= mute.end;
536         }
537
538         for (start = 0;  start < samples;  start = end) {
539                 /* Process in blocks. */
540                 limit = samples - start;
541                 if (limit > s->samples_pending) {
542                         limit = s->samples_pending;
543                 }
544                 end = start + limit;
545
546                 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
547                         /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
548                         s->energy += (int32_t) *ptr * (int32_t) *ptr;
549
550                         goertzel_sample(&s->tone, *ptr);
551                 }
552
553                 s->samples_pending -= limit;
554
555                 if (s->samples_pending) {
556                         /* Finished incomplete (last) block */
557                         break;
558                 }
559
560                 tone_energy = goertzel_result(&s->tone);
561
562                 /* Scale to make comparable */
563                 tone_energy *= 2.0;
564                 s->energy *= s->block_size;
565
566                 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));
567                 hit = 0;
568                 if (tone_energy > s->energy * s->threshold) {
569                         ast_debug(10, "Hit! count=%d\n", s->hit_count);
570                         hit = 1;
571                 }
572
573                 if (s->hit_count) {
574                         s->hit_count++;
575                 }
576
577                 if (hit == s->last_hit) {
578                         if (!hit) {
579                                 /* Two successive misses. Tone ended */
580                                 s->hit_count = 0;
581                         } else if (!s->hit_count) {
582                                 s->hit_count++;
583                         }
584
585                 }
586
587                 if (s->hit_count == s->hits_required) {
588                         ast_debug(1, "%d Hz done detected\n", s->freq);
589                         res = 1;
590                 }
591
592                 s->last_hit = hit;
593
594                 /* If we had a hit in this block, include it into mute fragment */
595                 if (s->squelch && hit) {
596                         if (mute.end < start - s->block_size) {
597                                 /* There is a gap between fragments */
598                                 mute_fragment(dsp, &mute);
599                                 mute.start = (start > s->block_size) ? (start - s->block_size) : 0;
600                         }
601                         mute.end = end + s->block_size;
602                 }
603
604                 /* Reinitialise the detector for the next block */
605                 /* Reset for the next block */
606                 goertzel_reset(&s->tone);
607
608                 /* Advance to the next block */
609                 s->energy = 0.0;
610                 s->samples_pending = s->block_size;
611
612                 amp += limit;
613         }
614
615         if (s->squelch && mute.end) {
616                 if (mute.end > samples) {
617                         s->mute_samples = mute.end - samples;
618                         mute.end = samples;
619                 }
620                 mute_fragment(dsp, &mute);
621         }
622
623         return res;
624 }
625
626 static void store_digit(digit_detect_state_t *s, char digit)
627 {
628         s->detected_digits++;
629         if (s->current_digits < MAX_DTMF_DIGITS) {
630                 s->digitlen[s->current_digits] = 0;
631                 s->digits[s->current_digits++] = digit;
632                 s->digits[s->current_digits] = '\0';
633         } else {
634                 ast_log(LOG_WARNING, "Digit lost due to full buffer\n");
635                 s->lost_digits++;
636         }
637 }
638
639 static int dtmf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[], int samples, int squelch, int relax)
640 {
641         float row_energy[4];
642         float col_energy[4];
643         float famp;
644         int i;
645         int j;
646         int sample;
647         int best_row;
648         int best_col;
649         int hit;
650         int limit;
651         fragment_t mute = {0, 0};
652
653         if (squelch && s->td.dtmf.mute_samples > 0) {
654                 mute.end = (s->td.dtmf.mute_samples < samples) ? s->td.dtmf.mute_samples : samples;
655                 s->td.dtmf.mute_samples -= mute.end;
656         }
657
658         hit = 0;
659         for (sample = 0; sample < samples; sample = limit) {
660                 /* DTMF_GSIZE is optimised to meet the DTMF specs. */
661                 if ((samples - sample) >= (DTMF_GSIZE - s->td.dtmf.current_sample)) {
662                         limit = sample + (DTMF_GSIZE - s->td.dtmf.current_sample);
663                 } else {
664                         limit = samples;
665                 }
666                 /* The following unrolled loop takes only 35% (rough estimate) of the 
667                    time of a rolled loop on the machine on which it was developed */
668                 for (j = sample; j < limit; j++) {
669                         famp = amp[j];
670                         s->td.dtmf.energy += famp*famp;
671                         /* With GCC 2.95, the following unrolled code seems to take about 35%
672                            (rough estimate) as long as a neat little 0-3 loop */
673                         goertzel_sample(s->td.dtmf.row_out, amp[j]);
674                         goertzel_sample(s->td.dtmf.col_out, amp[j]);
675                         goertzel_sample(s->td.dtmf.row_out + 1, amp[j]);
676                         goertzel_sample(s->td.dtmf.col_out + 1, amp[j]);
677                         goertzel_sample(s->td.dtmf.row_out + 2, amp[j]);
678                         goertzel_sample(s->td.dtmf.col_out + 2, amp[j]);
679                         goertzel_sample(s->td.dtmf.row_out + 3, amp[j]);
680                         goertzel_sample(s->td.dtmf.col_out + 3, amp[j]);
681                 }
682                 s->td.dtmf.current_sample += (limit - sample);
683                 if (s->td.dtmf.current_sample < DTMF_GSIZE) {
684                         continue;
685                 }
686                 /* We are at the end of a DTMF detection block */
687                 /* Find the peak row and the peak column */
688                 row_energy[0] = goertzel_result (&s->td.dtmf.row_out[0]);
689                 col_energy[0] = goertzel_result (&s->td.dtmf.col_out[0]);
690
691                 for (best_row = best_col = 0, i = 1;  i < 4;  i++) {
692                         row_energy[i] = goertzel_result (&s->td.dtmf.row_out[i]);
693                         if (row_energy[i] > row_energy[best_row]) {
694                                 best_row = i;
695                         }
696                         col_energy[i] = goertzel_result (&s->td.dtmf.col_out[i]);
697                         if (col_energy[i] > col_energy[best_col]) {
698                                 best_col = i;
699                         }
700                 }
701                 hit = 0;
702                 /* Basic signal level test and the twist test */
703                 if (row_energy[best_row] >= DTMF_THRESHOLD &&
704                     col_energy[best_col] >= DTMF_THRESHOLD &&
705                     col_energy[best_col] < row_energy[best_row] * DTMF_REVERSE_TWIST &&
706                     col_energy[best_col] * DTMF_NORMAL_TWIST > row_energy[best_row]) {
707                         /* Relative peak test */
708                         for (i = 0;  i < 4;  i++) {
709                                 if ((i != best_col &&
710                                     col_energy[i] * DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
711                                     (i != best_row
712                                      && row_energy[i] * DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
713                                         break;
714                                 }
715                         }
716                         /* ... and fraction of total energy test */
717                         if (i >= 4 &&
718                             (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY * s->td.dtmf.energy) {
719                                 /* Got a hit */
720                                 hit = dtmf_positions[(best_row << 2) + best_col];
721                         }
722                 }
723
724                 if (hit == s->td.dtmf.lasthit) {
725                         if (s->td.dtmf.current_hit) {
726                                 /* We are in the middle of a digit already */
727                                 if (hit) {
728                                         if (hit != s->td.dtmf.current_hit) {
729                                                 /* Look for a start of a new digit.
730                                                    This is because hits_to_begin may be smaller than misses_to_end
731                                                    and we may find the beginning of new digit before we consider last one ended. */
732                                                 s->td.dtmf.current_hit = 0;
733                                         } else {
734                                                 /* Current hit was same as last, so increment digit duration (of last digit) */
735                                                 s->digitlen[s->current_digits - 1] += DTMF_GSIZE;
736                                         }
737                                 } else {
738                                         /* No Digit */
739                                         s->td.dtmf.misses++;
740                                         if (s->td.dtmf.misses == s->td.dtmf.misses_to_end) {
741                                                 /* There were enough misses to consider digit ended */
742                                                 s->td.dtmf.current_hit = 0;
743                                         }
744                                 }
745                         } else if (hit) {
746                                 /* Detecting new digit */
747                                 s->td.dtmf.hits++;
748                                 if (s->td.dtmf.hits == s->td.dtmf.hits_to_begin) {
749                                         store_digit(s, hit);
750                                         s->td.dtmf.current_hit = hit;
751                                 }
752                         }
753                 } else {
754                         s->td.dtmf.hits = 1;
755                         s->td.dtmf.misses = 1;
756                         s->td.dtmf.lasthit = hit;
757                 }
758
759                 /* If we had a hit in this block, include it into mute fragment */
760                 if (squelch && hit) {
761                         if (mute.end < sample - DTMF_GSIZE) {
762                                 /* There is a gap between fragments */
763                                 mute_fragment(dsp, &mute);
764                                 mute.start = (sample > DTMF_GSIZE) ? (sample - DTMF_GSIZE) : 0;
765                         }
766                         mute.end = limit + DTMF_GSIZE;
767                 }
768
769                 /* Reinitialise the detector for the next block */
770                 for (i = 0; i < 4; i++) {
771                         goertzel_reset(&s->td.dtmf.row_out[i]);
772                         goertzel_reset(&s->td.dtmf.col_out[i]);
773                 }
774                 s->td.dtmf.energy = 0.0;
775                 s->td.dtmf.current_sample = 0;
776         }
777
778         if (squelch && mute.end) {
779                 if (mute.end > samples) {
780                         s->td.dtmf.mute_samples = mute.end - samples;
781                         mute.end = samples;
782                 }
783                 mute_fragment(dsp, &mute);
784         }
785
786         return (s->td.dtmf.current_hit);        /* return the debounced hit */
787 }
788
789 static int mf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[],
790                  int samples, int squelch, int relax)
791 {
792         float energy[6];
793         int best;
794         int second_best;
795         int i;
796         int j;
797         int sample;
798         int hit;
799         int limit;
800         fragment_t mute = {0, 0};
801
802         if (squelch && s->td.mf.mute_samples > 0) {
803                 mute.end = (s->td.mf.mute_samples < samples) ? s->td.mf.mute_samples : samples;
804                 s->td.mf.mute_samples -= mute.end;
805         }
806
807         hit = 0;
808         for (sample = 0;  sample < samples;  sample = limit) {
809                 /* 80 is optimised to meet the MF specs. */
810                 /* XXX So then why is MF_GSIZE defined as 120? */
811                 if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample)) {
812                         limit = sample + (MF_GSIZE - s->td.mf.current_sample);
813                 } else {
814                         limit = samples;
815                 }
816                 /* The following unrolled loop takes only 35% (rough estimate) of the 
817                    time of a rolled loop on the machine on which it was developed */
818                 for (j = sample;  j < limit;  j++) {
819                         /* With GCC 2.95, the following unrolled code seems to take about 35%
820                            (rough estimate) as long as a neat little 0-3 loop */
821                         goertzel_sample(s->td.mf.tone_out, amp[j]);
822                         goertzel_sample(s->td.mf.tone_out + 1, amp[j]);
823                         goertzel_sample(s->td.mf.tone_out + 2, amp[j]);
824                         goertzel_sample(s->td.mf.tone_out + 3, amp[j]);
825                         goertzel_sample(s->td.mf.tone_out + 4, amp[j]);
826                         goertzel_sample(s->td.mf.tone_out + 5, amp[j]);
827                 }
828                 s->td.mf.current_sample += (limit - sample);
829                 if (s->td.mf.current_sample < MF_GSIZE) {
830                         continue;
831                 }
832                 /* We're at the end of an MF detection block.  */
833                 /* Find the two highest energies. The spec says to look for
834                    two tones and two tones only. Taking this literally -ie
835                    only two tones pass the minimum threshold - doesn't work
836                    well. The sinc function mess, due to rectangular windowing
837                    ensure that! Find the two highest energies and ensure they
838                    are considerably stronger than any of the others. */
839                 energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
840                 energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
841                 if (energy[0] > energy[1]) {
842                         best = 0;
843                         second_best = 1;
844                 } else {
845                         best = 1;
846                         second_best = 0;
847                 }
848                 /*endif*/
849                 for (i = 2; i < 6; i++) {
850                         energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
851                         if (energy[i] >= energy[best]) {
852                                 second_best = best;
853                                 best = i;
854                         } else if (energy[i] >= energy[second_best]) {
855                                 second_best = i;
856                         }
857                 }
858                 /* Basic signal level and twist tests */
859                 hit = 0;
860                 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
861                     && energy[best] < energy[second_best]*BELL_MF_TWIST
862                     && energy[best] * BELL_MF_TWIST > energy[second_best]) {
863                         /* Relative peak test */
864                         hit = -1;
865                         for (i = 0; i < 6; i++) {
866                                 if (i != best && i != second_best) {
867                                         if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
868                                                 /* The best two are not clearly the best */
869                                                 hit = 0;
870                                                 break;
871                                         }
872                                 }
873                         }
874                 }
875                 if (hit) {
876                         /* Get the values into ascending order */
877                         if (second_best < best) {
878                                 i = best;
879                                 best = second_best;
880                                 second_best = i;
881                         }
882                         best = best * 5 + second_best - 1;
883                         hit = bell_mf_positions[best];
884                         /* Look for two successive similar results */
885                         /* The logic in the next test is:
886                            For KP we need 4 successive identical clean detects, with
887                            two blocks of something different preceeding it. For anything
888                            else we need two successive identical clean detects, with
889                            two blocks of something different preceeding it. */
890                         if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
891                            ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
892                             (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] &&
893                             hit != s->td.mf.hits[0]))) {
894                                 store_digit(s, hit);
895                         }
896                 }
897
898
899                 if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
900                         /* Two successive block without a hit terminate current digit */
901                         s->td.mf.current_hit = 0;
902                 }
903
904                 s->td.mf.hits[0] = s->td.mf.hits[1];
905                 s->td.mf.hits[1] = s->td.mf.hits[2];
906                 s->td.mf.hits[2] = s->td.mf.hits[3];
907                 s->td.mf.hits[3] = s->td.mf.hits[4];
908                 s->td.mf.hits[4] = hit;
909
910                 /* If we had a hit in this block, include it into mute fragment */
911                 if (squelch && hit) {
912                         if (mute.end < sample - MF_GSIZE) {
913                                 /* There is a gap between fragments */
914                                 mute_fragment(dsp, &mute);
915                                 mute.start = (sample > MF_GSIZE) ? (sample - MF_GSIZE) : 0;
916                         }
917                         mute.end = limit + DTMF_GSIZE;
918                 }
919
920                 /* Reinitialise the detector for the next block */
921                 for (i = 0;  i < 6;  i++) {
922                         goertzel_reset(&s->td.mf.tone_out[i]);
923                 }
924                 s->td.mf.current_sample = 0;
925         }
926
927         if (squelch && mute.end) {
928                 if (mute.end > samples) {
929                         s->td.mf.mute_samples = mute.end - samples;
930                         mute.end = samples;
931                 }
932                 mute_fragment(dsp, &mute);
933         }
934
935         return (s->td.mf.current_hit); /* return the debounced hit */
936 }
937
938 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
939 {
940         /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
941         /* Make sure absolute levels are high enough */
942         if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH)) {
943                 return 0;
944         }
945         /* Amplify ignored stuff */
946         i2 *= TONE_THRESH;
947         i1 *= TONE_THRESH;
948         e *= TONE_THRESH;
949         /* Check first tone */
950         if ((p1 < i1) || (p1 < i2) || (p1 < e)) {
951                 return 0;
952         }
953         /* And second */
954         if ((p2 < i1) || (p2 < i2) || (p2 < e)) {
955                 return 0;
956         }
957         /* Guess it's there... */
958         return 1;
959 }
960
961 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
962 {
963         int x;
964         int y;
965         int pass;
966         int newstate = DSP_TONE_STATE_SILENCE;
967         int res = 0;
968         while (len) {
969                 /* Take the lesser of the number of samples we need and what we have */
970                 pass = len;
971                 if (pass > dsp->gsamp_size - dsp->gsamps) {
972                         pass = dsp->gsamp_size - dsp->gsamps;
973                 }
974                 for (x = 0; x < pass; x++) {
975                         for (y = 0; y < dsp->freqcount; y++) {
976                                 goertzel_sample(&dsp->freqs[y], s[x]);
977                         }
978                         dsp->genergy += s[x] * s[x];
979                 }
980                 s += pass;
981                 dsp->gsamps += pass;
982                 len -= pass;
983                 if (dsp->gsamps == dsp->gsamp_size) {
984                         float hz[7];
985                         for (y = 0; y < 7; y++) {
986                                 hz[y] = goertzel_result(&dsp->freqs[y]);
987                         }
988                         switch (dsp->progmode) {
989                         case PROG_MODE_NA:
990                                 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
991                                         newstate = DSP_TONE_STATE_BUSY;
992                                 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
993                                         newstate = DSP_TONE_STATE_RINGING;
994                                 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
995                                         newstate = DSP_TONE_STATE_DIALTONE;
996                                 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
997                                         newstate = DSP_TONE_STATE_SPECIAL1;
998                                 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
999                                         /* End of SPECIAL1 or middle of SPECIAL2 */
1000                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL1 || dsp->tstate == DSP_TONE_STATE_SPECIAL2) {
1001                                                 newstate = DSP_TONE_STATE_SPECIAL2;
1002                                         }
1003                                 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
1004                                         /* End of SPECIAL2 or middle of SPECIAL3 */
1005                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL2 || dsp->tstate == DSP_TONE_STATE_SPECIAL3) {
1006                                                 newstate = DSP_TONE_STATE_SPECIAL3;
1007                                         }
1008                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1009                                         newstate = DSP_TONE_STATE_TALKING;
1010                                 } else {
1011                                         newstate = DSP_TONE_STATE_SILENCE;
1012                                 }
1013                                 break;
1014                         case PROG_MODE_CR:
1015                                 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
1016                                         newstate = DSP_TONE_STATE_RINGING;
1017                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1018                                         newstate = DSP_TONE_STATE_TALKING;
1019                                 } else {
1020                                         newstate = DSP_TONE_STATE_SILENCE;
1021                                 }
1022                                 break;
1023                         case PROG_MODE_UK:
1024                                 if (hz[HZ_400UK] > TONE_MIN_THRESH * TONE_THRESH) {
1025                                         newstate = DSP_TONE_STATE_HUNGUP;
1026                                 } else if (pair_there(hz[HZ_350UK], hz[HZ_440UK], hz[HZ_400UK], hz[HZ_400UK], dsp->genergy)) {
1027                                         newstate = DSP_TONE_STATE_DIALTONE;
1028                                 }
1029                                 break;
1030                         default:
1031                                 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
1032                         }
1033                         if (newstate == dsp->tstate) {
1034                                 dsp->tcount++;
1035                                 if (dsp->ringtimeout) {
1036                                         dsp->ringtimeout++;
1037                                 }
1038                                 switch (dsp->tstate) {
1039                                 case DSP_TONE_STATE_RINGING:
1040                                         if ((dsp->features & DSP_PROGRESS_RINGING) &&
1041                                             (dsp->tcount == THRESH_RING)) {
1042                                                 res = AST_CONTROL_RINGING;
1043                                                 dsp->ringtimeout = 1;
1044                                         }
1045                                         break;
1046                                 case DSP_TONE_STATE_BUSY:
1047                                         if ((dsp->features & DSP_PROGRESS_BUSY) &&
1048                                             (dsp->tcount == THRESH_BUSY)) {
1049                                                 res = AST_CONTROL_BUSY;
1050                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1051                                         }
1052                                         break;
1053                                 case DSP_TONE_STATE_TALKING:
1054                                         if ((dsp->features & DSP_PROGRESS_TALK) &&
1055                                             (dsp->tcount == THRESH_TALK)) {
1056                                                 res = AST_CONTROL_ANSWER;
1057                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1058                                         }
1059                                         break;
1060                                 case DSP_TONE_STATE_SPECIAL3:
1061                                         if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
1062                                             (dsp->tcount == THRESH_CONGESTION)) {
1063                                                 res = AST_CONTROL_CONGESTION;
1064                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1065                                         }
1066                                         break;
1067                                 case DSP_TONE_STATE_HUNGUP:
1068                                         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
1069                                             (dsp->tcount == THRESH_HANGUP)) {
1070                                                 res = AST_CONTROL_HANGUP;
1071                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1072                                         }
1073                                         break;
1074                                 }
1075                                 if (dsp->ringtimeout == THRESH_RING2ANSWER) {
1076                                         ast_debug(1, "Consider call as answered because of timeout after last ring\n");
1077                                         res = AST_CONTROL_ANSWER;
1078                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1079                                 }
1080                         } else {
1081                                 ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
1082                                 ast_debug(5, "Start state %d\n", newstate);
1083                                 dsp->tstate = newstate;
1084                                 dsp->tcount = 1;
1085                         }
1086
1087                         /* Reset goertzel */
1088                         for (x = 0; x < 7; x++) {
1089                                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1090                         }
1091                         dsp->gsamps = 0;
1092                         dsp->genergy = 0.0;
1093                 }
1094         }
1095
1096         return res;
1097 }
1098
1099 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1100 {
1101         if (inf->frametype != AST_FRAME_VOICE) {
1102                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1103                 return 0;
1104         }
1105         if (!ast_format_is_slinear(&inf->subclass.format)) {
1106                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1107                 return 0;
1108         }
1109         return __ast_dsp_call_progress(dsp, inf->data.ptr, inf->datalen / 2);
1110 }
1111
1112 static int __ast_dsp_silence_noise(struct ast_dsp *dsp, short *s, int len, int *totalsilence, int *totalnoise, int *frames_energy)
1113 {
1114         int accum;
1115         int x;
1116         int res = 0;
1117
1118         if (!len) {
1119                 return 0;
1120         }
1121         accum = 0;
1122         for (x = 0; x < len; x++) {
1123                 accum += abs(s[x]);
1124         }
1125         accum /= len;
1126         if (accum < dsp->threshold) {
1127                 /* Silent */
1128                 dsp->totalsilence += len / (dsp->sample_rate / 1000);
1129                 if (dsp->totalnoise) {
1130                         /* Move and save history */
1131                         memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicnoise[0]));
1132                         dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1133 /* we don't want to check for busydetect that frequently */
1134 #if 0
1135                         dsp->busymaybe = 1;
1136 #endif
1137                 }
1138                 dsp->totalnoise = 0;
1139                 res = 1;
1140         } else {
1141                 /* Not silent */
1142                 dsp->totalnoise += len / (dsp->sample_rate / 1000);
1143                 if (dsp->totalsilence) {
1144                         int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1145                         int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1146                         /* Move and save history */
1147                         memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicsilence[0]));
1148                         dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1149                         /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1150                         if (silence1 < silence2) {
1151                                 if (silence1 + silence1 * BUSY_PERCENT / 100 >= silence2) {
1152                                         dsp->busymaybe = 1;
1153                                 } else {
1154                                         dsp->busymaybe = 0;
1155                                 }
1156                         } else {
1157                                 if (silence1 - silence1 * BUSY_PERCENT / 100 <= silence2) {
1158                                         dsp->busymaybe = 1;
1159                                 } else {
1160                                         dsp->busymaybe = 0;
1161                                 }
1162                         }
1163                 }
1164                 dsp->totalsilence = 0;
1165         }
1166         if (totalsilence) {
1167                 *totalsilence = dsp->totalsilence;
1168         }
1169         if (totalnoise) {
1170                 *totalnoise = dsp->totalnoise;
1171         }
1172         if (frames_energy) {
1173                 *frames_energy = accum;
1174         }
1175         return res;
1176 }
1177
1178 int ast_dsp_busydetect(struct ast_dsp *dsp)
1179 {
1180         int res = 0, x;
1181 #ifndef BUSYDETECT_TONEONLY
1182         int avgsilence = 0, hitsilence = 0;
1183 #endif
1184         int avgtone = 0, hittone = 0;
1185
1186         /* if we have a 4 length pattern, the way busymaybe is set doesn't help us. */
1187         if (dsp->busy_cadence.length != 4) {
1188                 if (!dsp->busymaybe) {
1189                         return res;
1190                 }
1191         }
1192
1193         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1194 #ifndef BUSYDETECT_TONEONLY
1195                 avgsilence += dsp->historicsilence[x];
1196 #endif
1197                 avgtone += dsp->historicnoise[x];
1198         }
1199 #ifndef BUSYDETECT_TONEONLY
1200         avgsilence /= dsp->busycount;
1201 #endif
1202         avgtone /= dsp->busycount;
1203         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1204 #ifndef BUSYDETECT_TONEONLY
1205                 if (avgsilence > dsp->historicsilence[x]) {
1206                         if (avgsilence - (avgsilence * BUSY_PERCENT / 100) <= dsp->historicsilence[x]) {
1207                                 hitsilence++;
1208                         }
1209                 } else {
1210                         if (avgsilence + (avgsilence * BUSY_PERCENT / 100) >= dsp->historicsilence[x]) {
1211                                 hitsilence++;
1212                         }
1213                 }
1214 #endif
1215                 if (avgtone > dsp->historicnoise[x]) {
1216                         if (avgtone - (avgtone * BUSY_PERCENT / 100) <= dsp->historicnoise[x]) {
1217                                 hittone++;
1218                         }
1219                 } else {
1220                         if (avgtone + (avgtone * BUSY_PERCENT / 100) >= dsp->historicnoise[x]) {
1221                                 hittone++;
1222                         }
1223                 }
1224         }
1225 #ifndef BUSYDETECT_TONEONLY
1226         if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) &&
1227             (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) &&
1228             (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1229 #else
1230         if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1231 #endif
1232 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1233                 if (avgtone > avgsilence) {
1234                         if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence) {
1235                                 res = 1;
1236                         }
1237                 } else {
1238                         if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence) {
1239                                 res = 1;
1240                         }
1241                 }
1242 #else
1243                 res = 1;
1244 #endif
1245         }
1246
1247         /* If we have a 4-length pattern, we can go ahead and just check it in a different way. */
1248         if (dsp->busy_cadence.length == 4) {
1249                 int x;
1250                 int errors = 0;
1251                 int errors_max = ((4 * dsp->busycount) / 100.0) * BUSY_PAT_PERCENT;
1252
1253                 for (x = DSP_HISTORY - (dsp->busycount); x < DSP_HISTORY; x += 2) {
1254                         int temp_error;
1255                         temp_error = abs(dsp->historicnoise[x] - dsp->busy_cadence.pattern[0]);
1256                         if ((temp_error * 100) / dsp->busy_cadence.pattern[0] > BUSY_PERCENT) {
1257                                 errors++;
1258                         }
1259
1260                         temp_error = abs(dsp->historicnoise[x + 1] - dsp->busy_cadence.pattern[2]);
1261                         if ((temp_error * 100) / dsp->busy_cadence.pattern[2] > BUSY_PERCENT) {
1262                                 errors++;
1263                         }
1264
1265                         temp_error = abs(dsp->historicsilence[x] - dsp->busy_cadence.pattern[1]);
1266                         if ((temp_error * 100) / dsp->busy_cadence.pattern[1] > BUSY_PERCENT) {
1267                                 errors++;
1268                         }
1269
1270                         temp_error = abs(dsp->historicsilence[x + 1] - dsp->busy_cadence.pattern[3]);
1271                         if ((temp_error * 100) / dsp->busy_cadence.pattern[3] > BUSY_PERCENT) {
1272                                 errors++;
1273                         }
1274                 }
1275
1276                 ast_debug(5, "errors = %d  max = %d\n", errors, errors_max);
1277
1278                 if (errors <= errors_max) {
1279                         return 1;
1280                 }
1281         }
1282
1283         /* If we know the expected busy tone length, check we are in the range */
1284         if (res && (dsp->busy_cadence.pattern[0] > 0)) {
1285                 if (abs(avgtone - dsp->busy_cadence.pattern[0]) > MAX(dsp->busy_cadence.pattern[0]*BUSY_PAT_PERCENT/100, 20)) {
1286 #ifdef BUSYDETECT_DEBUG
1287                         ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
1288                                 avgtone, dsp->busy_cadence.pattern[0]);
1289 #endif
1290                         res = 0;
1291                 }
1292         }
1293 #ifndef BUSYDETECT_TONEONLY
1294         /* If we know the expected busy tone silent-period length, check we are in the range */
1295         if (res && (dsp->busy_cadence.pattern[1] > 0)) {
1296                 if (abs(avgsilence - dsp->busy_cadence.pattern[1]) > MAX(dsp->busy_cadence.pattern[1]*BUSY_PAT_PERCENT/100, 20)) {
1297 #ifdef BUSYDETECT_DEBUG
1298                 ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
1299                         avgsilence, dsp->busy_cadence.pattern[1]);
1300 #endif
1301                         res = 0;
1302                 }
1303         }
1304 #endif
1305 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
1306         if (res) {
1307                 ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1308         } else {
1309                 ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1310         }
1311 #endif
1312         return res;
1313 }
1314
1315 static int ast_dsp_silence_noise_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *total, int *frames_energy, int noise)
1316 {
1317         short *s;
1318         int len;
1319         int x;
1320         unsigned char *odata;
1321
1322         if (!f) {
1323                 return 0;
1324         }
1325
1326         if (f->frametype != AST_FRAME_VOICE) {
1327                 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1328                 return 0;
1329         }
1330         if (!ast_format_is_slinear(&f->subclass.format)) {
1331                 odata = f->data.ptr;
1332                 len = f->datalen;
1333                 switch (f->subclass.format.id) {
1334                         case AST_FORMAT_ULAW:
1335                                 s = alloca(len * 2);
1336                                 for (x = 0;x < len; x++) {
1337                                         s[x] = AST_MULAW(odata[x]);
1338                                 }
1339                                 break;
1340                         case AST_FORMAT_ALAW:
1341                                 s = alloca(len * 2);
1342                                 for (x = 0;x < len; x++) {
1343                                         s[x] = AST_ALAW(odata[x]);
1344                                 }
1345                                 break;
1346                         default:
1347                                 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear, alaw or ulaw frames :(\n");
1348                         return 0;
1349                 }
1350         } else {
1351                 s = f->data.ptr;
1352                 len = f->datalen/2;
1353         }
1354         if (noise) {
1355                 return __ast_dsp_silence_noise(dsp, s, len, NULL, total, frames_energy);
1356         } else {
1357                 return __ast_dsp_silence_noise(dsp, s, len, total, NULL, frames_energy);
1358         }
1359 }
1360
1361 int ast_dsp_silence_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence, int *frames_energy)
1362 {
1363         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, frames_energy, 0);
1364 }
1365
1366 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1367 {
1368         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, NULL, 0);
1369 }
1370
1371 int ast_dsp_noise(struct ast_dsp *dsp, struct ast_frame *f, int *totalnoise)
1372 {
1373         return ast_dsp_silence_noise_with_energy(dsp, f, totalnoise, NULL, 1);
1374 }
1375
1376
1377 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1378 {
1379         int silence;
1380         int res;
1381         int digit = 0, fax_digit = 0;
1382         int x;
1383         short *shortdata;
1384         unsigned char *odata;
1385         int len;
1386         struct ast_frame *outf = NULL;
1387
1388         if (!af) {
1389                 return NULL;
1390         }
1391         if (af->frametype != AST_FRAME_VOICE) {
1392                 return af;
1393         }
1394
1395         odata = af->data.ptr;
1396         len = af->datalen;
1397         /* Make sure we have short data */
1398         if (ast_format_is_slinear(&af->subclass.format)) {
1399                 shortdata = af->data.ptr;
1400                 len = af->datalen / 2;
1401         } else {
1402                 switch (af->subclass.format.id) {
1403                 case AST_FORMAT_ULAW:
1404                 case AST_FORMAT_TESTLAW:
1405                         shortdata = alloca(af->datalen * 2);
1406                         for (x = 0;x < len; x++) {
1407                                 shortdata[x] = AST_MULAW(odata[x]);
1408                         }
1409                         break;
1410                 case AST_FORMAT_ALAW:
1411                         shortdata = alloca(af->datalen * 2);
1412                         for (x = 0; x < len; x++) {
1413                                 shortdata[x] = AST_ALAW(odata[x]);
1414                         }
1415                         break;
1416                 default:
1417                         /*Display warning only once. Otherwise you would get hundreds of warnings every second */
1418                         if (dsp->display_inband_dtmf_warning)
1419                                 ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(&af->subclass.format));
1420                         dsp->display_inband_dtmf_warning = 0;
1421                         return af;
1422                 }
1423         }
1424
1425         /* Initially we do not want to mute anything */
1426         dsp->mute_fragments = 0;
1427
1428         /* Need to run the silence detection stuff for silence suppression and busy detection */
1429         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) || (dsp->features & DSP_FEATURE_BUSY_DETECT)) {
1430                 res = __ast_dsp_silence_noise(dsp, shortdata, len, &silence, NULL, NULL);
1431         }
1432
1433         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1434                 memset(&dsp->f, 0, sizeof(dsp->f));
1435                 dsp->f.frametype = AST_FRAME_NULL;
1436                 ast_frfree(af);
1437                 return ast_frisolate(&dsp->f);
1438         }
1439         if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1440                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1441                 memset(&dsp->f, 0, sizeof(dsp->f));
1442                 dsp->f.frametype = AST_FRAME_CONTROL;
1443                 dsp->f.subclass.integer = AST_CONTROL_BUSY;
1444                 ast_frfree(af);
1445                 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", chan->name);
1446                 return ast_frisolate(&dsp->f);
1447         }
1448
1449         if ((dsp->features & DSP_FEATURE_FAX_DETECT)) {
1450                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CNG) && tone_detect(dsp, &dsp->cng_tone_state, shortdata, len)) {
1451                         fax_digit = 'f';
1452                 }
1453
1454                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CED) && tone_detect(dsp, &dsp->ced_tone_state, shortdata, len)) {
1455                         fax_digit = 'e';
1456                 }
1457         }
1458
1459         if (dsp->features & (DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_BUSY_DETECT)) {
1460                 if (dsp->digitmode & DSP_DIGITMODE_MF) {
1461                         digit = mf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1462                 } else {
1463                         digit = dtmf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1464                 }
1465
1466                 if (dsp->digit_state.current_digits) {
1467                         int event = 0, event_len = 0;
1468                         char event_digit = 0;
1469
1470                         if (!dsp->dtmf_began) {
1471                                 /* We have not reported DTMF_BEGIN for anything yet */
1472
1473                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1474                                         event = AST_FRAME_DTMF_BEGIN;
1475                                         event_digit = dsp->digit_state.digits[0];
1476                                 }
1477                                 dsp->dtmf_began = 1;
1478
1479                         } else if (dsp->digit_state.current_digits > 1 || digit != dsp->digit_state.digits[0]) {
1480                                 /* Digit changed. This means digit we have reported with DTMF_BEGIN ended */
1481                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1482                                         event = AST_FRAME_DTMF_END;
1483                                         event_digit = dsp->digit_state.digits[0];
1484                                         event_len = dsp->digit_state.digitlen[0] * 1000 / dsp->sample_rate;
1485                                 }
1486                                 memmove(&dsp->digit_state.digits[0], &dsp->digit_state.digits[1], dsp->digit_state.current_digits);
1487                                 memmove(&dsp->digit_state.digitlen[0], &dsp->digit_state.digitlen[1], dsp->digit_state.current_digits * sizeof(dsp->digit_state.digitlen[0]));
1488                                 dsp->digit_state.current_digits--;
1489                                 dsp->dtmf_began = 0;
1490
1491                                 if (dsp->features & DSP_FEATURE_BUSY_DETECT) {
1492                                         /* Reset Busy Detector as we have some confirmed activity */
1493                                         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1494                                         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1495                                         ast_debug(1, "DTMF Detected - Reset busydetector\n");
1496                                 }
1497                         }
1498
1499                         if (event) {
1500                                 memset(&dsp->f, 0, sizeof(dsp->f));
1501                                 dsp->f.frametype = event;
1502                                 dsp->f.subclass.integer = event_digit;
1503                                 dsp->f.len = event_len;
1504                                 outf = &dsp->f;
1505                                 goto done;
1506                         }
1507                 }
1508         }
1509
1510         if (fax_digit) {
1511                 /* Fax was detected - digit is either 'f' or 'e' */
1512
1513                 memset(&dsp->f, 0, sizeof(dsp->f));
1514                 dsp->f.frametype = AST_FRAME_DTMF;
1515                 dsp->f.subclass.integer = fax_digit;
1516                 outf = &dsp->f;
1517                 goto done;
1518         }
1519
1520         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1521                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1522                 if (res) {
1523                         switch (res) {
1524                         case AST_CONTROL_ANSWER:
1525                         case AST_CONTROL_BUSY:
1526                         case AST_CONTROL_RINGING:
1527                         case AST_CONTROL_CONGESTION:
1528                         case AST_CONTROL_HANGUP:
1529                                 memset(&dsp->f, 0, sizeof(dsp->f));
1530                                 dsp->f.frametype = AST_FRAME_CONTROL;
1531                                 dsp->f.subclass.integer = res;
1532                                 dsp->f.src = "dsp_progress";
1533                                 if (chan) {
1534                                         ast_queue_frame(chan, &dsp->f);
1535                                 }
1536                                 break;
1537                         default:
1538                                 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1539                         }
1540                 }
1541         } else if ((dsp->features & DSP_FEATURE_WAITDIALTONE)) {
1542                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1543         }
1544
1545 done:
1546         /* Mute fragment of the frame */
1547         for (x = 0; x < dsp->mute_fragments; x++) {
1548                 memset(shortdata + dsp->mute_data[x].start, 0, sizeof(int16_t) * (dsp->mute_data[x].end - dsp->mute_data[x].start));
1549         }
1550
1551         switch (af->subclass.format.id) {
1552         case AST_FORMAT_ULAW:
1553                 for (x = 0; x < len; x++) {
1554                         odata[x] = AST_LIN2MU((unsigned short) shortdata[x]);
1555                 }
1556                 break;
1557         case AST_FORMAT_ALAW:
1558                 for (x = 0; x < len; x++) {
1559                         odata[x] = AST_LIN2A((unsigned short) shortdata[x]);
1560                 }
1561                 /* fall through */
1562         default:
1563                 break;
1564         }
1565
1566         if (outf) {
1567                 if (chan) {
1568                         ast_queue_frame(chan, af);
1569                 }
1570                 ast_frfree(af);
1571                 return ast_frisolate(outf);
1572         } else {
1573                 return af;
1574         }
1575 }
1576
1577 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1578 {
1579         int max = 0;
1580         int x;
1581
1582         dsp->gsamp_size = modes[dsp->progmode].size;
1583         dsp->gsamps = 0;
1584         for (x = 0; x < ARRAY_LEN(modes[dsp->progmode].freqs); x++) {
1585                 if (modes[dsp->progmode].freqs[x]) {
1586                         goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->gsamp_size, dsp->sample_rate);
1587                         max = x + 1;
1588                 }
1589         }
1590         dsp->freqcount = max;
1591         dsp->ringtimeout= 0;
1592 }
1593
1594 unsigned int ast_dsp_get_sample_rate(const struct ast_dsp *dsp)
1595 {
1596         return dsp->sample_rate;
1597 }
1598
1599 static struct ast_dsp *__ast_dsp_new(unsigned int sample_rate)
1600 {
1601         struct ast_dsp *dsp;
1602
1603         if ((dsp = ast_calloc(1, sizeof(*dsp)))) {
1604                 dsp->threshold = DEFAULT_THRESHOLD;
1605                 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1606                 dsp->busycount = DSP_HISTORY;
1607                 dsp->digitmode = DSP_DIGITMODE_DTMF;
1608                 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1609                 dsp->sample_rate = sample_rate;
1610                 /* Initialize digit detector */
1611                 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF, dsp->sample_rate);
1612                 dsp->display_inband_dtmf_warning = 1;
1613                 /* Initialize initial DSP progress detect parameters */
1614                 ast_dsp_prog_reset(dsp);
1615                 /* Initialize fax detector */
1616                 ast_fax_detect_init(dsp);
1617         }
1618         return dsp;
1619 }
1620
1621 struct ast_dsp *ast_dsp_new(void)
1622 {
1623         return __ast_dsp_new(DEFAULT_SAMPLE_RATE);
1624 }
1625
1626 struct ast_dsp *ast_dsp_new_with_rate(unsigned int sample_rate)
1627 {
1628         return __ast_dsp_new(sample_rate);
1629 }
1630
1631 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1632 {
1633         dsp->features = features;
1634         if (!(features & DSP_FEATURE_DIGIT_DETECT)) {
1635                 dsp->display_inband_dtmf_warning = 0;
1636         }
1637 }
1638
1639 void ast_dsp_free(struct ast_dsp *dsp)
1640 {
1641         ast_free(dsp);
1642 }
1643
1644 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1645 {
1646         dsp->threshold = threshold;
1647 }
1648
1649 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1650 {
1651         if (cadences < 4) {
1652                 cadences = 4;
1653         }
1654         if (cadences > DSP_HISTORY) {
1655                 cadences = DSP_HISTORY;
1656         }
1657         dsp->busycount = cadences;
1658 }
1659
1660 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, const struct ast_dsp_busy_pattern *cadence)
1661 {
1662         dsp->busy_cadence = *cadence;
1663         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);
1664 }
1665
1666 void ast_dsp_digitreset(struct ast_dsp *dsp)
1667 {
1668         int i;
1669
1670         dsp->dtmf_began = 0;
1671         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1672                 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1673                 /* Reinitialise the detector for the next block */
1674                 for (i = 0;  i < 6;  i++) {
1675                         goertzel_reset(&s->tone_out[i]);
1676                 }
1677                 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = s->current_hit = 0;
1678                 s->current_sample = 0;
1679         } else {
1680                 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1681                 /* Reinitialise the detector for the next block */
1682                 for (i = 0;  i < 4;  i++) {
1683                         goertzel_reset(&s->row_out[i]);
1684                         goertzel_reset(&s->col_out[i]);
1685                 }
1686                 s->lasthit = s->current_hit = 0;
1687                 s->energy = 0.0;
1688                 s->current_sample = 0;
1689                 s->hits = 0;
1690                 s->misses = 0;
1691         }
1692
1693         dsp->digit_state.digits[0] = '\0';
1694         dsp->digit_state.current_digits = 0;
1695 }
1696
1697 void ast_dsp_reset(struct ast_dsp *dsp)
1698 {
1699         int x;
1700
1701         dsp->totalsilence = 0;
1702         dsp->gsamps = 0;
1703         for (x = 0; x < 4; x++) {
1704                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1705         }
1706         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1707         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1708         dsp->ringtimeout= 0;
1709 }
1710
1711 int ast_dsp_set_digitmode(struct ast_dsp *dsp, int digitmode)
1712 {
1713         int new;
1714         int old;
1715
1716         old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1717         new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1718         if (old != new) {
1719                 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1720                 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF, dsp->sample_rate);
1721         }
1722         dsp->digitmode = digitmode;
1723         return 0;
1724 }
1725
1726 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1727 {
1728         if (dsp->faxmode != faxmode) {
1729                 dsp->faxmode = faxmode;
1730                 ast_fax_detect_init(dsp);
1731         }
1732         return 0;
1733 }
1734
1735 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1736 {
1737         int x;
1738
1739         for (x = 0; x < ARRAY_LEN(aliases); x++) {
1740                 if (!strcasecmp(aliases[x].name, zone)) {
1741                         dsp->progmode = aliases[x].mode;
1742                         ast_dsp_prog_reset(dsp);
1743                         return 0;
1744                 }
1745         }
1746         return -1;
1747 }
1748
1749 int ast_dsp_was_muted(struct ast_dsp *dsp)
1750 {
1751         return (dsp->mute_fragments > 0);
1752 }
1753
1754 int ast_dsp_get_tstate(struct ast_dsp *dsp)
1755 {
1756         return dsp->tstate;
1757 }
1758
1759 int ast_dsp_get_tcount(struct ast_dsp *dsp)
1760 {
1761         return dsp->tcount;
1762 }
1763
1764 static int _dsp_init(int reload)
1765 {
1766         struct ast_config *cfg;
1767         struct ast_variable *v;
1768         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1769         int cfg_threshold;
1770
1771         if ((cfg = ast_config_load2(CONFIG_FILE_NAME, "dsp", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
1772                 return 0;
1773         }
1774
1775         thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1776
1777         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
1778                 return 0;
1779         }
1780
1781         for (v = ast_variable_browse(cfg, "default"); v; v = v->next) {
1782                 if (!strcasecmp(v->name, "silencethreshold")) {
1783                         if (sscanf(v->value, "%30d", &cfg_threshold) < 1) {
1784                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1785                         } else if (cfg_threshold < 0) {
1786                                 ast_log(LOG_WARNING, "Invalid silence threshold '%d' specified, using default\n", cfg_threshold);
1787                         } else {
1788                                 thresholds[THRESHOLD_SILENCE] = cfg_threshold;
1789                         }
1790                 }
1791         }
1792         ast_config_destroy(cfg);
1793
1794         return 0;
1795 }
1796
1797 int ast_dsp_get_threshold_from_settings(enum threshold which)
1798 {
1799         return thresholds[which];
1800 }
1801
1802 int ast_dsp_init(void)
1803 {
1804         return _dsp_init(0);
1805 }
1806
1807 int ast_dsp_reload(void)
1808 {
1809         return _dsp_init(1);
1810 }