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