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