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