dsp.c ast_dsp_call_progress use local short variable in loop, plus other cleanup
[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      2
209 /* How many successive misses needed to consider end of a digit */
210 #define DTMF_MISSES_TO_END      3
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 } goertzel_state_t;
226
227 typedef struct {
228         int value;
229         int power;
230 } goertzel_result_t;
231
232 typedef struct
233 {
234         int freq;
235         int block_size;
236         int squelch;            /* Remove (squelch) tone */
237         goertzel_state_t tone;
238         float energy;           /* Accumulated energy of the current block */
239         int samples_pending;    /* Samples remain to complete the current block */
240         int mute_samples;       /* How many additional samples needs to be muted to suppress already detected tone */
241
242         int hits_required;      /* How many successive blocks with tone we are looking for */
243         float threshold;        /* Energy of the tone relative to energy from all other signals to consider a hit */
244
245         int hit_count;          /* How many successive blocks we consider tone present */
246         int last_hit;           /* Indicates if the last processed block was a hit */
247
248 } tone_detect_state_t;
249
250 typedef struct
251 {
252         goertzel_state_t row_out[4];
253         goertzel_state_t col_out[4];
254         int hits_to_begin;              /* How many successive hits needed to consider begin of a digit */
255         int misses_to_end;              /* How many successive misses needed to consider end of a digit */
256         int hits;                       /* How many successive hits we have seen already */
257         int misses;                     /* How many successive misses we have seen already */
258         int lasthit;
259         int current_hit;
260         float energy;
261         int current_sample;
262         int mute_samples;
263 } dtmf_detect_state_t;
264
265 typedef struct
266 {
267         goertzel_state_t tone_out[6];
268         int current_hit;
269         int hits[5];
270         int current_sample;
271         int mute_samples;
272 } mf_detect_state_t;
273
274 typedef struct
275 {
276         char digits[MAX_DTMF_DIGITS + 1];
277         int digitlen[MAX_DTMF_DIGITS + 1];
278         int current_digits;
279         int detected_digits;
280         int lost_digits;
281
282         union {
283                 dtmf_detect_state_t dtmf;
284                 mf_detect_state_t mf;
285         } td;
286 } digit_detect_state_t;
287
288 static const float dtmf_row[] = {
289         697.0,  770.0,  852.0,  941.0
290 };
291 static const float dtmf_col[] = {
292         1209.0, 1336.0, 1477.0, 1633.0
293 };
294 static const float mf_tones[] = {
295         700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
296 };
297 static const char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
298 static const char bell_mf_positions[] = "1247C-358A--69*---0B----#";
299 static int thresholds[THRESHOLD_MAX];
300
301 static inline void goertzel_sample(goertzel_state_t *s, short sample)
302 {
303         int v1;
304
305         v1 = s->v2;
306         s->v2 = s->v3;
307
308         s->v3 = (s->fac * s->v2) >> 15;
309         s->v3 = s->v3 - v1 + (sample >> s->chunky);
310         if (abs(s->v3) > 32768) {
311                 s->chunky++;
312                 s->v3 = s->v3 >> 1;
313                 s->v2 = s->v2 >> 1;
314         }
315 }
316
317 static inline void goertzel_update(goertzel_state_t *s, short *samps, int count)
318 {
319         int i;
320
321         for (i = 0; i < count; i++) {
322                 goertzel_sample(s, samps[i]);
323         }
324 }
325
326
327 static inline float goertzel_result(goertzel_state_t *s)
328 {
329         goertzel_result_t r;
330         r.value = (s->v3 * s->v3) + (s->v2 * s->v2);
331         r.value -= ((s->v2 * s->v3) >> 15) * s->fac;
332         r.power = s->chunky * 2;
333         return (float)r.value * (float)(1 << r.power);
334 }
335
336 static inline void goertzel_init(goertzel_state_t *s, float freq, unsigned int sample_rate)
337 {
338         s->v2 = s->v3 = s->chunky = 0.0;
339         s->fac = (int)(32768.0 * 2.0 * cos(2.0 * M_PI * freq / sample_rate));
340 }
341
342 static inline void goertzel_reset(goertzel_state_t *s)
343 {
344         s->v2 = s->v3 = s->chunky = 0.0;
345 }
346
347 typedef struct {
348         int start;
349         int end;
350 } fragment_t;
351
352 /* Note on tone suppression (squelching). Individual detectors (DTMF/MF/generic tone)
353  * report fragments of the frame in which detected tone resides and which needs
354  * to be "muted" in order to suppress the tone. To mark fragment for muting,
355  * detectors call mute_fragment passing fragment_t there. Multiple fragments
356  * can be marked and ast_dsp_process later will mute all of them.
357  *
358  * Note: When tone starts in the middle of a Goertzel block, it won't be properly
359  * detected in that block, only in the next. If we only mute the next block
360  * where tone is actually detected, the user will still hear beginning
361  * of the tone in preceeding block. This is why we usually want to mute some amount
362  * of samples preceeding and following the block where tone was detected.
363 */
364
365 struct ast_dsp {
366         struct ast_frame f;
367         int threshold;
368         int totalsilence;
369         int totalnoise;
370         int features;
371         int ringtimeout;
372         int busymaybe;
373         int busycount;
374         struct ast_dsp_busy_pattern busy_cadence;
375         int historicnoise[DSP_HISTORY];
376         int historicsilence[DSP_HISTORY];
377         goertzel_state_t freqs[7];
378         int freqcount;
379         int gsamps;
380         enum gsamp_size gsamp_size;
381         enum prog_mode progmode;
382         int tstate;
383         int tcount;
384         int digitmode;
385         int faxmode;
386         int dtmf_began;
387         int display_inband_dtmf_warning;
388         float genergy;
389         int mute_fragments;
390         unsigned int sample_rate;
391         fragment_t mute_data[5];
392         digit_detect_state_t digit_state;
393         tone_detect_state_t cng_tone_state;
394         tone_detect_state_t ced_tone_state;
395 };
396
397 static void mute_fragment(struct ast_dsp *dsp, fragment_t *fragment)
398 {
399         if (dsp->mute_fragments >= ARRAY_LEN(dsp->mute_data)) {
400                 ast_log(LOG_ERROR, "Too many fragments to mute. Ignoring\n");
401                 return;
402         }
403
404         dsp->mute_data[dsp->mute_fragments++] = *fragment;
405 }
406
407 static void ast_tone_detect_init(tone_detect_state_t *s, int freq, int duration, int amp, unsigned int sample_rate)
408 {
409         int duration_samples;
410         float x;
411         int periods_in_block;
412
413         s->freq = freq;
414
415         /* Desired tone duration in samples */
416         duration_samples = duration * sample_rate / 1000;
417         /* We want to allow 10% deviation of tone duration */
418         duration_samples = duration_samples * 9 / 10;
419
420         /* If we want to remove tone, it is important to have block size not
421            to exceed frame size. Otherwise by the moment tone is detected it is too late
422            to squelch it from previous frames. Block size is 20ms at the given sample rate.*/
423         s->block_size = (20 * sample_rate) / 1000;
424
425         periods_in_block = s->block_size * freq / sample_rate;
426
427         /* Make sure we will have at least 5 periods at target frequency for analisys.
428            This may make block larger than expected packet and will make squelching impossible
429            but at least we will be detecting the tone */
430         if (periods_in_block < 5) {
431                 periods_in_block = 5;
432         }
433
434         /* Now calculate final block size. It will contain integer number of periods */
435         s->block_size = periods_in_block * sample_rate / freq;
436
437         /* tone_detect is currently only used to detect fax tones and we
438            do not need squelching the fax tones */
439         s->squelch = 0;
440
441         /* Account for the first and the last block to be incomplete
442            and thus no tone will be detected in them */
443         s->hits_required = (duration_samples - (s->block_size - 1)) / s->block_size;
444
445         goertzel_init(&s->tone, freq, sample_rate);
446
447         s->samples_pending = s->block_size;
448         s->hit_count = 0;
449         s->last_hit = 0;
450         s->energy = 0.0;
451
452         /* We want tone energy to be amp decibels above the rest of the signal (the noise).
453            According to Parseval's theorem the energy computed in time domain equals to energy
454            computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
455            from the energy in the time domain we will get energy of the remaining signal (without the tone
456            we are detecting). We will be checking that
457                 10*log(Ew / (Et - Ew)) > amp
458            Calculate threshold so that we will be actually checking
459                 Ew > Et * threshold
460         */
461
462         x = pow(10.0, amp / 10.0);
463         s->threshold = x / (x + 1);
464
465         ast_debug(1, "Setup tone %d Hz, %d ms, block_size=%d, hits_required=%d\n", freq, duration, s->block_size, s->hits_required);
466 }
467
468 static void ast_fax_detect_init(struct ast_dsp *s)
469 {
470         ast_tone_detect_init(&s->cng_tone_state, FAX_TONE_CNG_FREQ, FAX_TONE_CNG_DURATION, FAX_TONE_CNG_DB, s->sample_rate);
471         ast_tone_detect_init(&s->ced_tone_state, FAX_TONE_CED_FREQ, FAX_TONE_CED_DURATION, FAX_TONE_CED_DB, s->sample_rate);
472         if (s->faxmode & DSP_FAXMODE_DETECT_SQUELCH) {
473                 s->cng_tone_state.squelch = 1;
474                 s->ced_tone_state.squelch = 1;
475         }
476
477 }
478
479 static void ast_dtmf_detect_init(dtmf_detect_state_t *s, unsigned int sample_rate)
480 {
481         int i;
482
483         for (i = 0; i < 4; i++) {
484                 goertzel_init(&s->row_out[i], dtmf_row[i], sample_rate);
485                 goertzel_init(&s->col_out[i], dtmf_col[i], sample_rate);
486         }
487         s->lasthit = 0;
488         s->current_hit = 0;
489         s->energy = 0.0;
490         s->current_sample = 0;
491         s->hits = 0;
492         s->misses = 0;
493
494         s->hits_to_begin = DTMF_HITS_TO_BEGIN;
495         s->misses_to_end = DTMF_MISSES_TO_END;
496 }
497
498 static void ast_mf_detect_init(mf_detect_state_t *s, unsigned int sample_rate)
499 {
500         int i;
501
502         for (i = 0; i < 6; i++) {
503                 goertzel_init(&s->tone_out[i], mf_tones[i], sample_rate);
504         }
505         s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
506         s->current_sample = 0;
507         s->current_hit = 0;
508 }
509
510 static void ast_digit_detect_init(digit_detect_state_t *s, int mf, unsigned int sample_rate)
511 {
512         s->current_digits = 0;
513         s->detected_digits = 0;
514         s->lost_digits = 0;
515         s->digits[0] = '\0';
516
517         if (mf) {
518                 ast_mf_detect_init(&s->td.mf, sample_rate);
519         } else {
520                 ast_dtmf_detect_init(&s->td.dtmf, sample_rate);
521         }
522 }
523
524 static int tone_detect(struct ast_dsp *dsp, tone_detect_state_t *s, int16_t *amp, int samples)
525 {
526         float tone_energy;
527         int i;
528         int hit = 0;
529         int limit;
530         int res = 0;
531         int16_t *ptr;
532         short samp;
533         int start, end;
534         fragment_t mute = {0, 0};
535
536         if (s->squelch && s->mute_samples > 0) {
537                 mute.end = (s->mute_samples < samples) ? s->mute_samples : samples;
538                 s->mute_samples -= mute.end;
539         }
540
541         for (start = 0; start < samples; start = end) {
542                 /* Process in blocks. */
543                 limit = samples - start;
544                 if (limit > s->samples_pending) {
545                         limit = s->samples_pending;
546                 }
547                 end = start + limit;
548
549                 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
550                         samp = *ptr;
551                         /* signed 32 bit int should be enough to square any possible signed 16 bit value */
552                         s->energy += (int32_t) samp * (int32_t) samp;
553
554                         goertzel_sample(&s->tone, samp);
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         int i;
648         int j;
649         int sample;
650         short samp;
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                         samp = amp[j];
674                         s->td.dtmf.energy += (int32_t) samp * (int32_t) samp;
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, samp);
678                         goertzel_sample(s->td.dtmf.col_out, samp);
679                         goertzel_sample(s->td.dtmf.row_out + 1, samp);
680                         goertzel_sample(s->td.dtmf.col_out + 1, samp);
681                         goertzel_sample(s->td.dtmf.row_out + 2, samp);
682                         goertzel_sample(s->td.dtmf.col_out + 2, samp);
683                         goertzel_sample(s->td.dtmf.row_out + 3, samp);
684                         goertzel_sample(s->td.dtmf.col_out + 3, samp);
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 /*
729  * Adapted from ETSI ES 201 235-3 V1.3.1 (2006-03)
730  * (40ms reference is tunable with hits_to_begin and misses_to_end)
731  * each hit/miss is 12.75ms with DTMF_GSIZE at 102
732  *
733  * Character recognition: When not DRC *(1) and then
734  *      Shall exist VSC > 40 ms (hits_to_begin)
735  *      May exist 20 ms <= VSC <= 40 ms
736  *      Shall not exist VSC < 20 ms
737  *
738  * Character recognition: When DRC and then
739  *      Shall cease Not VSC > 40 ms (misses_to_end)
740  *      May cease 20 ms >= Not VSC >= 40 ms
741  *      Shall not cease Not VSC < 20 ms
742  *
743  * *(1) or optionally a different digit recognition condition
744  *
745  * Legend: VSC The continuous existence of a valid signal condition.
746  *      Not VSC The continuous non-existence of valid signal condition.
747  *      DRC The existence of digit recognition condition.
748  *      Not DRC The non-existence of digit recognition condition.
749  */
750
751 /*
752  * Example: hits_to_begin=2 misses_to_end=3
753  * -------A last_hit=A hits=0&1
754  * ------AA hits=2 current_hit=A misses=0       BEGIN A
755  * -----AA- misses=1 last_hit=' ' hits=0
756  * ----AA-- misses=2
757  * ---AA--- misses=3 current_hit=' '            END A
758  * --AA---B last_hit=B hits=0&1
759  * -AA---BC last_hit=C hits=0&1
760  * AA---BCC hits=2 current_hit=C misses=0       BEGIN C
761  * A---BCC- misses=1 last_hit=' ' hits=0
762  * ---BCC-C misses=0 last_hit=C hits=0&1
763  * --BCC-CC misses=0
764  *
765  * Example: hits_to_begin=3 misses_to_end=2
766  * -------A last_hit=A hits=0&1
767  * ------AA hits=2
768  * -----AAA hits=3 current_hit=A misses=0       BEGIN A
769  * ----AAAB misses=1 last_hit=B hits=0&1
770  * ---AAABB misses=2 current_hit=' ' hits=2     END A
771  * --AAABBB hits=3 current_hit=B misses=0       BEGIN B
772  * -AAABBBB misses=0
773  *
774  * Example: hits_to_begin=2 misses_to_end=2
775  * -------A last_hit=A hits=0&1
776  * ------AA hits=2 current_hit=A misses=0       BEGIN A
777  * -----AAB misses=1 hits=0&1
778  * ----AABB misses=2 current_hit=' ' hits=2 current_hit=B misses=0 BEGIN B
779  * ---AABBB misses=0
780  */
781
782                 if (s->td.dtmf.current_hit) {
783                         /* We are in the middle of a digit already */
784                         if (hit != s->td.dtmf.current_hit) {
785                                 s->td.dtmf.misses++;
786                                 if (s->td.dtmf.misses == s->td.dtmf.misses_to_end) {
787                                         /* There were enough misses to consider digit ended */
788                                         s->td.dtmf.current_hit = 0;
789                                 }
790                         } else {
791                                 s->td.dtmf.misses = 0;
792                                 /* Current hit was same as last, so increment digit duration (of last digit) */
793                                 s->digitlen[s->current_digits - 1] += DTMF_GSIZE;
794                         }
795                 }
796
797                 /* Look for a start of a new digit no matter if we are already in the middle of some
798                    digit or not. This is because hits_to_begin may be smaller than misses_to_end
799                    and we may find begin of new digit before we consider last one ended. */
800
801                 if (hit != s->td.dtmf.lasthit) {
802                         s->td.dtmf.lasthit = hit;
803                         s->td.dtmf.hits = 0;
804                 }
805                 if (hit && hit != s->td.dtmf.current_hit) {
806                         s->td.dtmf.hits++;
807                         if (s->td.dtmf.hits == s->td.dtmf.hits_to_begin) {
808                                 store_digit(s, hit);
809                                 s->td.dtmf.current_hit = hit;
810                                 s->td.dtmf.misses = 0;
811                         }
812                 }
813
814                 /* If we had a hit in this block, include it into mute fragment */
815                 if (squelch && hit) {
816                         if (mute.end < sample - DTMF_GSIZE) {
817                                 /* There is a gap between fragments */
818                                 mute_fragment(dsp, &mute);
819                                 mute.start = (sample > DTMF_GSIZE) ? (sample - DTMF_GSIZE) : 0;
820                         }
821                         mute.end = limit + DTMF_GSIZE;
822                 }
823
824                 /* Reinitialise the detector for the next block */
825                 for (i = 0; i < 4; i++) {
826                         goertzel_reset(&s->td.dtmf.row_out[i]);
827                         goertzel_reset(&s->td.dtmf.col_out[i]);
828                 }
829                 s->td.dtmf.energy = 0.0;
830                 s->td.dtmf.current_sample = 0;
831         }
832
833         if (squelch && mute.end) {
834                 if (mute.end > samples) {
835                         s->td.dtmf.mute_samples = mute.end - samples;
836                         mute.end = samples;
837                 }
838                 mute_fragment(dsp, &mute);
839         }
840
841         return (s->td.dtmf.current_hit);        /* return the debounced hit */
842 }
843
844 static int mf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[],
845                 int samples, int squelch, int relax)
846 {
847         float energy[6];
848         int best;
849         int second_best;
850         int i;
851         int j;
852         int sample;
853         short samp;
854         int hit;
855         int limit;
856         fragment_t mute = {0, 0};
857
858         if (squelch && s->td.mf.mute_samples > 0) {
859                 mute.end = (s->td.mf.mute_samples < samples) ? s->td.mf.mute_samples : samples;
860                 s->td.mf.mute_samples -= mute.end;
861         }
862
863         hit = 0;
864         for (sample = 0; sample < samples; sample = limit) {
865                 /* 80 is optimised to meet the MF specs. */
866                 /* XXX So then why is MF_GSIZE defined as 120? */
867                 if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample)) {
868                         limit = sample + (MF_GSIZE - s->td.mf.current_sample);
869                 } else {
870                         limit = samples;
871                 }
872                 /* The following unrolled loop takes only 35% (rough estimate) of the
873                    time of a rolled loop on the machine on which it was developed */
874                 for (j = sample; j < limit; j++) {
875                         /* With GCC 2.95, the following unrolled code seems to take about 35%
876                            (rough estimate) as long as a neat little 0-3 loop */
877                         samp = amp[j];
878                         goertzel_sample(s->td.mf.tone_out, samp);
879                         goertzel_sample(s->td.mf.tone_out + 1, samp);
880                         goertzel_sample(s->td.mf.tone_out + 2, samp);
881                         goertzel_sample(s->td.mf.tone_out + 3, samp);
882                         goertzel_sample(s->td.mf.tone_out + 4, samp);
883                         goertzel_sample(s->td.mf.tone_out + 5, samp);
884                 }
885                 s->td.mf.current_sample += (limit - sample);
886                 if (s->td.mf.current_sample < MF_GSIZE) {
887                         continue;
888                 }
889                 /* We're at the end of an MF detection block.  */
890                 /* Find the two highest energies. The spec says to look for
891                    two tones and two tones only. Taking this literally -ie
892                    only two tones pass the minimum threshold - doesn't work
893                    well. The sinc function mess, due to rectangular windowing
894                    ensure that! Find the two highest energies and ensure they
895                    are considerably stronger than any of the others. */
896                 energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
897                 energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
898                 if (energy[0] > energy[1]) {
899                         best = 0;
900                         second_best = 1;
901                 } else {
902                         best = 1;
903                         second_best = 0;
904                 }
905                 /*endif*/
906                 for (i = 2; i < 6; i++) {
907                         energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
908                         if (energy[i] >= energy[best]) {
909                                 second_best = best;
910                                 best = i;
911                         } else if (energy[i] >= energy[second_best]) {
912                                 second_best = i;
913                         }
914                 }
915                 /* Basic signal level and twist tests */
916                 hit = 0;
917                 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
918                     && energy[best] < energy[second_best]*BELL_MF_TWIST
919                     && energy[best] * BELL_MF_TWIST > energy[second_best]) {
920                         /* Relative peak test */
921                         hit = -1;
922                         for (i = 0; i < 6; i++) {
923                                 if (i != best && i != second_best) {
924                                         if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
925                                                 /* The best two are not clearly the best */
926                                                 hit = 0;
927                                                 break;
928                                         }
929                                 }
930                         }
931                 }
932                 if (hit) {
933                         /* Get the values into ascending order */
934                         if (second_best < best) {
935                                 i = best;
936                                 best = second_best;
937                                 second_best = i;
938                         }
939                         best = best * 5 + second_best - 1;
940                         hit = bell_mf_positions[best];
941                         /* Look for two successive similar results */
942                         /* The logic in the next test is:
943                            For KP we need 4 successive identical clean detects, with
944                            two blocks of something different preceeding it. For anything
945                            else we need two successive identical clean detects, with
946                            two blocks of something different preceeding it. */
947                         if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
948                            ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
949                             (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] &&
950                             hit != s->td.mf.hits[0]))) {
951                                 store_digit(s, hit);
952                         }
953                 }
954
955
956                 if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
957                         /* Two successive block without a hit terminate current digit */
958                         s->td.mf.current_hit = 0;
959                 }
960
961                 s->td.mf.hits[0] = s->td.mf.hits[1];
962                 s->td.mf.hits[1] = s->td.mf.hits[2];
963                 s->td.mf.hits[2] = s->td.mf.hits[3];
964                 s->td.mf.hits[3] = s->td.mf.hits[4];
965                 s->td.mf.hits[4] = hit;
966
967                 /* If we had a hit in this block, include it into mute fragment */
968                 if (squelch && hit) {
969                         if (mute.end < sample - MF_GSIZE) {
970                                 /* There is a gap between fragments */
971                                 mute_fragment(dsp, &mute);
972                                 mute.start = (sample > MF_GSIZE) ? (sample - MF_GSIZE) : 0;
973                         }
974                         mute.end = limit + MF_GSIZE;
975                 }
976
977                 /* Reinitialise the detector for the next block */
978                 for (i = 0; i < 6; i++) {
979                         goertzel_reset(&s->td.mf.tone_out[i]);
980                 }
981                 s->td.mf.current_sample = 0;
982         }
983
984         if (squelch && mute.end) {
985                 if (mute.end > samples) {
986                         s->td.mf.mute_samples = mute.end - samples;
987                         mute.end = samples;
988                 }
989                 mute_fragment(dsp, &mute);
990         }
991
992         return (s->td.mf.current_hit); /* return the debounced hit */
993 }
994
995 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
996 {
997         /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
998         /* Make sure absolute levels are high enough */
999         if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH)) {
1000                 return 0;
1001         }
1002         /* Amplify ignored stuff */
1003         i2 *= TONE_THRESH;
1004         i1 *= TONE_THRESH;
1005         e *= TONE_THRESH;
1006         /* Check first tone */
1007         if ((p1 < i1) || (p1 < i2) || (p1 < e)) {
1008                 return 0;
1009         }
1010         /* And second */
1011         if ((p2 < i1) || (p2 < i2) || (p2 < e)) {
1012                 return 0;
1013         }
1014         /* Guess it's there... */
1015         return 1;
1016 }
1017
1018 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
1019 {
1020         short samp;
1021         int x;
1022         int y;
1023         int pass;
1024         int newstate = DSP_TONE_STATE_SILENCE;
1025         int res = 0;
1026         while (len) {
1027                 /* Take the lesser of the number of samples we need and what we have */
1028                 pass = len;
1029                 if (pass > dsp->gsamp_size - dsp->gsamps) {
1030                         pass = dsp->gsamp_size - dsp->gsamps;
1031                 }
1032                 for (x = 0; x < pass; x++) {
1033                         samp = s[x];
1034                         dsp->genergy += (int32_t) samp * (int32_t) samp;
1035                         for (y = 0; y < dsp->freqcount; y++) {
1036                                 goertzel_sample(&dsp->freqs[y], samp);
1037                         }
1038                 }
1039                 s += pass;
1040                 dsp->gsamps += pass;
1041                 len -= pass;
1042                 if (dsp->gsamps == dsp->gsamp_size) {
1043                         float hz[7];
1044                         for (y = 0; y < 7; y++) {
1045                                 hz[y] = goertzel_result(&dsp->freqs[y]);
1046                         }
1047                         switch (dsp->progmode) {
1048                         case PROG_MODE_NA:
1049                                 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
1050                                         newstate = DSP_TONE_STATE_BUSY;
1051                                 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
1052                                         newstate = DSP_TONE_STATE_RINGING;
1053                                 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
1054                                         newstate = DSP_TONE_STATE_DIALTONE;
1055                                 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
1056                                         newstate = DSP_TONE_STATE_SPECIAL1;
1057                                 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
1058                                         /* End of SPECIAL1 or middle of SPECIAL2 */
1059                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL1 || dsp->tstate == DSP_TONE_STATE_SPECIAL2) {
1060                                                 newstate = DSP_TONE_STATE_SPECIAL2;
1061                                         }
1062                                 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
1063                                         /* End of SPECIAL2 or middle of SPECIAL3 */
1064                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL2 || dsp->tstate == DSP_TONE_STATE_SPECIAL3) {
1065                                                 newstate = DSP_TONE_STATE_SPECIAL3;
1066                                         }
1067                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1068                                         newstate = DSP_TONE_STATE_TALKING;
1069                                 } else {
1070                                         newstate = DSP_TONE_STATE_SILENCE;
1071                                 }
1072                                 break;
1073                         case PROG_MODE_CR:
1074                                 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
1075                                         newstate = DSP_TONE_STATE_RINGING;
1076                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1077                                         newstate = DSP_TONE_STATE_TALKING;
1078                                 } else {
1079                                         newstate = DSP_TONE_STATE_SILENCE;
1080                                 }
1081                                 break;
1082                         case PROG_MODE_UK:
1083                                 if (hz[HZ_400UK] > TONE_MIN_THRESH * TONE_THRESH) {
1084                                         newstate = DSP_TONE_STATE_HUNGUP;
1085                                 } else if (pair_there(hz[HZ_350UK], hz[HZ_440UK], hz[HZ_400UK], hz[HZ_400UK], dsp->genergy)) {
1086                                         newstate = DSP_TONE_STATE_DIALTONE;
1087                                 }
1088                                 break;
1089                         default:
1090                                 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
1091                         }
1092                         if (newstate == dsp->tstate) {
1093                                 dsp->tcount++;
1094                                 if (dsp->ringtimeout) {
1095                                         dsp->ringtimeout++;
1096                                 }
1097                                 switch (dsp->tstate) {
1098                                 case DSP_TONE_STATE_RINGING:
1099                                         if ((dsp->features & DSP_PROGRESS_RINGING) &&
1100                                             (dsp->tcount == THRESH_RING)) {
1101                                                 res = AST_CONTROL_RINGING;
1102                                                 dsp->ringtimeout = 1;
1103                                         }
1104                                         break;
1105                                 case DSP_TONE_STATE_BUSY:
1106                                         if ((dsp->features & DSP_PROGRESS_BUSY) &&
1107                                             (dsp->tcount == THRESH_BUSY)) {
1108                                                 res = AST_CONTROL_BUSY;
1109                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1110                                         }
1111                                         break;
1112                                 case DSP_TONE_STATE_TALKING:
1113                                         if ((dsp->features & DSP_PROGRESS_TALK) &&
1114                                             (dsp->tcount == THRESH_TALK)) {
1115                                                 res = AST_CONTROL_ANSWER;
1116                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1117                                         }
1118                                         break;
1119                                 case DSP_TONE_STATE_SPECIAL3:
1120                                         if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
1121                                             (dsp->tcount == THRESH_CONGESTION)) {
1122                                                 res = AST_CONTROL_CONGESTION;
1123                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1124                                         }
1125                                         break;
1126                                 case DSP_TONE_STATE_HUNGUP:
1127                                         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
1128                                             (dsp->tcount == THRESH_HANGUP)) {
1129                                                 res = AST_CONTROL_HANGUP;
1130                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1131                                         }
1132                                         break;
1133                                 }
1134                                 if (dsp->ringtimeout == THRESH_RING2ANSWER) {
1135                                         ast_debug(1, "Consider call as answered because of timeout after last ring\n");
1136                                         res = AST_CONTROL_ANSWER;
1137                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1138                                 }
1139                         } else {
1140                                 ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
1141                                 ast_debug(5, "Start state %d\n", newstate);
1142                                 dsp->tstate = newstate;
1143                                 dsp->tcount = 1;
1144                         }
1145
1146                         /* Reset goertzel */
1147                         for (x = 0; x < 7; x++) {
1148                                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1149                         }
1150                         dsp->gsamps = 0;
1151                         dsp->genergy = 0.0;
1152                 }
1153         }
1154
1155         return res;
1156 }
1157
1158 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1159 {
1160         if (inf->frametype != AST_FRAME_VOICE) {
1161                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1162                 return 0;
1163         }
1164         if (!ast_format_is_slinear(&inf->subclass.format)) {
1165                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1166                 return 0;
1167         }
1168         return __ast_dsp_call_progress(dsp, inf->data.ptr, inf->datalen / 2);
1169 }
1170
1171 static int __ast_dsp_silence_noise(struct ast_dsp *dsp, short *s, int len, int *totalsilence, int *totalnoise, int *frames_energy)
1172 {
1173         int accum;
1174         int x;
1175         int res = 0;
1176
1177         if (!len) {
1178                 return 0;
1179         }
1180         accum = 0;
1181         for (x = 0; x < len; x++) {
1182                 accum += abs(s[x]);
1183         }
1184         accum /= len;
1185         if (accum < dsp->threshold) {
1186                 /* Silent */
1187                 dsp->totalsilence += len / (dsp->sample_rate / 1000);
1188                 if (dsp->totalnoise) {
1189                         /* Move and save history */
1190                         memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicnoise[0]));
1191                         dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1192 /* we don't want to check for busydetect that frequently */
1193 #if 0
1194                         dsp->busymaybe = 1;
1195 #endif
1196                 }
1197                 dsp->totalnoise = 0;
1198                 res = 1;
1199         } else {
1200                 /* Not silent */
1201                 dsp->totalnoise += len / (dsp->sample_rate / 1000);
1202                 if (dsp->totalsilence) {
1203                         int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1204                         int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1205                         /* Move and save history */
1206                         memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicsilence[0]));
1207                         dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1208                         /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1209                         if (silence1 < silence2) {
1210                                 if (silence1 + silence1 * BUSY_PERCENT / 100 >= silence2) {
1211                                         dsp->busymaybe = 1;
1212                                 } else {
1213                                         dsp->busymaybe = 0;
1214                                 }
1215                         } else {
1216                                 if (silence1 - silence1 * BUSY_PERCENT / 100 <= silence2) {
1217                                         dsp->busymaybe = 1;
1218                                 } else {
1219                                         dsp->busymaybe = 0;
1220                                 }
1221                         }
1222                 }
1223                 dsp->totalsilence = 0;
1224         }
1225         if (totalsilence) {
1226                 *totalsilence = dsp->totalsilence;
1227         }
1228         if (totalnoise) {
1229                 *totalnoise = dsp->totalnoise;
1230         }
1231         if (frames_energy) {
1232                 *frames_energy = accum;
1233         }
1234         return res;
1235 }
1236
1237 int ast_dsp_busydetect(struct ast_dsp *dsp)
1238 {
1239         int res = 0, x;
1240 #ifndef BUSYDETECT_TONEONLY
1241         int avgsilence = 0, hitsilence = 0;
1242 #endif
1243         int avgtone = 0, hittone = 0;
1244
1245         /* if we have a 4 length pattern, the way busymaybe is set doesn't help us. */
1246         if (dsp->busy_cadence.length != 4) {
1247                 if (!dsp->busymaybe) {
1248                         return res;
1249                 }
1250         }
1251
1252         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1253 #ifndef BUSYDETECT_TONEONLY
1254                 avgsilence += dsp->historicsilence[x];
1255 #endif
1256                 avgtone += dsp->historicnoise[x];
1257         }
1258 #ifndef BUSYDETECT_TONEONLY
1259         avgsilence /= dsp->busycount;
1260 #endif
1261         avgtone /= dsp->busycount;
1262         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1263 #ifndef BUSYDETECT_TONEONLY
1264                 if (avgsilence > dsp->historicsilence[x]) {
1265                         if (avgsilence - (avgsilence * BUSY_PERCENT / 100) <= dsp->historicsilence[x]) {
1266                                 hitsilence++;
1267                         }
1268                 } else {
1269                         if (avgsilence + (avgsilence * BUSY_PERCENT / 100) >= dsp->historicsilence[x]) {
1270                                 hitsilence++;
1271                         }
1272                 }
1273 #endif
1274                 if (avgtone > dsp->historicnoise[x]) {
1275                         if (avgtone - (avgtone * BUSY_PERCENT / 100) <= dsp->historicnoise[x]) {
1276                                 hittone++;
1277                         }
1278                 } else {
1279                         if (avgtone + (avgtone * BUSY_PERCENT / 100) >= dsp->historicnoise[x]) {
1280                                 hittone++;
1281                         }
1282                 }
1283         }
1284 #ifndef BUSYDETECT_TONEONLY
1285         if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) &&
1286             (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) &&
1287             (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1288 #else
1289         if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1290 #endif
1291 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1292                 if (avgtone > avgsilence) {
1293                         if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence) {
1294                                 res = 1;
1295                         }
1296                 } else {
1297                         if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence) {
1298                                 res = 1;
1299                         }
1300                 }
1301 #else
1302                 res = 1;
1303 #endif
1304         }
1305
1306         /* If we have a 4-length pattern, we can go ahead and just check it in a different way. */
1307         if (dsp->busy_cadence.length == 4) {
1308                 int x;
1309                 int errors = 0;
1310                 int errors_max = ((4 * dsp->busycount) / 100.0) * BUSY_PAT_PERCENT;
1311
1312                 for (x = DSP_HISTORY - (dsp->busycount); x < DSP_HISTORY; x += 2) {
1313                         int temp_error;
1314                         temp_error = abs(dsp->historicnoise[x] - dsp->busy_cadence.pattern[0]);
1315                         if ((temp_error * 100) / dsp->busy_cadence.pattern[0] > BUSY_PERCENT) {
1316                                 errors++;
1317                         }
1318
1319                         temp_error = abs(dsp->historicnoise[x + 1] - dsp->busy_cadence.pattern[2]);
1320                         if ((temp_error * 100) / dsp->busy_cadence.pattern[2] > BUSY_PERCENT) {
1321                                 errors++;
1322                         }
1323
1324                         temp_error = abs(dsp->historicsilence[x] - dsp->busy_cadence.pattern[1]);
1325                         if ((temp_error * 100) / dsp->busy_cadence.pattern[1] > BUSY_PERCENT) {
1326                                 errors++;
1327                         }
1328
1329                         temp_error = abs(dsp->historicsilence[x + 1] - dsp->busy_cadence.pattern[3]);
1330                         if ((temp_error * 100) / dsp->busy_cadence.pattern[3] > BUSY_PERCENT) {
1331                                 errors++;
1332                         }
1333                 }
1334
1335                 ast_debug(5, "errors = %d  max = %d\n", errors, errors_max);
1336
1337                 if (errors <= errors_max) {
1338                         return 1;
1339                 }
1340         }
1341
1342         /* If we know the expected busy tone length, check we are in the range */
1343         if (res && (dsp->busy_cadence.pattern[0] > 0)) {
1344                 if (abs(avgtone - dsp->busy_cadence.pattern[0]) > MAX(dsp->busy_cadence.pattern[0]*BUSY_PAT_PERCENT/100, 20)) {
1345 #ifdef BUSYDETECT_DEBUG
1346                         ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
1347                                 avgtone, dsp->busy_cadence.pattern[0]);
1348 #endif
1349                         res = 0;
1350                 }
1351         }
1352 #ifndef BUSYDETECT_TONEONLY
1353         /* If we know the expected busy tone silent-period length, check we are in the range */
1354         if (res && (dsp->busy_cadence.pattern[1] > 0)) {
1355                 if (abs(avgsilence - dsp->busy_cadence.pattern[1]) > MAX(dsp->busy_cadence.pattern[1]*BUSY_PAT_PERCENT/100, 20)) {
1356 #ifdef BUSYDETECT_DEBUG
1357                 ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
1358                         avgsilence, dsp->busy_cadence.pattern[1]);
1359 #endif
1360                         res = 0;
1361                 }
1362         }
1363 #endif
1364 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
1365         if (res) {
1366                 ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1367         } else {
1368                 ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1369         }
1370 #endif
1371         return res;
1372 }
1373
1374 static int ast_dsp_silence_noise_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *total, int *frames_energy, int noise)
1375 {
1376         short *s;
1377         int len;
1378         int x;
1379         unsigned char *odata;
1380
1381         if (!f) {
1382                 return 0;
1383         }
1384
1385         if (f->frametype != AST_FRAME_VOICE) {
1386                 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1387                 return 0;
1388         }
1389         if (!ast_format_is_slinear(&f->subclass.format)) {
1390                 odata = f->data.ptr;
1391                 len = f->datalen;
1392                 switch (f->subclass.format.id) {
1393                         case AST_FORMAT_ULAW:
1394                                 s = ast_alloca(len * 2);
1395                                 for (x = 0;x < len; x++) {
1396                                         s[x] = AST_MULAW(odata[x]);
1397                                 }
1398                                 break;
1399                         case AST_FORMAT_ALAW:
1400                                 s = ast_alloca(len * 2);
1401                                 for (x = 0;x < len; x++) {
1402                                         s[x] = AST_ALAW(odata[x]);
1403                                 }
1404                                 break;
1405                         default:
1406                                 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear, alaw or ulaw frames :(\n");
1407                         return 0;
1408                 }
1409         } else {
1410                 s = f->data.ptr;
1411                 len = f->datalen/2;
1412         }
1413         if (noise) {
1414                 return __ast_dsp_silence_noise(dsp, s, len, NULL, total, frames_energy);
1415         } else {
1416                 return __ast_dsp_silence_noise(dsp, s, len, total, NULL, frames_energy);
1417         }
1418 }
1419
1420 int ast_dsp_silence_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence, int *frames_energy)
1421 {
1422         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, frames_energy, 0);
1423 }
1424
1425 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1426 {
1427         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, NULL, 0);
1428 }
1429
1430 int ast_dsp_noise(struct ast_dsp *dsp, struct ast_frame *f, int *totalnoise)
1431 {
1432         return ast_dsp_silence_noise_with_energy(dsp, f, totalnoise, NULL, 1);
1433 }
1434
1435
1436 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1437 {
1438         int silence;
1439         int res;
1440         int digit = 0, fax_digit = 0;
1441         int x;
1442         short *shortdata;
1443         unsigned char *odata;
1444         int len;
1445         struct ast_frame *outf = NULL;
1446
1447         if (!af) {
1448                 return NULL;
1449         }
1450         if (af->frametype != AST_FRAME_VOICE) {
1451                 return af;
1452         }
1453
1454         odata = af->data.ptr;
1455         len = af->datalen;
1456         /* Make sure we have short data */
1457         if (ast_format_is_slinear(&af->subclass.format)) {
1458                 shortdata = af->data.ptr;
1459                 len = af->datalen / 2;
1460         } else {
1461                 switch (af->subclass.format.id) {
1462                 case AST_FORMAT_ULAW:
1463                 case AST_FORMAT_TESTLAW:
1464                         shortdata = ast_alloca(af->datalen * 2);
1465                         for (x = 0;x < len; x++) {
1466                                 shortdata[x] = AST_MULAW(odata[x]);
1467                         }
1468                         break;
1469                 case AST_FORMAT_ALAW:
1470                         shortdata = ast_alloca(af->datalen * 2);
1471                         for (x = 0; x < len; x++) {
1472                                 shortdata[x] = AST_ALAW(odata[x]);
1473                         }
1474                         break;
1475                 default:
1476                         /*Display warning only once. Otherwise you would get hundreds of warnings every second */
1477                         if (dsp->display_inband_dtmf_warning)
1478                                 ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(&af->subclass.format));
1479                         dsp->display_inband_dtmf_warning = 0;
1480                         return af;
1481                 }
1482         }
1483
1484         /* Initially we do not want to mute anything */
1485         dsp->mute_fragments = 0;
1486
1487         /* Need to run the silence detection stuff for silence suppression and busy detection */
1488         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) || (dsp->features & DSP_FEATURE_BUSY_DETECT)) {
1489                 res = __ast_dsp_silence_noise(dsp, shortdata, len, &silence, NULL, NULL);
1490         }
1491
1492         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1493                 memset(&dsp->f, 0, sizeof(dsp->f));
1494                 dsp->f.frametype = AST_FRAME_NULL;
1495                 ast_frfree(af);
1496                 return ast_frisolate(&dsp->f);
1497         }
1498         if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1499                 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1500                 memset(&dsp->f, 0, sizeof(dsp->f));
1501                 dsp->f.frametype = AST_FRAME_CONTROL;
1502                 dsp->f.subclass.integer = AST_CONTROL_BUSY;
1503                 ast_frfree(af);
1504                 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", ast_channel_name(chan));
1505                 return ast_frisolate(&dsp->f);
1506         }
1507
1508         if ((dsp->features & DSP_FEATURE_FAX_DETECT)) {
1509                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CNG) && tone_detect(dsp, &dsp->cng_tone_state, shortdata, len)) {
1510                         fax_digit = 'f';
1511                 }
1512
1513                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CED) && tone_detect(dsp, &dsp->ced_tone_state, shortdata, len)) {
1514                         fax_digit = 'e';
1515                 }
1516         }
1517
1518         if (dsp->features & (DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_BUSY_DETECT)) {
1519                 if (dsp->digitmode & DSP_DIGITMODE_MF) {
1520                         digit = mf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1521                 } else {
1522                         digit = dtmf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1523                 }
1524
1525                 if (dsp->digit_state.current_digits) {
1526                         int event = 0, event_len = 0;
1527                         char event_digit = 0;
1528
1529                         if (!dsp->dtmf_began) {
1530                                 /* We have not reported DTMF_BEGIN for anything yet */
1531
1532                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1533                                         event = AST_FRAME_DTMF_BEGIN;
1534                                         event_digit = dsp->digit_state.digits[0];
1535                                 }
1536                                 dsp->dtmf_began = 1;
1537
1538                         } else if (dsp->digit_state.current_digits > 1 || digit != dsp->digit_state.digits[0]) {
1539                                 /* Digit changed. This means digit we have reported with DTMF_BEGIN ended */
1540                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1541                                         event = AST_FRAME_DTMF_END;
1542                                         event_digit = dsp->digit_state.digits[0];
1543                                         event_len = dsp->digit_state.digitlen[0] * 1000 / dsp->sample_rate;
1544                                 }
1545                                 memmove(&dsp->digit_state.digits[0], &dsp->digit_state.digits[1], dsp->digit_state.current_digits);
1546                                 memmove(&dsp->digit_state.digitlen[0], &dsp->digit_state.digitlen[1], dsp->digit_state.current_digits * sizeof(dsp->digit_state.digitlen[0]));
1547                                 dsp->digit_state.current_digits--;
1548                                 dsp->dtmf_began = 0;
1549
1550                                 if (dsp->features & DSP_FEATURE_BUSY_DETECT) {
1551                                         /* Reset Busy Detector as we have some confirmed activity */
1552                                         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1553                                         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1554                                         ast_debug(1, "DTMF Detected - Reset busydetector\n");
1555                                 }
1556                         }
1557
1558                         if (event) {
1559                                 memset(&dsp->f, 0, sizeof(dsp->f));
1560                                 dsp->f.frametype = event;
1561                                 dsp->f.subclass.integer = event_digit;
1562                                 dsp->f.len = event_len;
1563                                 outf = &dsp->f;
1564                                 goto done;
1565                         }
1566                 }
1567         }
1568
1569         if (fax_digit) {
1570                 /* Fax was detected - digit is either 'f' or 'e' */
1571
1572                 memset(&dsp->f, 0, sizeof(dsp->f));
1573                 dsp->f.frametype = AST_FRAME_DTMF;
1574                 dsp->f.subclass.integer = fax_digit;
1575                 outf = &dsp->f;
1576                 goto done;
1577         }
1578
1579         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1580                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1581                 if (res) {
1582                         switch (res) {
1583                         case AST_CONTROL_ANSWER:
1584                         case AST_CONTROL_BUSY:
1585                         case AST_CONTROL_RINGING:
1586                         case AST_CONTROL_CONGESTION:
1587                         case AST_CONTROL_HANGUP:
1588                                 memset(&dsp->f, 0, sizeof(dsp->f));
1589                                 dsp->f.frametype = AST_FRAME_CONTROL;
1590                                 dsp->f.subclass.integer = res;
1591                                 dsp->f.src = "dsp_progress";
1592                                 if (chan) {
1593                                         ast_queue_frame(chan, &dsp->f);
1594                                 }
1595                                 break;
1596                         default:
1597                                 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1598                         }
1599                 }
1600         } else if ((dsp->features & DSP_FEATURE_WAITDIALTONE)) {
1601                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1602         }
1603
1604 done:
1605         /* Mute fragment of the frame */
1606         for (x = 0; x < dsp->mute_fragments; x++) {
1607                 memset(shortdata + dsp->mute_data[x].start, 0, sizeof(int16_t) * (dsp->mute_data[x].end - dsp->mute_data[x].start));
1608         }
1609
1610         switch (af->subclass.format.id) {
1611         case AST_FORMAT_ULAW:
1612                 for (x = 0; x < len; x++) {
1613                         odata[x] = AST_LIN2MU((unsigned short) shortdata[x]);
1614                 }
1615                 break;
1616         case AST_FORMAT_ALAW:
1617                 for (x = 0; x < len; x++) {
1618                         odata[x] = AST_LIN2A((unsigned short) shortdata[x]);
1619                 }
1620                 /* fall through */
1621         default:
1622                 break;
1623         }
1624
1625         if (outf) {
1626                 if (chan) {
1627                         ast_queue_frame(chan, af);
1628                 }
1629                 ast_frfree(af);
1630                 return ast_frisolate(outf);
1631         } else {
1632                 return af;
1633         }
1634 }
1635
1636 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1637 {
1638         int max = 0;
1639         int x;
1640
1641         dsp->gsamp_size = modes[dsp->progmode].size;
1642         dsp->gsamps = 0;
1643         for (x = 0; x < ARRAY_LEN(modes[dsp->progmode].freqs); x++) {
1644                 if (modes[dsp->progmode].freqs[x]) {
1645                         goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->sample_rate);
1646                         max = x + 1;
1647                 }
1648         }
1649         dsp->freqcount = max;
1650         dsp->ringtimeout= 0;
1651 }
1652
1653 unsigned int ast_dsp_get_sample_rate(const struct ast_dsp *dsp)
1654 {
1655         return dsp->sample_rate;
1656 }
1657
1658 static struct ast_dsp *__ast_dsp_new(unsigned int sample_rate)
1659 {
1660         struct ast_dsp *dsp;
1661
1662         if ((dsp = ast_calloc(1, sizeof(*dsp)))) {
1663                 dsp->threshold = DEFAULT_THRESHOLD;
1664                 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1665                 dsp->busycount = DSP_HISTORY;
1666                 dsp->digitmode = DSP_DIGITMODE_DTMF;
1667                 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1668                 dsp->sample_rate = sample_rate;
1669                 /* Initialize digit detector */
1670                 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF, dsp->sample_rate);
1671                 dsp->display_inband_dtmf_warning = 1;
1672                 /* Initialize initial DSP progress detect parameters */
1673                 ast_dsp_prog_reset(dsp);
1674                 /* Initialize fax detector */
1675                 ast_fax_detect_init(dsp);
1676         }
1677         return dsp;
1678 }
1679
1680 struct ast_dsp *ast_dsp_new(void)
1681 {
1682         return __ast_dsp_new(DEFAULT_SAMPLE_RATE);
1683 }
1684
1685 struct ast_dsp *ast_dsp_new_with_rate(unsigned int sample_rate)
1686 {
1687         return __ast_dsp_new(sample_rate);
1688 }
1689
1690 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1691 {
1692         dsp->features = features;
1693         if (!(features & DSP_FEATURE_DIGIT_DETECT)) {
1694                 dsp->display_inband_dtmf_warning = 0;
1695         }
1696 }
1697
1698 void ast_dsp_free(struct ast_dsp *dsp)
1699 {
1700         ast_free(dsp);
1701 }
1702
1703 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1704 {
1705         dsp->threshold = threshold;
1706 }
1707
1708 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1709 {
1710         if (cadences < 4) {
1711                 cadences = 4;
1712         }
1713         if (cadences > DSP_HISTORY) {
1714                 cadences = DSP_HISTORY;
1715         }
1716         dsp->busycount = cadences;
1717 }
1718
1719 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, const struct ast_dsp_busy_pattern *cadence)
1720 {
1721         dsp->busy_cadence = *cadence;
1722         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);
1723 }
1724
1725 void ast_dsp_digitreset(struct ast_dsp *dsp)
1726 {
1727         int i;
1728
1729         dsp->dtmf_began = 0;
1730         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1731                 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1732                 /* Reinitialise the detector for the next block */
1733                 for (i = 0; i < 6; i++) {
1734                         goertzel_reset(&s->tone_out[i]);
1735                 }
1736                 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = 0;
1737                 s->current_hit = 0;
1738                 s->current_sample = 0;
1739         } else {
1740                 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1741                 /* Reinitialise the detector for the next block */
1742                 for (i = 0; i < 4; i++) {
1743                         goertzel_reset(&s->row_out[i]);
1744                         goertzel_reset(&s->col_out[i]);
1745                 }
1746                 s->lasthit = 0;
1747                 s->current_hit = 0;
1748                 s->energy = 0.0;
1749                 s->current_sample = 0;
1750                 s->hits = 0;
1751                 s->misses = 0;
1752         }
1753
1754         dsp->digit_state.digits[0] = '\0';
1755         dsp->digit_state.current_digits = 0;
1756 }
1757
1758 void ast_dsp_reset(struct ast_dsp *dsp)
1759 {
1760         int x;
1761
1762         dsp->totalsilence = 0;
1763         dsp->gsamps = 0;
1764         for (x = 0; x < 4; x++) {
1765                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1766         }
1767         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1768         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1769         dsp->ringtimeout= 0;
1770 }
1771
1772 int ast_dsp_set_digitmode(struct ast_dsp *dsp, int digitmode)
1773 {
1774         int new;
1775         int old;
1776
1777         old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1778         new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1779         if (old != new) {
1780                 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1781                 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF, dsp->sample_rate);
1782         }
1783         dsp->digitmode = digitmode;
1784         return 0;
1785 }
1786
1787 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1788 {
1789         if (dsp->faxmode != faxmode) {
1790                 dsp->faxmode = faxmode;
1791                 ast_fax_detect_init(dsp);
1792         }
1793         return 0;
1794 }
1795
1796 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1797 {
1798         int x;
1799
1800         for (x = 0; x < ARRAY_LEN(aliases); x++) {
1801                 if (!strcasecmp(aliases[x].name, zone)) {
1802                         dsp->progmode = aliases[x].mode;
1803                         ast_dsp_prog_reset(dsp);
1804                         return 0;
1805                 }
1806         }
1807         return -1;
1808 }
1809
1810 int ast_dsp_was_muted(struct ast_dsp *dsp)
1811 {
1812         return (dsp->mute_fragments > 0);
1813 }
1814
1815 int ast_dsp_get_tstate(struct ast_dsp *dsp)
1816 {
1817         return dsp->tstate;
1818 }
1819
1820 int ast_dsp_get_tcount(struct ast_dsp *dsp)
1821 {
1822         return dsp->tcount;
1823 }
1824
1825 static int _dsp_init(int reload)
1826 {
1827         struct ast_config *cfg;
1828         struct ast_variable *v;
1829         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1830         int cfg_threshold;
1831
1832         if ((cfg = ast_config_load2(CONFIG_FILE_NAME, "dsp", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
1833                 return 0;
1834         }
1835
1836         thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1837
1838         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
1839                 return 0;
1840         }
1841
1842         for (v = ast_variable_browse(cfg, "default"); v; v = v->next) {
1843                 if (!strcasecmp(v->name, "silencethreshold")) {
1844                         if (sscanf(v->value, "%30d", &cfg_threshold) < 1) {
1845                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1846                         } else if (cfg_threshold < 0) {
1847                                 ast_log(LOG_WARNING, "Invalid silence threshold '%d' specified, using default\n", cfg_threshold);
1848                         } else {
1849                                 thresholds[THRESHOLD_SILENCE] = cfg_threshold;
1850                         }
1851                 }
1852         }
1853         ast_config_destroy(cfg);
1854
1855         return 0;
1856 }
1857
1858 int ast_dsp_get_threshold_from_settings(enum threshold which)
1859 {
1860         return thresholds[which];
1861 }
1862
1863 int ast_dsp_init(void)
1864 {
1865         return _dsp_init(0);
1866 }
1867
1868 int ast_dsp_reload(void)
1869 {
1870         return _dsp_init(1);
1871 }