clang compiler warnings: Fix -Wunused-function; make inline function static
[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 static struct progress {
116         enum gsamp_size size;
117         int freqs[7];
118 } modes[] = {
119         { GSAMP_SIZE_NA, { 350, 440, 480, 620, 950, 1400, 1800 } },     /*!< North America */
120         { GSAMP_SIZE_CR, { 425 } },                                     /*!< Costa Rica, Brazil */
121         { GSAMP_SIZE_UK, { 350, 400, 440 } },                           /*!< UK */
122 };
123
124 /*!\brief This value is the minimum threshold, calculated by averaging all
125  * of the samples within a frame, for which a frame is determined to either
126  * be silence (below the threshold) or noise (above the threshold).  Please
127  * note that while the default threshold is an even exponent of 2, there is
128  * no requirement that it be so.  The threshold will accept any value between
129  * 0 and 32767.
130  */
131 #define DEFAULT_THRESHOLD       512
132
133 enum busy_detect {
134         BUSY_PERCENT = 10,      /*!< The percentage difference between the two last silence periods */
135         BUSY_PAT_PERCENT = 7,   /*!< The percentage difference between measured and actual pattern */
136         BUSY_THRESHOLD = 100,   /*!< Max number of ms difference between max and min times in busy */
137         BUSY_MIN = 75,          /*!< Busy must be at least 80 ms in half-cadence */
138         BUSY_MAX = 3100         /*!< Busy can't be longer than 3100 ms in half-cadence */
139 };
140
141 /*! Remember last 15 units */
142 #define DSP_HISTORY             15
143
144 #define TONE_THRESH             10.0    /*!< How much louder the tone should be than channel energy */
145 #define TONE_MIN_THRESH         1e8     /*!< How much tone there should be at least to attempt */
146
147 /*! All THRESH_XXX values are in GSAMP_SIZE chunks (us = 22ms) */
148 enum gsamp_thresh {
149         THRESH_RING = 8,                /*!< Need at least 150ms ring to accept */
150         THRESH_TALK = 2,                /*!< Talk detection does not work continuously */
151         THRESH_BUSY = 4,                /*!< Need at least 80ms to accept */
152         THRESH_CONGESTION = 4,          /*!< Need at least 80ms to accept */
153         THRESH_HANGUP = 60,             /*!< Need at least 1300ms to accept hangup */
154         THRESH_RING2ANSWER = 300        /*!< Timeout from start of ring to answer (about 6600 ms) */
155 };
156
157 #define MAX_DTMF_DIGITS         128
158
159 /* Basic DTMF (AT&T) specs:
160  *
161  * Minimum tone on = 40ms
162  * Minimum tone off = 50ms
163  * Maximum digit rate = 10 per second
164  * Normal twist <= 8dB accepted
165  * Reverse twist <= 4dB accepted
166  * S/N >= 15dB will detect OK
167  * Attenuation <= 26dB will detect OK
168  * Frequency tolerance +- 1.5% will detect, +-3.5% will reject
169  */
170
171 #define DTMF_THRESHOLD          8.0e7
172 #define FAX_THRESHOLD           8.0e7
173 #define FAX_2ND_HARMONIC        2.0     /* 4dB */
174
175 #define DEF_DTMF_NORMAL_TWIST           6.31     /* 8.0dB */
176 #define DEF_RELAX_DTMF_NORMAL_TWIST     6.31     /* 8.0dB */
177
178 #ifdef  RADIO_RELAX
179 #define DEF_DTMF_REVERSE_TWIST          2.51     /* 4.01dB */
180 #define DEF_RELAX_DTMF_REVERSE_TWIST    6.61     /* 8.2dB */
181 #else
182 #define DEF_DTMF_REVERSE_TWIST          2.51     /* 4.01dB */
183 #define DEF_RELAX_DTMF_REVERSE_TWIST    3.98     /* 6.0dB */
184 #endif
185
186 #define DTMF_RELATIVE_PEAK_ROW  6.3     /* 8dB */
187 #define DTMF_RELATIVE_PEAK_COL  6.3     /* 8dB */
188 #define DTMF_2ND_HARMONIC_ROW       (relax ? 1.7 : 2.5)     /* 4dB normal */
189 #define DTMF_2ND_HARMONIC_COL   63.1    /* 18dB */
190 #define DTMF_TO_TOTAL_ENERGY    42.0
191
192 #define BELL_MF_THRESHOLD       1.6e9
193 #define BELL_MF_TWIST           4.0     /* 6dB */
194 #define BELL_MF_RELATIVE_PEAK   12.6    /* 11dB */
195
196 #if defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
197 #error You cant use BUSYDETECT_TONEONLY together with BUSYDETECT_COMPARE_TONE_AND_SILENCE
198 #endif
199
200 /* The CNG signal consists of the transmission of 1100 Hz for 1/2 second,
201  * followed by a 3 second silent (2100 Hz OFF) period.
202  */
203 #define FAX_TONE_CNG_FREQ       1100
204 #define FAX_TONE_CNG_DURATION   500
205 #define FAX_TONE_CNG_DB         16
206
207 /* This signal may be sent by the Terminating FAX machine anywhere between
208  * 1.8 to 2.5 seconds AFTER answering the call.  The CED signal consists
209  * of a 2100 Hz tone that is from 2.6 to 4 seconds in duration.
210 */
211 #define FAX_TONE_CED_FREQ       2100
212 #define FAX_TONE_CED_DURATION   2600
213 #define FAX_TONE_CED_DB         16
214
215 #define DEFAULT_SAMPLE_RATE             8000
216
217 /* MF goertzel size */
218 #define MF_GSIZE                120
219
220 /* DTMF goertzel size */
221 #define DTMF_GSIZE              102
222
223 /* How many successive hits needed to consider begin of a digit
224  * IE. Override with dtmf_hits_to_begin=4 in dsp.conf
225  */
226 #define DEF_DTMF_HITS_TO_BEGIN  2
227
228 /* How many successive misses needed to consider end of a digit
229  * IE. Override with dtmf_misses_to_end=4 in dsp.conf
230  */
231 #define DEF_DTMF_MISSES_TO_END  3
232
233 /*!
234  * \brief The default silence threshold we will use if an alternate
235  * configured value is not present or is invalid.
236  */
237 static const int DEFAULT_SILENCE_THRESHOLD = 256;
238
239 #define CONFIG_FILE_NAME "dsp.conf"
240
241 typedef struct {
242         int v2;
243         int v3;
244         int chunky;
245         int fac;
246 } goertzel_state_t;
247
248 typedef struct {
249         int value;
250         int power;
251 } goertzel_result_t;
252
253 typedef struct
254 {
255         int freq;
256         int block_size;
257         int squelch;            /* Remove (squelch) tone */
258         goertzel_state_t tone;
259         float energy;           /* Accumulated energy of the current block */
260         int samples_pending;    /* Samples remain to complete the current block */
261         int mute_samples;       /* How many additional samples needs to be muted to suppress already detected tone */
262
263         int hits_required;      /* How many successive blocks with tone we are looking for */
264         float threshold;        /* Energy of the tone relative to energy from all other signals to consider a hit */
265
266         int hit_count;          /* How many successive blocks we consider tone present */
267         int last_hit;           /* Indicates if the last processed block was a hit */
268
269 } tone_detect_state_t;
270
271 typedef struct
272 {
273         goertzel_state_t row_out[4];
274         goertzel_state_t col_out[4];
275         int hits;                       /* How many successive hits we have seen already */
276         int misses;                     /* How many successive misses we have seen already */
277         int lasthit;
278         int current_hit;
279         float energy;
280         int current_sample;
281         int mute_samples;
282 } dtmf_detect_state_t;
283
284 typedef struct
285 {
286         goertzel_state_t tone_out[6];
287         int current_hit;
288         int hits[5];
289         int current_sample;
290         int mute_samples;
291 } mf_detect_state_t;
292
293 typedef struct
294 {
295         char digits[MAX_DTMF_DIGITS + 1];
296         int digitlen[MAX_DTMF_DIGITS + 1];
297         int current_digits;
298         int detected_digits;
299         int lost_digits;
300
301         union {
302                 dtmf_detect_state_t dtmf;
303                 mf_detect_state_t mf;
304         } td;
305 } digit_detect_state_t;
306
307 static const float dtmf_row[] = {
308         697.0,  770.0,  852.0,  941.0
309 };
310 static const float dtmf_col[] = {
311         1209.0, 1336.0, 1477.0, 1633.0
312 };
313 static const float mf_tones[] = {
314         700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
315 };
316 static const char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
317 static const char bell_mf_positions[] = "1247C-358A--69*---0B----#";
318 static int thresholds[THRESHOLD_MAX];
319 static float dtmf_normal_twist;         /* AT&T = 8dB */
320 static float dtmf_reverse_twist;        /* AT&T = 4dB */
321 static float relax_dtmf_normal_twist;   /* AT&T = 8dB */
322 static float relax_dtmf_reverse_twist;  /* AT&T = 6dB */
323 static int dtmf_hits_to_begin;          /* How many successive hits needed to consider begin of a digit */
324 static int dtmf_misses_to_end;          /* How many successive misses needed to consider end of a digit */
325
326 static inline void goertzel_sample(goertzel_state_t *s, short sample)
327 {
328         int v1;
329
330         v1 = s->v2;
331         s->v2 = s->v3;
332
333         s->v3 = (s->fac * s->v2) >> 15;
334         s->v3 = s->v3 - v1 + (sample >> s->chunky);
335         if (abs(s->v3) > 32768) {
336                 s->chunky++;
337                 s->v3 = s->v3 >> 1;
338                 s->v2 = s->v2 >> 1;
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 '%u'\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_cache_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
1403         if (ast_format_cache_is_slinear(f->subclass.format)) {
1404                 s = f->data.ptr;
1405                 len = f->datalen/2;
1406         } else {
1407                 odata = f->data.ptr;
1408                 len = f->datalen;
1409                 if (ast_format_cmp(f->subclass.format, ast_format_ulaw)) {
1410                         s = ast_alloca(len * 2);
1411                         for (x = 0; x < len; x++) {
1412                                 s[x] = AST_MULAW(odata[x]);
1413                         }
1414                 } else if (ast_format_cmp(f->subclass.format, ast_format_alaw)) {
1415                         s = ast_alloca(len * 2);
1416                         for (x = 0; x < len; x++) {
1417                                 s[x] = AST_ALAW(odata[x]);
1418                         }
1419                 } else {
1420                         ast_log(LOG_WARNING, "Can only calculate silence on signed-linear, alaw or ulaw frames :(\n");
1421                         return 0;
1422                 }
1423         }
1424
1425         if (noise) {
1426                 return __ast_dsp_silence_noise(dsp, s, len, NULL, total, frames_energy);
1427         } else {
1428                 return __ast_dsp_silence_noise(dsp, s, len, total, NULL, frames_energy);
1429         }
1430 }
1431
1432 int ast_dsp_silence_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence, int *frames_energy)
1433 {
1434         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, frames_energy, 0);
1435 }
1436
1437 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1438 {
1439         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, NULL, 0);
1440 }
1441
1442 int ast_dsp_noise(struct ast_dsp *dsp, struct ast_frame *f, int *totalnoise)
1443 {
1444         return ast_dsp_silence_noise_with_energy(dsp, f, totalnoise, NULL, 1);
1445 }
1446
1447
1448 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1449 {
1450         int silence;
1451         int res;
1452         int digit = 0, fax_digit = 0;
1453         int x;
1454         short *shortdata;
1455         unsigned char *odata;
1456         int len;
1457         struct ast_frame *outf = NULL;
1458
1459         if (!af) {
1460                 return NULL;
1461         }
1462         if (af->frametype != AST_FRAME_VOICE) {
1463                 return af;
1464         }
1465
1466         odata = af->data.ptr;
1467         len = af->datalen;
1468         /* Make sure we have short data */
1469         if (ast_format_cache_is_slinear(af->subclass.format)) {
1470                 shortdata = af->data.ptr;
1471                 len = af->datalen / 2;
1472         } else if (ast_format_cmp(af->subclass.format, ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) {
1473                 shortdata = ast_alloca(af->datalen * 2);
1474                 for (x = 0; x < len; x++) {
1475                         shortdata[x] = AST_MULAW(odata[x]);
1476                 }
1477         } else if (ast_format_cmp(af->subclass.format, ast_format_alaw) == AST_FORMAT_CMP_EQUAL) {
1478                 shortdata = ast_alloca(af->datalen * 2);
1479                 for (x = 0; x < len; x++) {
1480                         shortdata[x] = AST_ALAW(odata[x]);
1481                 }
1482         } else {
1483                 /*Display warning only once. Otherwise you would get hundreds of warnings every second */
1484                 if (dsp->display_inband_dtmf_warning) {
1485                         ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_format_get_name(af->subclass.format));
1486                 }
1487                 dsp->display_inband_dtmf_warning = 0;
1488                 return af;
1489         }
1490
1491         /* Initially we do not want to mute anything */
1492         dsp->mute_fragments = 0;
1493
1494         /* Need to run the silence detection stuff for silence suppression and busy detection */
1495         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) || (dsp->features & DSP_FEATURE_BUSY_DETECT)) {
1496                 res = __ast_dsp_silence_noise(dsp, shortdata, len, &silence, NULL, NULL);
1497         }
1498
1499         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1500                 memset(&dsp->f, 0, sizeof(dsp->f));
1501                 dsp->f.frametype = AST_FRAME_NULL;
1502                 ast_frfree(af);
1503                 return ast_frisolate(&dsp->f);
1504         }
1505         if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1506                 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1507                 memset(&dsp->f, 0, sizeof(dsp->f));
1508                 dsp->f.frametype = AST_FRAME_CONTROL;
1509                 dsp->f.subclass.integer = AST_CONTROL_BUSY;
1510                 ast_frfree(af);
1511                 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", ast_channel_name(chan));
1512                 return ast_frisolate(&dsp->f);
1513         }
1514
1515         if ((dsp->features & DSP_FEATURE_FAX_DETECT)) {
1516                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CNG) && tone_detect(dsp, &dsp->cng_tone_state, shortdata, len)) {
1517                         fax_digit = 'f';
1518                 }
1519
1520                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CED) && tone_detect(dsp, &dsp->ced_tone_state, shortdata, len)) {
1521                         fax_digit = 'e';
1522                 }
1523         }
1524
1525         if (dsp->features & (DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_BUSY_DETECT)) {
1526                 if (dsp->digitmode & DSP_DIGITMODE_MF) {
1527                         digit = mf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1528                 } else {
1529                         digit = dtmf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1530                 }
1531
1532                 if (dsp->digit_state.current_digits) {
1533                         int event = 0, event_len = 0;
1534                         char event_digit = 0;
1535
1536                         if (!dsp->dtmf_began) {
1537                                 /* We have not reported DTMF_BEGIN for anything yet */
1538
1539                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1540                                         event = AST_FRAME_DTMF_BEGIN;
1541                                         event_digit = dsp->digit_state.digits[0];
1542                                 }
1543                                 dsp->dtmf_began = 1;
1544
1545                         } else if (dsp->digit_state.current_digits > 1 || digit != dsp->digit_state.digits[0]) {
1546                                 /* Digit changed. This means digit we have reported with DTMF_BEGIN ended */
1547                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1548                                         event = AST_FRAME_DTMF_END;
1549                                         event_digit = dsp->digit_state.digits[0];
1550                                         event_len = dsp->digit_state.digitlen[0] * 1000 / dsp->sample_rate;
1551                                 }
1552                                 memmove(&dsp->digit_state.digits[0], &dsp->digit_state.digits[1], dsp->digit_state.current_digits);
1553                                 memmove(&dsp->digit_state.digitlen[0], &dsp->digit_state.digitlen[1], dsp->digit_state.current_digits * sizeof(dsp->digit_state.digitlen[0]));
1554                                 dsp->digit_state.current_digits--;
1555                                 dsp->dtmf_began = 0;
1556
1557                                 if (dsp->features & DSP_FEATURE_BUSY_DETECT) {
1558                                         /* Reset Busy Detector as we have some confirmed activity */
1559                                         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1560                                         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1561                                         ast_debug(1, "DTMF Detected - Reset busydetector\n");
1562                                 }
1563                         }
1564
1565                         if (event) {
1566                                 memset(&dsp->f, 0, sizeof(dsp->f));
1567                                 dsp->f.frametype = event;
1568                                 dsp->f.subclass.integer = event_digit;
1569                                 dsp->f.len = event_len;
1570                                 outf = &dsp->f;
1571                                 goto done;
1572                         }
1573                 }
1574         }
1575
1576         if (fax_digit) {
1577                 /* Fax was detected - digit is either 'f' or 'e' */
1578
1579                 memset(&dsp->f, 0, sizeof(dsp->f));
1580                 dsp->f.frametype = AST_FRAME_DTMF;
1581                 dsp->f.subclass.integer = fax_digit;
1582                 outf = &dsp->f;
1583                 goto done;
1584         }
1585
1586         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1587                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1588                 if (res) {
1589                         switch (res) {
1590                         case AST_CONTROL_ANSWER:
1591                         case AST_CONTROL_BUSY:
1592                         case AST_CONTROL_RINGING:
1593                         case AST_CONTROL_CONGESTION:
1594                         case AST_CONTROL_HANGUP:
1595                                 memset(&dsp->f, 0, sizeof(dsp->f));
1596                                 dsp->f.frametype = AST_FRAME_CONTROL;
1597                                 dsp->f.subclass.integer = res;
1598                                 dsp->f.src = "dsp_progress";
1599                                 if (chan) {
1600                                         ast_queue_frame(chan, &dsp->f);
1601                                 }
1602                                 break;
1603                         default:
1604                                 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1605                         }
1606                 }
1607         } else if ((dsp->features & DSP_FEATURE_WAITDIALTONE)) {
1608                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1609         }
1610
1611 done:
1612         /* Mute fragment of the frame */
1613         for (x = 0; x < dsp->mute_fragments; x++) {
1614                 memset(shortdata + dsp->mute_data[x].start, 0, sizeof(int16_t) * (dsp->mute_data[x].end - dsp->mute_data[x].start));
1615         }
1616
1617         if (ast_format_cmp(af->subclass.format, ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) {
1618                 for (x = 0; x < len; x++) {
1619                         odata[x] = AST_LIN2MU((unsigned short) shortdata[x]);
1620                 }
1621         } else 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_LIN2A((unsigned short) shortdata[x]);
1624                 }
1625         }
1626
1627         if (outf) {
1628                 if (chan) {
1629                         ast_queue_frame(chan, af);
1630                 }
1631                 ast_frfree(af);
1632                 return ast_frisolate(outf);
1633         } else {
1634                 return af;
1635         }
1636 }
1637
1638 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1639 {
1640         int max = 0;
1641         int x;
1642
1643         dsp->gsamp_size = modes[dsp->progmode].size;
1644         dsp->gsamps = 0;
1645         for (x = 0; x < ARRAY_LEN(modes[dsp->progmode].freqs); x++) {
1646                 if (modes[dsp->progmode].freqs[x]) {
1647                         goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->sample_rate);
1648                         max = x + 1;
1649                 }
1650         }
1651         dsp->freqcount = max;
1652         dsp->ringtimeout = 0;
1653 }
1654
1655 unsigned int ast_dsp_get_sample_rate(const struct ast_dsp *dsp)
1656 {
1657         return dsp->sample_rate;
1658 }
1659
1660 static struct ast_dsp *__ast_dsp_new(unsigned int sample_rate)
1661 {
1662         struct ast_dsp *dsp;
1663
1664         if ((dsp = ast_calloc(1, sizeof(*dsp)))) {
1665                 dsp->threshold = DEFAULT_THRESHOLD;
1666                 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1667                 dsp->busycount = DSP_HISTORY;
1668                 dsp->digitmode = DSP_DIGITMODE_DTMF;
1669                 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1670                 dsp->sample_rate = sample_rate;
1671                 /* Initialize digit detector */
1672                 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF, dsp->sample_rate);
1673                 dsp->display_inband_dtmf_warning = 1;
1674                 /* Initialize initial DSP progress detect parameters */
1675                 ast_dsp_prog_reset(dsp);
1676                 /* Initialize fax detector */
1677                 ast_fax_detect_init(dsp);
1678         }
1679         return dsp;
1680 }
1681
1682 struct ast_dsp *ast_dsp_new(void)
1683 {
1684         return __ast_dsp_new(DEFAULT_SAMPLE_RATE);
1685 }
1686
1687 struct ast_dsp *ast_dsp_new_with_rate(unsigned int sample_rate)
1688 {
1689         return __ast_dsp_new(sample_rate);
1690 }
1691
1692 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1693 {
1694         dsp->features = features;
1695         if (!(features & DSP_FEATURE_DIGIT_DETECT)) {
1696                 dsp->display_inband_dtmf_warning = 0;
1697         }
1698 }
1699
1700 void ast_dsp_free(struct ast_dsp *dsp)
1701 {
1702         ast_free(dsp);
1703 }
1704
1705 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1706 {
1707         dsp->threshold = threshold;
1708 }
1709
1710 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1711 {
1712         if (cadences < 4) {
1713                 cadences = 4;
1714         }
1715         if (cadences > DSP_HISTORY) {
1716                 cadences = DSP_HISTORY;
1717         }
1718         dsp->busycount = cadences;
1719 }
1720
1721 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, const struct ast_dsp_busy_pattern *cadence)
1722 {
1723         dsp->busy_cadence = *cadence;
1724         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);
1725 }
1726
1727 void ast_dsp_digitreset(struct ast_dsp *dsp)
1728 {
1729         int i;
1730
1731         dsp->dtmf_began = 0;
1732         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1733                 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1734                 /* Reinitialise the detector for the next block */
1735                 for (i = 0; i < 6; i++) {
1736                         goertzel_reset(&s->tone_out[i]);
1737                 }
1738                 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = 0;
1739                 s->current_hit = 0;
1740                 s->current_sample = 0;
1741         } else {
1742                 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1743                 /* Reinitialise the detector for the next block */
1744                 for (i = 0; i < 4; i++) {
1745                         goertzel_reset(&s->row_out[i]);
1746                         goertzel_reset(&s->col_out[i]);
1747                 }
1748                 s->lasthit = 0;
1749                 s->current_hit = 0;
1750                 s->energy = 0.0;
1751                 s->current_sample = 0;
1752                 s->hits = 0;
1753                 s->misses = 0;
1754         }
1755
1756         dsp->digit_state.digits[0] = '\0';
1757         dsp->digit_state.current_digits = 0;
1758 }
1759
1760 void ast_dsp_reset(struct ast_dsp *dsp)
1761 {
1762         int x;
1763
1764         dsp->totalsilence = 0;
1765         dsp->gsamps = 0;
1766         for (x = 0; x < 4; x++) {
1767                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1768         }
1769         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1770         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1771         dsp->ringtimeout = 0;
1772 }
1773
1774 int ast_dsp_set_digitmode(struct ast_dsp *dsp, int digitmode)
1775 {
1776         int new;
1777         int old;
1778
1779         old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1780         new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1781         if (old != new) {
1782                 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1783                 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF, dsp->sample_rate);
1784         }
1785         dsp->digitmode = digitmode;
1786         return 0;
1787 }
1788
1789 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1790 {
1791         if (dsp->faxmode != faxmode) {
1792                 dsp->faxmode = faxmode;
1793                 ast_fax_detect_init(dsp);
1794         }
1795         return 0;
1796 }
1797
1798 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1799 {
1800         int x;
1801
1802         for (x = 0; x < ARRAY_LEN(aliases); x++) {
1803                 if (!strcasecmp(aliases[x].name, zone)) {
1804                         dsp->progmode = aliases[x].mode;
1805                         ast_dsp_prog_reset(dsp);
1806                         return 0;
1807                 }
1808         }
1809         return -1;
1810 }
1811
1812 int ast_dsp_was_muted(struct ast_dsp *dsp)
1813 {
1814         return (dsp->mute_fragments > 0);
1815 }
1816
1817 int ast_dsp_get_tstate(struct ast_dsp *dsp)
1818 {
1819         return dsp->tstate;
1820 }
1821
1822 int ast_dsp_get_tcount(struct ast_dsp *dsp)
1823 {
1824         return dsp->tcount;
1825 }
1826
1827 static int _dsp_init(int reload)
1828 {
1829         struct ast_config *cfg;
1830         struct ast_variable *v;
1831         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1832         int cfg_threshold;
1833         float cfg_twist;
1834
1835         if ((cfg = ast_config_load2(CONFIG_FILE_NAME, "dsp", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
1836                 return 0;
1837         }
1838
1839         thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1840         dtmf_normal_twist = DEF_DTMF_NORMAL_TWIST;
1841         dtmf_reverse_twist = DEF_DTMF_REVERSE_TWIST;
1842         relax_dtmf_normal_twist = DEF_RELAX_DTMF_NORMAL_TWIST;
1843         relax_dtmf_reverse_twist = DEF_RELAX_DTMF_REVERSE_TWIST;
1844         dtmf_hits_to_begin = DEF_DTMF_HITS_TO_BEGIN;
1845         dtmf_misses_to_end = DEF_DTMF_MISSES_TO_END;
1846
1847         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
1848                 return 0;
1849         }
1850
1851         for (v = ast_variable_browse(cfg, "default"); v; v = v->next) {
1852                 if (!strcasecmp(v->name, "silencethreshold")) {
1853                         if (sscanf(v->value, "%30d", &cfg_threshold) < 1) {
1854                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1855                         } else if (cfg_threshold < 0) {
1856                                 ast_log(LOG_WARNING, "Invalid silence threshold '%d' specified, using default\n", cfg_threshold);
1857                         } else {
1858                                 thresholds[THRESHOLD_SILENCE] = cfg_threshold;
1859                         }
1860                 } else if (!strcasecmp(v->name, "dtmf_normal_twist")) {
1861                         if (sscanf(v->value, "%30f", &cfg_twist) < 1) {
1862                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1863                         } else if ((cfg_twist < 2.0) || (cfg_twist > 100.0)) {          /* < 3.0dB or > 20dB */
1864                                 ast_log(LOG_WARNING, "Invalid dtmf_normal_twist value '%.2f' specified, using default of %.2f\n", cfg_twist, dtmf_normal_twist);
1865                         } else {
1866                                 dtmf_normal_twist = cfg_twist;
1867                         }
1868                 } else if (!strcasecmp(v->name, "dtmf_reverse_twist")) {
1869                         if (sscanf(v->value, "%30f", &cfg_twist) < 1) {
1870                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1871                         } else if ((cfg_twist < 2.0) || (cfg_twist > 100.0)) {          /* < 3.0dB or > 20dB */
1872                                 ast_log(LOG_WARNING, "Invalid dtmf_reverse_twist value '%.2f' specified, using default of %.2f\n", cfg_twist, dtmf_reverse_twist);
1873                         } else {
1874                                 dtmf_reverse_twist = cfg_twist;
1875                         }
1876                 } else if (!strcasecmp(v->name, "relax_dtmf_normal_twist")) {
1877                         if (sscanf(v->value, "%30f", &cfg_twist) < 1) {
1878                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1879                         } else if ((cfg_twist < 2.0) || (cfg_twist > 100.0)) {          /* < 3.0dB or > 20dB */
1880                                 ast_log(LOG_WARNING, "Invalid relax_dtmf_normal_twist value '%.2f' specified, using default of %.2f\n", cfg_twist, relax_dtmf_normal_twist);
1881                         } else {
1882                                 relax_dtmf_normal_twist = cfg_twist;
1883                         }
1884                 } else if (!strcasecmp(v->name, "relax_dtmf_reverse_twist")) {
1885                         if (sscanf(v->value, "%30f", &cfg_twist) < 1) {
1886                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1887                         } else if ((cfg_twist < 2.0) || (cfg_twist > 100.0)) {          /* < 3.0dB or > 20dB */
1888                                 ast_log(LOG_WARNING, "Invalid relax_dtmf_reverse_twist value '%.2f' specified, using default of %.2f\n", cfg_twist, relax_dtmf_reverse_twist);
1889                         } else {
1890                                 relax_dtmf_reverse_twist = cfg_twist;
1891                         }
1892                 } else if (!strcasecmp(v->name, "dtmf_hits_to_begin")) {
1893                         if (sscanf(v->value, "%30d", &cfg_threshold) < 1) {
1894                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1895                         } else if (cfg_threshold < 1) {         /* must be 1 or greater */
1896                                 ast_log(LOG_WARNING, "Invalid dtmf_hits_to_begin value '%d' specified, using default of %d\n", cfg_threshold, dtmf_hits_to_begin);
1897                         } else {
1898                                 dtmf_hits_to_begin = cfg_threshold;
1899                         }
1900                 } else if (!strcasecmp(v->name, "dtmf_misses_to_end")) {
1901                         if (sscanf(v->value, "%30d", &cfg_threshold) < 1) {
1902                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1903                         } else if (cfg_threshold < 1) {         /* must be 1 or greater */
1904                                 ast_log(LOG_WARNING, "Invalid dtmf_misses_to_end value '%d' specified, using default of %d\n", cfg_threshold, dtmf_misses_to_end);
1905                         } else {
1906                                 dtmf_misses_to_end = cfg_threshold;
1907                         }
1908                 }
1909         }
1910         ast_config_destroy(cfg);
1911
1912         return 0;
1913 }
1914
1915 int ast_dsp_get_threshold_from_settings(enum threshold which)
1916 {
1917         return thresholds[which];
1918 }
1919
1920 int ast_dsp_init(void)
1921 {
1922         return _dsp_init(0);
1923 }
1924
1925 int ast_dsp_reload(void)
1926 {
1927         return _dsp_init(1);
1928 }