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