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