loader: Fix comments in struct ast_module.
[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 #include <math.h>
59
60 #include "asterisk/frame.h"
61 #include "asterisk/format_cache.h"
62 #include "asterisk/channel.h"
63 #include "asterisk/dsp.h"
64 #include "asterisk/ulaw.h"
65 #include "asterisk/alaw.h"
66 #include "asterisk/utils.h"
67 #include "asterisk/options.h"
68 #include "asterisk/config.h"
69 #include "asterisk/test.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 #define FREQ_ARRAY_SIZE 7
115
116 static struct progress {
117         enum gsamp_size size;
118         int freqs[FREQ_ARRAY_SIZE];
119 } modes[] = {
120         { GSAMP_SIZE_NA, { 350, 440, 480, 620, 950, 1400, 1800 } },     /*!< North America */
121         { GSAMP_SIZE_CR, { 425 } },                                     /*!< Costa Rica, Brazil */
122         { GSAMP_SIZE_UK, { 350, 400, 440 } },                           /*!< UK */
123 };
124
125 /*!\brief This value is the minimum threshold, calculated by averaging all
126  * of the samples within a frame, for which a frame is determined to either
127  * be silence (below the threshold) or noise (above the threshold).  Please
128  * note that while the default threshold is an even exponent of 2, there is
129  * no requirement that it be so.  The threshold will accept any value between
130  * 0 and 32767.
131  */
132 #define DEFAULT_THRESHOLD       512
133
134 enum busy_detect {
135         BUSY_PERCENT = 10,      /*!< The percentage difference between the two last silence periods */
136         BUSY_PAT_PERCENT = 7,   /*!< The percentage difference between measured and actual pattern */
137         BUSY_THRESHOLD = 100,   /*!< Max number of ms difference between max and min times in busy */
138         BUSY_MIN = 75,          /*!< Busy must be at least 80 ms in half-cadence */
139         BUSY_MAX = 3100         /*!< Busy can't be longer than 3100 ms in half-cadence */
140 };
141
142 /*! Remember last 15 units */
143 #define DSP_HISTORY             15
144
145 #define TONE_THRESH             10.0    /*!< How much louder the tone should be than channel energy */
146 #define TONE_MIN_THRESH         1e8     /*!< How much tone there should be at least to attempt */
147
148 /*! All THRESH_XXX values are in GSAMP_SIZE chunks (us = 22ms) */
149 enum gsamp_thresh {
150         THRESH_RING = 8,                /*!< Need at least 150ms ring to accept */
151         THRESH_TALK = 2,                /*!< Talk detection does not work continuously */
152         THRESH_BUSY = 4,                /*!< Need at least 80ms to accept */
153         THRESH_CONGESTION = 4,          /*!< Need at least 80ms to accept */
154         THRESH_HANGUP = 60,             /*!< Need at least 1300ms to accept hangup */
155         THRESH_RING2ANSWER = 300        /*!< Timeout from start of ring to answer (about 6600 ms) */
156 };
157
158 #define MAX_DTMF_DIGITS         128
159
160 /* Basic DTMF (AT&T) specs:
161  *
162  * Minimum tone on = 40ms
163  * Minimum tone off = 50ms
164  * Maximum digit rate = 10 per second
165  * Normal twist <= 8dB accepted
166  * Reverse twist <= 4dB accepted
167  * S/N >= 15dB will detect OK
168  * Attenuation <= 26dB will detect OK
169  * Frequency tolerance +- 1.5% will detect, +-3.5% will reject
170  */
171
172 #define DTMF_THRESHOLD          8.0e7
173 #define TONE_THRESHOLD          7.8e7
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_TO_TOTAL_ENERGY    42.0
189
190 #define BELL_MF_THRESHOLD       1.6e9
191 #define BELL_MF_TWIST           4.0     /* 6dB */
192 #define BELL_MF_RELATIVE_PEAK   12.6    /* 11dB */
193
194 #if defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
195 #error You cant use BUSYDETECT_TONEONLY together with BUSYDETECT_COMPARE_TONE_AND_SILENCE
196 #endif
197
198 /* The CNG signal consists of the transmission of 1100 Hz for 1/2 second,
199  * followed by a 3 second silent (2100 Hz OFF) period.
200  */
201 #define FAX_TONE_CNG_FREQ       1100
202 #define FAX_TONE_CNG_DURATION   500     /* ms */
203 #define FAX_TONE_CNG_DB         16
204
205 /* This signal may be sent by the Terminating FAX machine anywhere between
206  * 1.8 to 2.5 seconds AFTER answering the call.  The CED signal consists
207  * of a 2100 Hz tone that is from 2.6 to 4 seconds in duration.
208 */
209 #define FAX_TONE_CED_FREQ       2100
210 #define FAX_TONE_CED_DURATION   2600    /* ms */
211 #define FAX_TONE_CED_DB         16
212
213 #define DEFAULT_SAMPLE_RATE             8000
214
215 /* MF goertzel size */
216 #define MF_GSIZE                120
217
218 /* DTMF goertzel size */
219 #define DTMF_GSIZE              102
220
221 /* How many successive hits needed to consider begin of a digit
222  * IE. Override with dtmf_hits_to_begin=4 in dsp.conf
223  */
224 #define DEF_DTMF_HITS_TO_BEGIN  2
225
226 /* How many successive misses needed to consider end of a digit
227  * IE. Override with dtmf_misses_to_end=4 in dsp.conf
228  */
229 #define DEF_DTMF_MISSES_TO_END  3
230
231 /*!
232  * \brief The default silence threshold we will use if an alternate
233  * configured value is not present or is invalid.
234  */
235 static const int DEFAULT_SILENCE_THRESHOLD = 256;
236
237 #define CONFIG_FILE_NAME "dsp.conf"
238
239 typedef struct {
240         /*! The previous previous sample calculation (No binary point just plain int) */
241         int v2;
242         /*! The previous sample calculation (No binary point just plain int) */
243         int v3;
244         /*! v2 and v3 power of two exponent to keep value in int range */
245         int chunky;
246         /*! 15 bit fixed point goertzel coefficient = 2 * cos(2 * pi * freq / sample_rate) */
247         int fac;
248 } goertzel_state_t;
249
250 typedef struct {
251         int value;
252         int power;
253 } goertzel_result_t;
254
255 typedef struct
256 {
257         int freq;
258         int block_size;
259         int squelch;            /* Remove (squelch) tone */
260         goertzel_state_t tone;
261         float energy;           /* Accumulated energy of the current block */
262         int samples_pending;    /* Samples remain to complete the current block */
263         int mute_samples;       /* How many additional samples needs to be muted to suppress already detected tone */
264
265         int hits_required;      /* How many successive blocks with tone we are looking for */
266         float threshold;        /* Energy of the tone relative to energy from all other signals to consider a hit */
267
268         int hit_count;          /* How many successive blocks we consider tone present */
269         int last_hit;           /* Indicates if the last processed block was a hit */
270
271 } tone_detect_state_t;
272
273 typedef struct
274 {
275         goertzel_state_t row_out[4];
276         goertzel_state_t col_out[4];
277         int hits;                       /* How many successive hits we have seen already */
278         int misses;                     /* How many successive misses we have seen already */
279         int lasthit;
280         int current_hit;
281         float energy;
282         int current_sample;
283         int mute_samples;
284 } dtmf_detect_state_t;
285
286 typedef struct
287 {
288         goertzel_state_t tone_out[6];
289         int current_hit;
290         int hits[5];
291         int current_sample;
292         int mute_samples;
293 } mf_detect_state_t;
294
295 typedef struct
296 {
297         char digits[MAX_DTMF_DIGITS + 1];
298         int digitlen[MAX_DTMF_DIGITS + 1];
299         int current_digits;
300         int detected_digits;
301         int lost_digits;
302
303         union {
304                 dtmf_detect_state_t dtmf;
305                 mf_detect_state_t mf;
306         } td;
307 } digit_detect_state_t;
308
309 static const float dtmf_row[] = {
310         697.0,  770.0,  852.0,  941.0
311 };
312 static const float dtmf_col[] = {
313         1209.0, 1336.0, 1477.0, 1633.0
314 };
315 static const float mf_tones[] = {
316         700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
317 };
318 static const char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
319 static const char bell_mf_positions[] = "1247C-358A--69*---0B----#";
320 static int thresholds[THRESHOLD_MAX];
321 static float dtmf_normal_twist;         /* AT&T = 8dB */
322 static float dtmf_reverse_twist;        /* AT&T = 4dB */
323 static float relax_dtmf_normal_twist;   /* AT&T = 8dB */
324 static float relax_dtmf_reverse_twist;  /* AT&T = 6dB */
325 static int dtmf_hits_to_begin;          /* How many successive hits needed to consider begin of a digit */
326 static int dtmf_misses_to_end;          /* How many successive misses needed to consider end of a digit */
327
328 static inline void goertzel_sample(goertzel_state_t *s, short sample)
329 {
330         int v1;
331
332         /*
333          * Shift previous values so
334          * v1 is previous previous value
335          * v2 is previous value
336          * until the new v3 is calculated.
337          */
338         v1 = s->v2;
339         s->v2 = s->v3;
340
341         /* Discard the binary fraction introduced by s->fac */
342         s->v3 = (s->fac * s->v2) >> 15;
343         /* Scale sample to match previous values */
344         s->v3 = s->v3 - v1 + (sample >> s->chunky);
345
346         if (abs(s->v3) > (1 << 15)) {
347                 /* The result is now too large so increase the chunky power. */
348                 s->chunky++;
349                 s->v3 = s->v3 >> 1;
350                 s->v2 = s->v2 >> 1;
351         }
352 }
353
354 static inline float goertzel_result(goertzel_state_t *s)
355 {
356         goertzel_result_t r;
357
358         r.value = (s->v3 * s->v3) + (s->v2 * s->v2);
359         r.value -= ((s->v2 * s->v3) >> 15) * s->fac;
360         /*
361          * We have to double the exponent because we multiplied the
362          * previous sample calculation values together.
363          */
364         r.power = s->chunky * 2;
365         return (float)r.value * (float)(1 << r.power);
366 }
367
368 static inline void goertzel_init(goertzel_state_t *s, float freq, unsigned int sample_rate)
369 {
370         s->v2 = s->v3 = s->chunky = 0;
371         s->fac = (int)(32768.0 * 2.0 * cos(2.0 * M_PI * freq / sample_rate));
372 }
373
374 static inline void goertzel_reset(goertzel_state_t *s)
375 {
376         s->v2 = s->v3 = s->chunky = 0;
377 }
378
379 typedef struct {
380         int start;
381         int end;
382 } fragment_t;
383
384 /* Note on tone suppression (squelching). Individual detectors (DTMF/MF/generic tone)
385  * report fragments of the frame in which detected tone resides and which needs
386  * to be "muted" in order to suppress the tone. To mark fragment for muting,
387  * detectors call mute_fragment passing fragment_t there. Multiple fragments
388  * can be marked and ast_dsp_process later will mute all of them.
389  *
390  * Note: When tone starts in the middle of a Goertzel block, it won't be properly
391  * detected in that block, only in the next. If we only mute the next block
392  * where tone is actually detected, the user will still hear beginning
393  * of the tone in preceeding block. This is why we usually want to mute some amount
394  * of samples preceeding and following the block where tone was detected.
395 */
396
397 struct ast_dsp {
398         struct ast_frame f;
399         int threshold;
400         int totalsilence;
401         int totalnoise;
402         int features;
403         int ringtimeout;
404         int busymaybe;
405         int busycount;
406         struct ast_dsp_busy_pattern busy_cadence;
407         int historicnoise[DSP_HISTORY];
408         int historicsilence[DSP_HISTORY];
409         goertzel_state_t freqs[FREQ_ARRAY_SIZE];
410         int freqcount;
411         int gsamps;
412         enum gsamp_size gsamp_size;
413         enum prog_mode progmode;
414         int tstate;
415         int tcount;
416         int digitmode;
417         int faxmode;
418         int dtmf_began;
419         int display_inband_dtmf_warning;
420         float genergy;
421         int mute_fragments;
422         unsigned int sample_rate;
423         fragment_t mute_data[5];
424         digit_detect_state_t digit_state;
425         tone_detect_state_t cng_tone_state;
426         tone_detect_state_t ced_tone_state;
427 };
428
429 static void mute_fragment(struct ast_dsp *dsp, fragment_t *fragment)
430 {
431         if (dsp->mute_fragments >= ARRAY_LEN(dsp->mute_data)) {
432                 ast_log(LOG_ERROR, "Too many fragments to mute. Ignoring\n");
433                 return;
434         }
435
436         dsp->mute_data[dsp->mute_fragments++] = *fragment;
437 }
438
439 static void ast_tone_detect_init(tone_detect_state_t *s, int freq, int duration, int amp, unsigned int sample_rate)
440 {
441         int duration_samples;
442         float x;
443         int periods_in_block;
444
445         s->freq = freq;
446
447         /* Desired tone duration in samples */
448         duration_samples = duration * sample_rate / 1000;
449         /* We want to allow 10% deviation of tone duration */
450         duration_samples = duration_samples * 9 / 10;
451
452         /* If we want to remove tone, it is important to have block size not
453            to exceed frame size. Otherwise by the moment tone is detected it is too late
454            to squelch it from previous frames. Block size is 20ms at the given sample rate.*/
455         s->block_size = (20 * sample_rate) / 1000;
456
457         periods_in_block = s->block_size * freq / sample_rate;
458
459         /* Make sure we will have at least 5 periods at target frequency for analisys.
460            This may make block larger than expected packet and will make squelching impossible
461            but at least we will be detecting the tone */
462         if (periods_in_block < 5) {
463                 periods_in_block = 5;
464         }
465
466         /* Now calculate final block size. It will contain integer number of periods */
467         s->block_size = periods_in_block * sample_rate / freq;
468
469         /* tone_detect is currently only used to detect fax tones and we
470            do not need squelching the fax tones */
471         s->squelch = 0;
472
473         /* Account for the first and the last block to be incomplete
474            and thus no tone will be detected in them */
475         s->hits_required = (duration_samples - (s->block_size - 1)) / s->block_size;
476
477         goertzel_init(&s->tone, freq, sample_rate);
478
479         s->samples_pending = s->block_size;
480         s->hit_count = 0;
481         s->last_hit = 0;
482         s->energy = 0.0;
483
484         /* We want tone energy to be amp decibels above the rest of the signal (the noise).
485            According to Parseval's theorem the energy computed in time domain equals to energy
486            computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
487            from the energy in the time domain we will get energy of the remaining signal (without the tone
488            we are detecting). We will be checking that
489                 10*log(Ew / (Et - Ew)) > amp
490            Calculate threshold so that we will be actually checking
491                 Ew > Et * threshold
492         */
493
494         x = pow(10.0, amp / 10.0);
495         s->threshold = x / (x + 1);
496
497         ast_debug(1, "Setup tone %d Hz, %d ms, block_size=%d, hits_required=%d\n", freq, duration, s->block_size, s->hits_required);
498 }
499
500 static void ast_fax_detect_init(struct ast_dsp *s)
501 {
502         ast_tone_detect_init(&s->cng_tone_state, FAX_TONE_CNG_FREQ, FAX_TONE_CNG_DURATION, FAX_TONE_CNG_DB, s->sample_rate);
503         ast_tone_detect_init(&s->ced_tone_state, FAX_TONE_CED_FREQ, FAX_TONE_CED_DURATION, FAX_TONE_CED_DB, s->sample_rate);
504         if (s->faxmode & DSP_FAXMODE_DETECT_SQUELCH) {
505                 s->cng_tone_state.squelch = 1;
506                 s->ced_tone_state.squelch = 1;
507         }
508
509 }
510
511 static void ast_dtmf_detect_init(dtmf_detect_state_t *s, unsigned int sample_rate)
512 {
513         int i;
514
515         for (i = 0; i < 4; i++) {
516                 goertzel_init(&s->row_out[i], dtmf_row[i], sample_rate);
517                 goertzel_init(&s->col_out[i], dtmf_col[i], sample_rate);
518         }
519         s->lasthit = 0;
520         s->current_hit = 0;
521         s->energy = 0.0;
522         s->current_sample = 0;
523         s->hits = 0;
524         s->misses = 0;
525 }
526
527 static void ast_mf_detect_init(mf_detect_state_t *s, unsigned int sample_rate)
528 {
529         int i;
530
531         for (i = 0; i < 6; i++) {
532                 goertzel_init(&s->tone_out[i], mf_tones[i], sample_rate);
533         }
534         s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
535         s->current_sample = 0;
536         s->current_hit = 0;
537 }
538
539 static void ast_digit_detect_init(digit_detect_state_t *s, int mf, unsigned int sample_rate)
540 {
541         s->current_digits = 0;
542         s->detected_digits = 0;
543         s->lost_digits = 0;
544         s->digits[0] = '\0';
545
546         if (mf) {
547                 ast_mf_detect_init(&s->td.mf, sample_rate);
548         } else {
549                 ast_dtmf_detect_init(&s->td.dtmf, sample_rate);
550         }
551 }
552
553 static int tone_detect(struct ast_dsp *dsp, tone_detect_state_t *s, int16_t *amp, int samples)
554 {
555         float tone_energy;
556         int i;
557         int hit = 0;
558         int limit;
559         int res = 0;
560         int16_t *ptr;
561         short samp;
562         int start, end;
563         fragment_t mute = {0, 0};
564
565         if (s->squelch && s->mute_samples > 0) {
566                 mute.end = (s->mute_samples < samples) ? s->mute_samples : samples;
567                 s->mute_samples -= mute.end;
568         }
569
570         for (start = 0; start < samples; start = end) {
571                 /* Process in blocks. */
572                 limit = samples - start;
573                 if (limit > s->samples_pending) {
574                         limit = s->samples_pending;
575                 }
576                 end = start + limit;
577
578                 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
579                         samp = *ptr;
580                         /* signed 32 bit int should be enough to square any possible signed 16 bit value */
581                         s->energy += (int32_t) samp * (int32_t) samp;
582
583                         goertzel_sample(&s->tone, samp);
584                 }
585
586                 s->samples_pending -= limit;
587
588                 if (s->samples_pending) {
589                         /* Finished incomplete (last) block */
590                         break;
591                 }
592
593                 tone_energy = goertzel_result(&s->tone);
594
595                 /* Scale to make comparable */
596                 tone_energy *= 2.0;
597                 s->energy *= s->block_size;
598
599                 ast_debug(10, "%d Hz tone %2d Ew=%.4E, Et=%.4E, s/n=%10.2f\n", s->freq, s->hit_count, tone_energy, s->energy, tone_energy / (s->energy - tone_energy));
600                 hit = 0;
601                 if (TONE_THRESHOLD <= tone_energy
602                         && tone_energy > s->energy * s->threshold) {
603                         ast_debug(10, "%d Hz tone Hit! %2d Ew=%.4E, Et=%.4E, s/n=%10.2f\n", s->freq, s->hit_count, tone_energy, s->energy, tone_energy / (s->energy - tone_energy));
604                         hit = 1;
605                 }
606
607                 if (s->hit_count) {
608                         s->hit_count++;
609                 }
610
611                 if (hit == s->last_hit) {
612                         if (!hit) {
613                                 /* Two successive misses. Tone ended */
614                                 s->hit_count = 0;
615                         } else if (!s->hit_count) {
616                                 s->hit_count++;
617                         }
618
619                 }
620
621                 if (s->hit_count == s->hits_required) {
622                         ast_debug(1, "%d Hz tone detected\n", s->freq);
623                         res = 1;
624                 }
625
626                 s->last_hit = hit;
627
628                 /* If we had a hit in this block, include it into mute fragment */
629                 if (s->squelch && hit) {
630                         if (mute.end < start - s->block_size) {
631                                 /* There is a gap between fragments */
632                                 mute_fragment(dsp, &mute);
633                                 mute.start = (start > s->block_size) ? (start - s->block_size) : 0;
634                         }
635                         mute.end = end + s->block_size;
636                 }
637
638                 /* Reinitialise the detector for the next block */
639                 /* Reset for the next block */
640                 goertzel_reset(&s->tone);
641
642                 /* Advance to the next block */
643                 s->energy = 0.0;
644                 s->samples_pending = s->block_size;
645
646                 amp += limit;
647         }
648
649         if (s->squelch && mute.end) {
650                 if (mute.end > samples) {
651                         s->mute_samples = mute.end - samples;
652                         mute.end = samples;
653                 }
654                 mute_fragment(dsp, &mute);
655         }
656
657         return res;
658 }
659
660 static void store_digit(digit_detect_state_t *s, char digit)
661 {
662         s->detected_digits++;
663         if (s->current_digits < MAX_DTMF_DIGITS) {
664                 s->digitlen[s->current_digits] = 0;
665                 s->digits[s->current_digits++] = digit;
666                 s->digits[s->current_digits] = '\0';
667         } else {
668                 ast_log(LOG_WARNING, "Digit lost due to full buffer\n");
669                 s->lost_digits++;
670         }
671 }
672
673 static int dtmf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[], int samples, int squelch, int relax)
674 {
675         float row_energy[4];
676         float col_energy[4];
677         int i;
678         int j;
679         int sample;
680         short samp;
681         int best_row;
682         int best_col;
683         int hit;
684         int limit;
685         fragment_t mute = {0, 0};
686
687         if (squelch && s->td.dtmf.mute_samples > 0) {
688                 mute.end = (s->td.dtmf.mute_samples < samples) ? s->td.dtmf.mute_samples : samples;
689                 s->td.dtmf.mute_samples -= mute.end;
690         }
691
692         hit = 0;
693         for (sample = 0; sample < samples; sample = limit) {
694                 /* DTMF_GSIZE is optimised to meet the DTMF specs. */
695                 if ((samples - sample) >= (DTMF_GSIZE - s->td.dtmf.current_sample)) {
696                         limit = sample + (DTMF_GSIZE - s->td.dtmf.current_sample);
697                 } else {
698                         limit = samples;
699                 }
700                 /* The following unrolled loop takes only 35% (rough estimate) of the
701                    time of a rolled loop on the machine on which it was developed */
702                 for (j = sample; j < limit; j++) {
703                         samp = amp[j];
704                         s->td.dtmf.energy += (int32_t) samp * (int32_t) samp;
705                         /* With GCC 2.95, the following unrolled code seems to take about 35%
706                            (rough estimate) as long as a neat little 0-3 loop */
707                         goertzel_sample(s->td.dtmf.row_out, samp);
708                         goertzel_sample(s->td.dtmf.col_out, samp);
709                         goertzel_sample(s->td.dtmf.row_out + 1, samp);
710                         goertzel_sample(s->td.dtmf.col_out + 1, samp);
711                         goertzel_sample(s->td.dtmf.row_out + 2, samp);
712                         goertzel_sample(s->td.dtmf.col_out + 2, samp);
713                         goertzel_sample(s->td.dtmf.row_out + 3, samp);
714                         goertzel_sample(s->td.dtmf.col_out + 3, samp);
715                 }
716                 s->td.dtmf.current_sample += (limit - sample);
717                 if (s->td.dtmf.current_sample < DTMF_GSIZE) {
718                         continue;
719                 }
720                 /* We are at the end of a DTMF detection block */
721                 /* Find the peak row and the peak column */
722                 row_energy[0] = goertzel_result(&s->td.dtmf.row_out[0]);
723                 col_energy[0] = goertzel_result(&s->td.dtmf.col_out[0]);
724
725                 for (best_row = best_col = 0, i = 1; i < 4; i++) {
726                         row_energy[i] = goertzel_result(&s->td.dtmf.row_out[i]);
727                         if (row_energy[i] > row_energy[best_row]) {
728                                 best_row = i;
729                         }
730                         col_energy[i] = goertzel_result(&s->td.dtmf.col_out[i]);
731                         if (col_energy[i] > col_energy[best_col]) {
732                                 best_col = i;
733                         }
734                 }
735                 ast_debug(10, "DTMF best '%c' Erow=%.4E Ecol=%.4E Erc=%.4E Et=%.4E\n",
736                         dtmf_positions[(best_row << 2) + best_col],
737                         row_energy[best_row], col_energy[best_col],
738                         row_energy[best_row] + col_energy[best_col], s->td.dtmf.energy);
739                 hit = 0;
740                 /* Basic signal level test and the twist test */
741                 if (row_energy[best_row] >= DTMF_THRESHOLD &&
742                     col_energy[best_col] >= DTMF_THRESHOLD &&
743                     col_energy[best_col] < row_energy[best_row] * (relax ? relax_dtmf_reverse_twist : dtmf_reverse_twist) &&
744                     row_energy[best_row] < col_energy[best_col] * (relax ? relax_dtmf_normal_twist : dtmf_normal_twist)) {
745                         /* Relative peak test */
746                         for (i = 0; i < 4; i++) {
747                                 if ((i != best_col &&
748                                     col_energy[i] * DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
749                                     (i != best_row
750                                      && row_energy[i] * DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
751                                         break;
752                                 }
753                         }
754                         /* ... and fraction of total energy test */
755                         if (i >= 4 &&
756                             (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY * s->td.dtmf.energy) {
757                                 /* Got a hit */
758                                 hit = dtmf_positions[(best_row << 2) + best_col];
759                                 ast_debug(10, "DTMF hit '%c'\n", hit);
760                         }
761                 }
762
763 /*
764  * Adapted from ETSI ES 201 235-3 V1.3.1 (2006-03)
765  * (40ms reference is tunable with hits_to_begin and misses_to_end)
766  * each hit/miss is 12.75ms with DTMF_GSIZE at 102
767  *
768  * Character recognition: When not DRC *(1) and then
769  *      Shall exist VSC > 40 ms (hits_to_begin)
770  *      May exist 20 ms <= VSC <= 40 ms
771  *      Shall not exist VSC < 20 ms
772  *
773  * Character recognition: When DRC and then
774  *      Shall cease Not VSC > 40 ms (misses_to_end)
775  *      May cease 20 ms >= Not VSC >= 40 ms
776  *      Shall not cease Not VSC < 20 ms
777  *
778  * *(1) or optionally a different digit recognition condition
779  *
780  * Legend: VSC The continuous existence of a valid signal condition.
781  *      Not VSC The continuous non-existence of valid signal condition.
782  *      DRC The existence of digit recognition condition.
783  *      Not DRC The non-existence of digit recognition condition.
784  */
785
786 /*
787  * Example: hits_to_begin=2 misses_to_end=3
788  * -------A last_hit=A hits=0&1
789  * ------AA hits=2 current_hit=A misses=0       BEGIN A
790  * -----AA- misses=1 last_hit=' ' hits=0
791  * ----AA-- misses=2
792  * ---AA--- misses=3 current_hit=' '            END A
793  * --AA---B last_hit=B hits=0&1
794  * -AA---BC last_hit=C hits=0&1
795  * AA---BCC hits=2 current_hit=C misses=0       BEGIN C
796  * A---BCC- misses=1 last_hit=' ' hits=0
797  * ---BCC-C misses=0 last_hit=C hits=0&1
798  * --BCC-CC misses=0
799  *
800  * Example: hits_to_begin=3 misses_to_end=2
801  * -------A last_hit=A hits=0&1
802  * ------AA hits=2
803  * -----AAA hits=3 current_hit=A misses=0       BEGIN A
804  * ----AAAB misses=1 last_hit=B hits=0&1
805  * ---AAABB misses=2 current_hit=' ' hits=2     END A
806  * --AAABBB hits=3 current_hit=B misses=0       BEGIN B
807  * -AAABBBB misses=0
808  *
809  * Example: hits_to_begin=2 misses_to_end=2
810  * -------A last_hit=A hits=0&1
811  * ------AA hits=2 current_hit=A misses=0       BEGIN A
812  * -----AAB misses=1 hits=0&1
813  * ----AABB misses=2 current_hit=' ' hits=2 current_hit=B misses=0 BEGIN B
814  * ---AABBB misses=0
815  */
816
817                 if (s->td.dtmf.current_hit) {
818                         /* We are in the middle of a digit already */
819                         if (hit != s->td.dtmf.current_hit) {
820                                 s->td.dtmf.misses++;
821                                 if (s->td.dtmf.misses == dtmf_misses_to_end) {
822                                         /* There were enough misses to consider digit ended */
823                                         s->td.dtmf.current_hit = 0;
824                                 }
825                         } else {
826                                 s->td.dtmf.misses = 0;
827                                 /* Current hit was same as last, so increment digit duration (of last digit) */
828                                 s->digitlen[s->current_digits - 1] += DTMF_GSIZE;
829                         }
830                 }
831
832                 /* Look for a start of a new digit no matter if we are already in the middle of some
833                    digit or not. This is because hits_to_begin may be smaller than misses_to_end
834                    and we may find begin of new digit before we consider last one ended. */
835
836                 if (hit != s->td.dtmf.lasthit) {
837                         s->td.dtmf.lasthit = hit;
838                         s->td.dtmf.hits = 0;
839                 }
840                 if (hit && hit != s->td.dtmf.current_hit) {
841                         s->td.dtmf.hits++;
842                         if (s->td.dtmf.hits == dtmf_hits_to_begin) {
843                                 store_digit(s, hit);
844                                 s->digitlen[s->current_digits - 1] = dtmf_hits_to_begin * DTMF_GSIZE;
845                                 s->td.dtmf.current_hit = hit;
846                                 s->td.dtmf.misses = 0;
847                         }
848                 }
849
850                 /* If we had a hit in this block, include it into mute fragment */
851                 if (squelch && hit) {
852                         if (mute.end < sample - DTMF_GSIZE) {
853                                 /* There is a gap between fragments */
854                                 mute_fragment(dsp, &mute);
855                                 mute.start = (sample > DTMF_GSIZE) ? (sample - DTMF_GSIZE) : 0;
856                         }
857                         mute.end = limit + DTMF_GSIZE;
858                 }
859
860                 /* Reinitialise the detector for the next block */
861                 for (i = 0; i < 4; i++) {
862                         goertzel_reset(&s->td.dtmf.row_out[i]);
863                         goertzel_reset(&s->td.dtmf.col_out[i]);
864                 }
865                 s->td.dtmf.energy = 0.0;
866                 s->td.dtmf.current_sample = 0;
867         }
868
869         if (squelch && mute.end) {
870                 if (mute.end > samples) {
871                         s->td.dtmf.mute_samples = mute.end - samples;
872                         mute.end = samples;
873                 }
874                 mute_fragment(dsp, &mute);
875         }
876
877         return (s->td.dtmf.current_hit);        /* return the debounced hit */
878 }
879
880 static int mf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[],
881                 int samples, int squelch, int relax)
882 {
883         float energy[6];
884         int best;
885         int second_best;
886         int i;
887         int j;
888         int sample;
889         short samp;
890         int hit;
891         int limit;
892         fragment_t mute = {0, 0};
893
894         if (squelch && s->td.mf.mute_samples > 0) {
895                 mute.end = (s->td.mf.mute_samples < samples) ? s->td.mf.mute_samples : samples;
896                 s->td.mf.mute_samples -= mute.end;
897         }
898
899         hit = 0;
900         for (sample = 0; sample < samples; sample = limit) {
901                 /* 80 is optimised to meet the MF specs. */
902                 /* XXX So then why is MF_GSIZE defined as 120? */
903                 if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample)) {
904                         limit = sample + (MF_GSIZE - s->td.mf.current_sample);
905                 } else {
906                         limit = samples;
907                 }
908                 /* The following unrolled loop takes only 35% (rough estimate) of the
909                    time of a rolled loop on the machine on which it was developed */
910                 for (j = sample; j < limit; j++) {
911                         /* With GCC 2.95, the following unrolled code seems to take about 35%
912                            (rough estimate) as long as a neat little 0-3 loop */
913                         samp = amp[j];
914                         goertzel_sample(s->td.mf.tone_out, samp);
915                         goertzel_sample(s->td.mf.tone_out + 1, samp);
916                         goertzel_sample(s->td.mf.tone_out + 2, samp);
917                         goertzel_sample(s->td.mf.tone_out + 3, samp);
918                         goertzel_sample(s->td.mf.tone_out + 4, samp);
919                         goertzel_sample(s->td.mf.tone_out + 5, samp);
920                 }
921                 s->td.mf.current_sample += (limit - sample);
922                 if (s->td.mf.current_sample < MF_GSIZE) {
923                         continue;
924                 }
925                 /* We're at the end of an MF detection block.  */
926                 /* Find the two highest energies. The spec says to look for
927                    two tones and two tones only. Taking this literally -ie
928                    only two tones pass the minimum threshold - doesn't work
929                    well. The sinc function mess, due to rectangular windowing
930                    ensure that! Find the two highest energies and ensure they
931                    are considerably stronger than any of the others. */
932                 energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
933                 energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
934                 if (energy[0] > energy[1]) {
935                         best = 0;
936                         second_best = 1;
937                 } else {
938                         best = 1;
939                         second_best = 0;
940                 }
941                 /*endif*/
942                 for (i = 2; i < 6; i++) {
943                         energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
944                         if (energy[i] >= energy[best]) {
945                                 second_best = best;
946                                 best = i;
947                         } else if (energy[i] >= energy[second_best]) {
948                                 second_best = i;
949                         }
950                 }
951                 /* Basic signal level and twist tests */
952                 hit = 0;
953                 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
954                     && energy[best] < energy[second_best]*BELL_MF_TWIST
955                     && energy[best] * BELL_MF_TWIST > energy[second_best]) {
956                         /* Relative peak test */
957                         hit = -1;
958                         for (i = 0; i < 6; i++) {
959                                 if (i != best && i != second_best) {
960                                         if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
961                                                 /* The best two are not clearly the best */
962                                                 hit = 0;
963                                                 break;
964                                         }
965                                 }
966                         }
967                 }
968                 if (hit) {
969                         /* Get the values into ascending order */
970                         if (second_best < best) {
971                                 i = best;
972                                 best = second_best;
973                                 second_best = i;
974                         }
975                         best = best * 5 + second_best - 1;
976                         hit = bell_mf_positions[best];
977                         /* Look for two successive similar results */
978                         /* The logic in the next test is:
979                            For KP we need 4 successive identical clean detects, with
980                            two blocks of something different preceeding it. For anything
981                            else we need two successive identical clean detects, with
982                            two blocks of something different preceeding it. */
983                         if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
984                            ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
985                             (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] &&
986                             hit != s->td.mf.hits[0]))) {
987                                 store_digit(s, hit);
988                         }
989                 }
990
991
992                 if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
993                         /* Two successive block without a hit terminate current digit */
994                         s->td.mf.current_hit = 0;
995                 }
996
997                 s->td.mf.hits[0] = s->td.mf.hits[1];
998                 s->td.mf.hits[1] = s->td.mf.hits[2];
999                 s->td.mf.hits[2] = s->td.mf.hits[3];
1000                 s->td.mf.hits[3] = s->td.mf.hits[4];
1001                 s->td.mf.hits[4] = hit;
1002
1003                 /* If we had a hit in this block, include it into mute fragment */
1004                 if (squelch && hit) {
1005                         if (mute.end < sample - MF_GSIZE) {
1006                                 /* There is a gap between fragments */
1007                                 mute_fragment(dsp, &mute);
1008                                 mute.start = (sample > MF_GSIZE) ? (sample - MF_GSIZE) : 0;
1009                         }
1010                         mute.end = limit + MF_GSIZE;
1011                 }
1012
1013                 /* Reinitialise the detector for the next block */
1014                 for (i = 0; i < 6; i++) {
1015                         goertzel_reset(&s->td.mf.tone_out[i]);
1016                 }
1017                 s->td.mf.current_sample = 0;
1018         }
1019
1020         if (squelch && mute.end) {
1021                 if (mute.end > samples) {
1022                         s->td.mf.mute_samples = mute.end - samples;
1023                         mute.end = samples;
1024                 }
1025                 mute_fragment(dsp, &mute);
1026         }
1027
1028         return (s->td.mf.current_hit); /* return the debounced hit */
1029 }
1030
1031 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
1032 {
1033         /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
1034         /* Make sure absolute levels are high enough */
1035         if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH)) {
1036                 return 0;
1037         }
1038         /* Amplify ignored stuff */
1039         i2 *= TONE_THRESH;
1040         i1 *= TONE_THRESH;
1041         e *= TONE_THRESH;
1042         /* Check first tone */
1043         if ((p1 < i1) || (p1 < i2) || (p1 < e)) {
1044                 return 0;
1045         }
1046         /* And second */
1047         if ((p2 < i1) || (p2 < i2) || (p2 < e)) {
1048                 return 0;
1049         }
1050         /* Guess it's there... */
1051         return 1;
1052 }
1053
1054 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
1055 {
1056         short samp;
1057         int x;
1058         int y;
1059         int pass;
1060         int newstate = DSP_TONE_STATE_SILENCE;
1061         int res = 0;
1062         int freqcount = dsp->freqcount > FREQ_ARRAY_SIZE ? FREQ_ARRAY_SIZE : dsp->freqcount;
1063
1064         while (len) {
1065                 /* Take the lesser of the number of samples we need and what we have */
1066                 pass = len;
1067                 if (pass > dsp->gsamp_size - dsp->gsamps) {
1068                         pass = dsp->gsamp_size - dsp->gsamps;
1069                 }
1070                 for (x = 0; x < pass; x++) {
1071                         samp = s[x];
1072                         dsp->genergy += (int32_t) samp * (int32_t) samp;
1073                         for (y = 0; y < freqcount; y++) {
1074                                 goertzel_sample(&dsp->freqs[y], samp);
1075                         }
1076                 }
1077                 s += pass;
1078                 dsp->gsamps += pass;
1079                 len -= pass;
1080                 if (dsp->gsamps == dsp->gsamp_size) {
1081                         float hz[FREQ_ARRAY_SIZE];
1082                         for (y = 0; y < FREQ_ARRAY_SIZE; y++) {
1083                                 hz[y] = goertzel_result(&dsp->freqs[y]);
1084                         }
1085                         switch (dsp->progmode) {
1086                         case PROG_MODE_NA:
1087                                 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
1088                                         newstate = DSP_TONE_STATE_BUSY;
1089                                 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
1090                                         newstate = DSP_TONE_STATE_RINGING;
1091                                 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
1092                                         newstate = DSP_TONE_STATE_DIALTONE;
1093                                 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
1094                                         newstate = DSP_TONE_STATE_SPECIAL1;
1095                                 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
1096                                         /* End of SPECIAL1 or middle of SPECIAL2 */
1097                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL1 || dsp->tstate == DSP_TONE_STATE_SPECIAL2) {
1098                                                 newstate = DSP_TONE_STATE_SPECIAL2;
1099                                         }
1100                                 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
1101                                         /* End of SPECIAL2 or middle of SPECIAL3 */
1102                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL2 || dsp->tstate == DSP_TONE_STATE_SPECIAL3) {
1103                                                 newstate = DSP_TONE_STATE_SPECIAL3;
1104                                         }
1105                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1106                                         newstate = DSP_TONE_STATE_TALKING;
1107                                 } else {
1108                                         newstate = DSP_TONE_STATE_SILENCE;
1109                                 }
1110                                 break;
1111                         case PROG_MODE_CR:
1112                                 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
1113                                         newstate = DSP_TONE_STATE_RINGING;
1114                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1115                                         newstate = DSP_TONE_STATE_TALKING;
1116                                 } else {
1117                                         newstate = DSP_TONE_STATE_SILENCE;
1118                                 }
1119                                 break;
1120                         case PROG_MODE_UK:
1121                                 if (hz[HZ_400UK] > TONE_MIN_THRESH * TONE_THRESH) {
1122                                         newstate = DSP_TONE_STATE_HUNGUP;
1123                                 } else if (pair_there(hz[HZ_350UK], hz[HZ_440UK], hz[HZ_400UK], hz[HZ_400UK], dsp->genergy)) {
1124                                         newstate = DSP_TONE_STATE_DIALTONE;
1125                                 }
1126                                 break;
1127                         default:
1128                                 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%u'\n", dsp->progmode);
1129                         }
1130                         if (newstate == dsp->tstate) {
1131                                 dsp->tcount++;
1132                                 if (dsp->ringtimeout) {
1133                                         dsp->ringtimeout++;
1134                                 }
1135                                 switch (dsp->tstate) {
1136                                 case DSP_TONE_STATE_RINGING:
1137                                         if ((dsp->features & DSP_PROGRESS_RINGING) &&
1138                                             (dsp->tcount == THRESH_RING)) {
1139                                                 res = AST_CONTROL_RINGING;
1140                                                 dsp->ringtimeout = 1;
1141                                         }
1142                                         break;
1143                                 case DSP_TONE_STATE_BUSY:
1144                                         if ((dsp->features & DSP_PROGRESS_BUSY) &&
1145                                             (dsp->tcount == THRESH_BUSY)) {
1146                                                 res = AST_CONTROL_BUSY;
1147                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1148                                         }
1149                                         break;
1150                                 case DSP_TONE_STATE_TALKING:
1151                                         if ((dsp->features & DSP_PROGRESS_TALK) &&
1152                                             (dsp->tcount == THRESH_TALK)) {
1153                                                 res = AST_CONTROL_ANSWER;
1154                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1155                                         }
1156                                         break;
1157                                 case DSP_TONE_STATE_SPECIAL3:
1158                                         if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
1159                                             (dsp->tcount == THRESH_CONGESTION)) {
1160                                                 res = AST_CONTROL_CONGESTION;
1161                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1162                                         }
1163                                         break;
1164                                 case DSP_TONE_STATE_HUNGUP:
1165                                         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
1166                                             (dsp->tcount == THRESH_HANGUP)) {
1167                                                 res = AST_CONTROL_HANGUP;
1168                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1169                                         }
1170                                         break;
1171                                 }
1172                                 if (dsp->ringtimeout == THRESH_RING2ANSWER) {
1173                                         ast_debug(1, "Consider call as answered because of timeout after last ring\n");
1174                                         res = AST_CONTROL_ANSWER;
1175                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1176                                 }
1177                         } else {
1178                                 ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
1179                                 ast_debug(5, "Start state %d\n", newstate);
1180                                 dsp->tstate = newstate;
1181                                 dsp->tcount = 1;
1182                         }
1183
1184                         /* Reset goertzel */
1185                         for (x = 0; x < 7; x++) {
1186                                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1187                         }
1188                         dsp->gsamps = 0;
1189                         dsp->genergy = 0.0;
1190                 }
1191         }
1192
1193         return res;
1194 }
1195
1196 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1197 {
1198         if (inf->frametype != AST_FRAME_VOICE) {
1199                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1200                 return 0;
1201         }
1202         if (!ast_format_cache_is_slinear(inf->subclass.format)) {
1203                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1204                 return 0;
1205         }
1206         return __ast_dsp_call_progress(dsp, inf->data.ptr, inf->datalen / 2);
1207 }
1208
1209 static int __ast_dsp_silence_noise(struct ast_dsp *dsp, short *s, int len, int *totalsilence, int *totalnoise, int *frames_energy)
1210 {
1211         int accum;
1212         int x;
1213         int res = 0;
1214
1215         if (!len) {
1216                 return 0;
1217         }
1218         accum = 0;
1219         for (x = 0; x < len; x++) {
1220                 accum += abs(s[x]);
1221         }
1222         accum /= len;
1223         if (accum < dsp->threshold) {
1224                 /* Silent */
1225                 dsp->totalsilence += len / (dsp->sample_rate / 1000);
1226                 if (dsp->totalnoise) {
1227                         /* Move and save history */
1228                         memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicnoise[0]));
1229                         dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1230 /* we don't want to check for busydetect that frequently */
1231 #if 0
1232                         dsp->busymaybe = 1;
1233 #endif
1234                 }
1235                 dsp->totalnoise = 0;
1236                 res = 1;
1237         } else {
1238                 /* Not silent */
1239                 dsp->totalnoise += len / (dsp->sample_rate / 1000);
1240                 if (dsp->totalsilence) {
1241                         int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1242                         int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1243                         /* Move and save history */
1244                         memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicsilence[0]));
1245                         dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1246                         /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1247                         if (silence1 < silence2) {
1248                                 if (silence1 + silence1 * BUSY_PERCENT / 100 >= silence2) {
1249                                         dsp->busymaybe = 1;
1250                                 } else {
1251                                         dsp->busymaybe = 0;
1252                                 }
1253                         } else {
1254                                 if (silence1 - silence1 * BUSY_PERCENT / 100 <= silence2) {
1255                                         dsp->busymaybe = 1;
1256                                 } else {
1257                                         dsp->busymaybe = 0;
1258                                 }
1259                         }
1260                 }
1261                 dsp->totalsilence = 0;
1262         }
1263         if (totalsilence) {
1264                 *totalsilence = dsp->totalsilence;
1265         }
1266         if (totalnoise) {
1267                 *totalnoise = dsp->totalnoise;
1268         }
1269         if (frames_energy) {
1270                 *frames_energy = accum;
1271         }
1272         return res;
1273 }
1274
1275 int ast_dsp_busydetect(struct ast_dsp *dsp)
1276 {
1277         int res = 0, x;
1278 #ifndef BUSYDETECT_TONEONLY
1279         int avgsilence = 0, hitsilence = 0;
1280 #endif
1281         int avgtone = 0, hittone = 0;
1282
1283         /* if we have a 4 length pattern, the way busymaybe is set doesn't help us. */
1284         if (dsp->busy_cadence.length != 4) {
1285                 if (!dsp->busymaybe) {
1286                         return res;
1287                 }
1288         }
1289
1290         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1291 #ifndef BUSYDETECT_TONEONLY
1292                 avgsilence += dsp->historicsilence[x];
1293 #endif
1294                 avgtone += dsp->historicnoise[x];
1295         }
1296 #ifndef BUSYDETECT_TONEONLY
1297         avgsilence /= dsp->busycount;
1298 #endif
1299         avgtone /= dsp->busycount;
1300         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1301 #ifndef BUSYDETECT_TONEONLY
1302                 if (avgsilence > dsp->historicsilence[x]) {
1303                         if (avgsilence - (avgsilence * BUSY_PERCENT / 100) <= dsp->historicsilence[x]) {
1304                                 hitsilence++;
1305                         }
1306                 } else {
1307                         if (avgsilence + (avgsilence * BUSY_PERCENT / 100) >= dsp->historicsilence[x]) {
1308                                 hitsilence++;
1309                         }
1310                 }
1311 #endif
1312                 if (avgtone > dsp->historicnoise[x]) {
1313                         if (avgtone - (avgtone * BUSY_PERCENT / 100) <= dsp->historicnoise[x]) {
1314                                 hittone++;
1315                         }
1316                 } else {
1317                         if (avgtone + (avgtone * BUSY_PERCENT / 100) >= dsp->historicnoise[x]) {
1318                                 hittone++;
1319                         }
1320                 }
1321         }
1322 #ifndef BUSYDETECT_TONEONLY
1323         if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) &&
1324             (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) &&
1325             (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1326 #else
1327         if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1328 #endif
1329 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1330                 if (avgtone > avgsilence) {
1331                         if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence) {
1332                                 res = 1;
1333                         }
1334                 } else {
1335                         if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence) {
1336                                 res = 1;
1337                         }
1338                 }
1339 #else
1340                 res = 1;
1341 #endif
1342         }
1343
1344         /* If we have a 4-length pattern, we can go ahead and just check it in a different way. */
1345         if (dsp->busy_cadence.length == 4) {
1346                 int x;
1347                 int errors = 0;
1348                 int errors_max = ((4 * dsp->busycount) / 100.0) * BUSY_PAT_PERCENT;
1349
1350                 for (x = DSP_HISTORY - (dsp->busycount); x < DSP_HISTORY; x += 2) {
1351                         int temp_error;
1352                         temp_error = abs(dsp->historicnoise[x] - dsp->busy_cadence.pattern[0]);
1353                         if ((temp_error * 100) / dsp->busy_cadence.pattern[0] > BUSY_PERCENT) {
1354                                 errors++;
1355                         }
1356
1357                         temp_error = abs(dsp->historicnoise[x + 1] - dsp->busy_cadence.pattern[2]);
1358                         if ((temp_error * 100) / dsp->busy_cadence.pattern[2] > BUSY_PERCENT) {
1359                                 errors++;
1360                         }
1361
1362                         temp_error = abs(dsp->historicsilence[x] - dsp->busy_cadence.pattern[1]);
1363                         if ((temp_error * 100) / dsp->busy_cadence.pattern[1] > BUSY_PERCENT) {
1364                                 errors++;
1365                         }
1366
1367                         temp_error = abs(dsp->historicsilence[x + 1] - dsp->busy_cadence.pattern[3]);
1368                         if ((temp_error * 100) / dsp->busy_cadence.pattern[3] > BUSY_PERCENT) {
1369                                 errors++;
1370                         }
1371                 }
1372
1373                 ast_debug(5, "errors = %d  max = %d\n", errors, errors_max);
1374
1375                 if (errors <= errors_max) {
1376                         return 1;
1377                 }
1378         }
1379
1380         /* If we know the expected busy tone length, check we are in the range */
1381         if (res && (dsp->busy_cadence.pattern[0] > 0)) {
1382                 if (abs(avgtone - dsp->busy_cadence.pattern[0]) > MAX(dsp->busy_cadence.pattern[0]*BUSY_PAT_PERCENT/100, 20)) {
1383 #ifdef BUSYDETECT_DEBUG
1384                         ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
1385                                 avgtone, dsp->busy_cadence.pattern[0]);
1386 #endif
1387                         res = 0;
1388                 }
1389         }
1390 #ifndef BUSYDETECT_TONEONLY
1391         /* If we know the expected busy tone silent-period length, check we are in the range */
1392         if (res && (dsp->busy_cadence.pattern[1] > 0)) {
1393                 if (abs(avgsilence - dsp->busy_cadence.pattern[1]) > MAX(dsp->busy_cadence.pattern[1]*BUSY_PAT_PERCENT/100, 20)) {
1394 #ifdef BUSYDETECT_DEBUG
1395                 ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
1396                         avgsilence, dsp->busy_cadence.pattern[1]);
1397 #endif
1398                         res = 0;
1399                 }
1400         }
1401 #endif
1402 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
1403         if (res) {
1404                 ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1405         } else {
1406                 ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1407         }
1408 #endif
1409         return res;
1410 }
1411
1412 static int ast_dsp_silence_noise_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *total, int *frames_energy, int noise)
1413 {
1414         short *s;
1415         int len;
1416         int x;
1417         unsigned char *odata;
1418
1419         if (!f) {
1420                 return 0;
1421         }
1422
1423         if (f->frametype != AST_FRAME_VOICE) {
1424                 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1425                 return 0;
1426         }
1427
1428         if (ast_format_cache_is_slinear(f->subclass.format)) {
1429                 s = f->data.ptr;
1430                 len = f->datalen/2;
1431         } else {
1432                 odata = f->data.ptr;
1433                 len = f->datalen;
1434                 if (ast_format_cmp(f->subclass.format, ast_format_ulaw)) {
1435                         s = ast_alloca(len * 2);
1436                         for (x = 0; x < len; x++) {
1437                                 s[x] = AST_MULAW(odata[x]);
1438                         }
1439                 } else if (ast_format_cmp(f->subclass.format, ast_format_alaw)) {
1440                         s = ast_alloca(len * 2);
1441                         for (x = 0; x < len; x++) {
1442                                 s[x] = AST_ALAW(odata[x]);
1443                         }
1444                 } else {
1445                         ast_log(LOG_WARNING, "Can only calculate silence on signed-linear, alaw or ulaw frames :(\n");
1446                         return 0;
1447                 }
1448         }
1449
1450         if (noise) {
1451                 return __ast_dsp_silence_noise(dsp, s, len, NULL, total, frames_energy);
1452         } else {
1453                 return __ast_dsp_silence_noise(dsp, s, len, total, NULL, frames_energy);
1454         }
1455 }
1456
1457 int ast_dsp_silence_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence, int *frames_energy)
1458 {
1459         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, frames_energy, 0);
1460 }
1461
1462 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1463 {
1464         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, NULL, 0);
1465 }
1466
1467 int ast_dsp_noise(struct ast_dsp *dsp, struct ast_frame *f, int *totalnoise)
1468 {
1469         return ast_dsp_silence_noise_with_energy(dsp, f, totalnoise, NULL, 1);
1470 }
1471
1472
1473 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1474 {
1475         int silence;
1476         int res;
1477         int digit = 0, fax_digit = 0;
1478         int x;
1479         short *shortdata;
1480         unsigned char *odata;
1481         int len;
1482         struct ast_frame *outf = NULL;
1483
1484         if (!af) {
1485                 return NULL;
1486         }
1487         if (af->frametype != AST_FRAME_VOICE) {
1488                 return af;
1489         }
1490
1491         odata = af->data.ptr;
1492         len = af->datalen;
1493         /* Make sure we have short data */
1494         if (ast_format_cache_is_slinear(af->subclass.format)) {
1495                 shortdata = af->data.ptr;
1496                 len = af->datalen / 2;
1497         } else if (ast_format_cmp(af->subclass.format, ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) {
1498                 shortdata = ast_alloca(af->datalen * 2);
1499                 for (x = 0; x < len; x++) {
1500                         shortdata[x] = AST_MULAW(odata[x]);
1501                 }
1502         } else if (ast_format_cmp(af->subclass.format, ast_format_alaw) == AST_FORMAT_CMP_EQUAL) {
1503                 shortdata = ast_alloca(af->datalen * 2);
1504                 for (x = 0; x < len; x++) {
1505                         shortdata[x] = AST_ALAW(odata[x]);
1506                 }
1507         } else {
1508                 /*Display warning only once. Otherwise you would get hundreds of warnings every second */
1509                 if (dsp->display_inband_dtmf_warning) {
1510                         ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_format_get_name(af->subclass.format));
1511                 }
1512                 dsp->display_inband_dtmf_warning = 0;
1513                 return af;
1514         }
1515
1516         /* Initially we do not want to mute anything */
1517         dsp->mute_fragments = 0;
1518
1519         /* Need to run the silence detection stuff for silence suppression and busy detection */
1520         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) || (dsp->features & DSP_FEATURE_BUSY_DETECT)) {
1521                 res = __ast_dsp_silence_noise(dsp, shortdata, len, &silence, NULL, NULL);
1522         }
1523
1524         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1525                 memset(&dsp->f, 0, sizeof(dsp->f));
1526                 dsp->f.frametype = AST_FRAME_NULL;
1527                 ast_frfree(af);
1528                 return ast_frisolate(&dsp->f);
1529         }
1530         if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1531                 ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
1532                 memset(&dsp->f, 0, sizeof(dsp->f));
1533                 dsp->f.frametype = AST_FRAME_CONTROL;
1534                 dsp->f.subclass.integer = AST_CONTROL_BUSY;
1535                 ast_frfree(af);
1536                 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", ast_channel_name(chan));
1537                 return ast_frisolate(&dsp->f);
1538         }
1539
1540         if ((dsp->features & DSP_FEATURE_FAX_DETECT)) {
1541                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CNG) && tone_detect(dsp, &dsp->cng_tone_state, shortdata, len)) {
1542                         fax_digit = 'f';
1543                 }
1544
1545                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CED) && tone_detect(dsp, &dsp->ced_tone_state, shortdata, len)) {
1546                         fax_digit = 'e';
1547                 }
1548         }
1549
1550         if (dsp->features & (DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_BUSY_DETECT)) {
1551                 if (dsp->digitmode & DSP_DIGITMODE_MF) {
1552                         digit = mf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1553                 } else {
1554                         digit = dtmf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1555                 }
1556
1557                 if (dsp->digit_state.current_digits) {
1558                         int event = 0, event_len = 0;
1559                         char event_digit = 0;
1560
1561                         if (!dsp->dtmf_began) {
1562                                 /* We have not reported DTMF_BEGIN for anything yet */
1563
1564                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1565                                         event = AST_FRAME_DTMF_BEGIN;
1566                                         event_digit = dsp->digit_state.digits[0];
1567                                 }
1568                                 dsp->dtmf_began = 1;
1569
1570                         } else if (dsp->digit_state.current_digits > 1 || digit != dsp->digit_state.digits[0]) {
1571                                 /* Digit changed. This means digit we have reported with DTMF_BEGIN ended */
1572                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1573                                         event = AST_FRAME_DTMF_END;
1574                                         event_digit = dsp->digit_state.digits[0];
1575                                         event_len = dsp->digit_state.digitlen[0] * 1000 / dsp->sample_rate;
1576                                 }
1577                                 memmove(&dsp->digit_state.digits[0], &dsp->digit_state.digits[1], dsp->digit_state.current_digits);
1578                                 memmove(&dsp->digit_state.digitlen[0], &dsp->digit_state.digitlen[1], dsp->digit_state.current_digits * sizeof(dsp->digit_state.digitlen[0]));
1579                                 dsp->digit_state.current_digits--;
1580                                 dsp->dtmf_began = 0;
1581
1582                                 if (dsp->features & DSP_FEATURE_BUSY_DETECT) {
1583                                         /* Reset Busy Detector as we have some confirmed activity */
1584                                         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1585                                         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1586                                         ast_debug(1, "DTMF Detected - Reset busydetector\n");
1587                                 }
1588                         }
1589
1590                         if (event) {
1591                                 memset(&dsp->f, 0, sizeof(dsp->f));
1592                                 dsp->f.frametype = event;
1593                                 dsp->f.subclass.integer = event_digit;
1594                                 dsp->f.len = event_len;
1595                                 outf = &dsp->f;
1596                                 goto done;
1597                         }
1598                 }
1599         }
1600
1601         if (fax_digit) {
1602                 /* Fax was detected - digit is either 'f' or 'e' */
1603
1604                 memset(&dsp->f, 0, sizeof(dsp->f));
1605                 dsp->f.frametype = AST_FRAME_DTMF;
1606                 dsp->f.subclass.integer = fax_digit;
1607                 outf = &dsp->f;
1608                 goto done;
1609         }
1610
1611         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1612                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1613                 if (res) {
1614                         switch (res) {
1615                         case AST_CONTROL_ANSWER:
1616                         case AST_CONTROL_BUSY:
1617                         case AST_CONTROL_RINGING:
1618                         case AST_CONTROL_CONGESTION:
1619                         case AST_CONTROL_HANGUP:
1620                                 memset(&dsp->f, 0, sizeof(dsp->f));
1621                                 dsp->f.frametype = AST_FRAME_CONTROL;
1622                                 dsp->f.subclass.integer = res;
1623                                 dsp->f.src = "dsp_progress";
1624                                 if (chan) {
1625                                         ast_queue_frame(chan, &dsp->f);
1626                                 }
1627                                 break;
1628                         default:
1629                                 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1630                         }
1631                 }
1632         } else if ((dsp->features & DSP_FEATURE_WAITDIALTONE)) {
1633                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1634         }
1635
1636 done:
1637         /* Mute fragment of the frame */
1638         for (x = 0; x < dsp->mute_fragments; x++) {
1639                 memset(shortdata + dsp->mute_data[x].start, 0, sizeof(int16_t) * (dsp->mute_data[x].end - dsp->mute_data[x].start));
1640         }
1641
1642         if (ast_format_cmp(af->subclass.format, ast_format_ulaw) == AST_FORMAT_CMP_EQUAL) {
1643                 for (x = 0; x < len; x++) {
1644                         odata[x] = AST_LIN2MU((unsigned short) shortdata[x]);
1645                 }
1646         } else if (ast_format_cmp(af->subclass.format, ast_format_alaw) == AST_FORMAT_CMP_EQUAL) {
1647                 for (x = 0; x < len; x++) {
1648                         odata[x] = AST_LIN2A((unsigned short) shortdata[x]);
1649                 }
1650         }
1651
1652         if (outf) {
1653                 if (chan) {
1654                         ast_queue_frame(chan, af);
1655                 }
1656                 ast_frfree(af);
1657                 return ast_frisolate(outf);
1658         } else {
1659                 return af;
1660         }
1661 }
1662
1663 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1664 {
1665         int max = 0;
1666         int x;
1667
1668         dsp->gsamp_size = modes[dsp->progmode].size;
1669         dsp->gsamps = 0;
1670         for (x = 0; x < FREQ_ARRAY_SIZE; x++) {
1671                 if (modes[dsp->progmode].freqs[x]) {
1672                         goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->sample_rate);
1673                         max = x + 1;
1674                 }
1675         }
1676         dsp->freqcount = max;
1677         dsp->ringtimeout = 0;
1678 }
1679
1680 unsigned int ast_dsp_get_sample_rate(const struct ast_dsp *dsp)
1681 {
1682         return dsp->sample_rate;
1683 }
1684
1685 static struct ast_dsp *__ast_dsp_new(unsigned int sample_rate)
1686 {
1687         struct ast_dsp *dsp;
1688
1689         if ((dsp = ast_calloc(1, sizeof(*dsp)))) {
1690                 dsp->threshold = DEFAULT_THRESHOLD;
1691                 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1692                 dsp->busycount = DSP_HISTORY;
1693                 dsp->digitmode = DSP_DIGITMODE_DTMF;
1694                 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1695                 dsp->sample_rate = sample_rate;
1696                 dsp->freqcount = 0;
1697                 /* Initialize digit detector */
1698                 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF, dsp->sample_rate);
1699                 dsp->display_inband_dtmf_warning = 1;
1700                 /* Initialize initial DSP progress detect parameters */
1701                 ast_dsp_prog_reset(dsp);
1702                 /* Initialize fax detector */
1703                 ast_fax_detect_init(dsp);
1704         }
1705         return dsp;
1706 }
1707
1708 struct ast_dsp *ast_dsp_new(void)
1709 {
1710         return __ast_dsp_new(DEFAULT_SAMPLE_RATE);
1711 }
1712
1713 struct ast_dsp *ast_dsp_new_with_rate(unsigned int sample_rate)
1714 {
1715         return __ast_dsp_new(sample_rate);
1716 }
1717
1718 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1719 {
1720         dsp->features = features;
1721         if (!(features & DSP_FEATURE_DIGIT_DETECT)) {
1722                 dsp->display_inband_dtmf_warning = 0;
1723         }
1724 }
1725
1726
1727 int ast_dsp_get_features(struct ast_dsp *dsp)
1728 {
1729         return (dsp->features);
1730 }
1731
1732
1733 void ast_dsp_free(struct ast_dsp *dsp)
1734 {
1735         ast_free(dsp);
1736 }
1737
1738 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1739 {
1740         dsp->threshold = threshold;
1741 }
1742
1743 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1744 {
1745         if (cadences < 4) {
1746                 cadences = 4;
1747         }
1748         if (cadences > DSP_HISTORY) {
1749                 cadences = DSP_HISTORY;
1750         }
1751         dsp->busycount = cadences;
1752 }
1753
1754 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, const struct ast_dsp_busy_pattern *cadence)
1755 {
1756         dsp->busy_cadence = *cadence;
1757         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);
1758 }
1759
1760 void ast_dsp_digitreset(struct ast_dsp *dsp)
1761 {
1762         int i;
1763
1764         dsp->dtmf_began = 0;
1765         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1766                 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1767                 /* Reinitialise the detector for the next block */
1768                 for (i = 0; i < 6; i++) {
1769                         goertzel_reset(&s->tone_out[i]);
1770                 }
1771                 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = 0;
1772                 s->current_hit = 0;
1773                 s->current_sample = 0;
1774         } else {
1775                 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1776                 /* Reinitialise the detector for the next block */
1777                 for (i = 0; i < 4; i++) {
1778                         goertzel_reset(&s->row_out[i]);
1779                         goertzel_reset(&s->col_out[i]);
1780                 }
1781                 s->lasthit = 0;
1782                 s->current_hit = 0;
1783                 s->energy = 0.0;
1784                 s->current_sample = 0;
1785                 s->hits = 0;
1786                 s->misses = 0;
1787         }
1788
1789         dsp->digit_state.digits[0] = '\0';
1790         dsp->digit_state.current_digits = 0;
1791 }
1792
1793 void ast_dsp_reset(struct ast_dsp *dsp)
1794 {
1795         int x;
1796
1797         dsp->totalsilence = 0;
1798         dsp->gsamps = 0;
1799         for (x = 0; x < 4; x++) {
1800                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1801         }
1802         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1803         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1804         dsp->ringtimeout = 0;
1805 }
1806
1807 int ast_dsp_set_digitmode(struct ast_dsp *dsp, int digitmode)
1808 {
1809         int new;
1810         int old;
1811
1812         old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1813         new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1814         if (old != new) {
1815                 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1816                 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF, dsp->sample_rate);
1817         }
1818         dsp->digitmode = digitmode;
1819         return 0;
1820 }
1821
1822 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1823 {
1824         if (dsp->faxmode != faxmode) {
1825                 dsp->faxmode = faxmode;
1826                 ast_fax_detect_init(dsp);
1827         }
1828         return 0;
1829 }
1830
1831 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1832 {
1833         int x;
1834
1835         for (x = 0; x < ARRAY_LEN(aliases); x++) {
1836                 if (!strcasecmp(aliases[x].name, zone)) {
1837                         dsp->progmode = aliases[x].mode;
1838                         ast_dsp_prog_reset(dsp);
1839                         return 0;
1840                 }
1841         }
1842         return -1;
1843 }
1844
1845 int ast_dsp_was_muted(struct ast_dsp *dsp)
1846 {
1847         return (dsp->mute_fragments > 0);
1848 }
1849
1850 int ast_dsp_get_tstate(struct ast_dsp *dsp)
1851 {
1852         return dsp->tstate;
1853 }
1854
1855 int ast_dsp_get_tcount(struct ast_dsp *dsp)
1856 {
1857         return dsp->tcount;
1858 }
1859
1860 static int _dsp_init(int reload)
1861 {
1862         struct ast_config *cfg;
1863         struct ast_variable *v;
1864         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1865         int cfg_threshold;
1866         float cfg_twist;
1867
1868         if ((cfg = ast_config_load2(CONFIG_FILE_NAME, "dsp", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
1869                 return 0;
1870         }
1871
1872         thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1873         dtmf_normal_twist = DEF_DTMF_NORMAL_TWIST;
1874         dtmf_reverse_twist = DEF_DTMF_REVERSE_TWIST;
1875         relax_dtmf_normal_twist = DEF_RELAX_DTMF_NORMAL_TWIST;
1876         relax_dtmf_reverse_twist = DEF_RELAX_DTMF_REVERSE_TWIST;
1877         dtmf_hits_to_begin = DEF_DTMF_HITS_TO_BEGIN;
1878         dtmf_misses_to_end = DEF_DTMF_MISSES_TO_END;
1879
1880         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
1881                 return 0;
1882         }
1883
1884         for (v = ast_variable_browse(cfg, "default"); v; v = v->next) {
1885                 if (!strcasecmp(v->name, "silencethreshold")) {
1886                         if (sscanf(v->value, "%30d", &cfg_threshold) < 1) {
1887                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1888                         } else if (cfg_threshold < 0) {
1889                                 ast_log(LOG_WARNING, "Invalid silence threshold '%d' specified, using default\n", cfg_threshold);
1890                         } else {
1891                                 thresholds[THRESHOLD_SILENCE] = cfg_threshold;
1892                         }
1893                 } else if (!strcasecmp(v->name, "dtmf_normal_twist")) {
1894                         if (sscanf(v->value, "%30f", &cfg_twist) < 1) {
1895                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1896                         } else if ((cfg_twist < 2.0) || (cfg_twist > 100.0)) {          /* < 3.0dB or > 20dB */
1897                                 ast_log(LOG_WARNING, "Invalid dtmf_normal_twist value '%.2f' specified, using default of %.2f\n", cfg_twist, dtmf_normal_twist);
1898                         } else {
1899                                 dtmf_normal_twist = cfg_twist;
1900                         }
1901                 } else if (!strcasecmp(v->name, "dtmf_reverse_twist")) {
1902                         if (sscanf(v->value, "%30f", &cfg_twist) < 1) {
1903                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1904                         } else if ((cfg_twist < 2.0) || (cfg_twist > 100.0)) {          /* < 3.0dB or > 20dB */
1905                                 ast_log(LOG_WARNING, "Invalid dtmf_reverse_twist value '%.2f' specified, using default of %.2f\n", cfg_twist, dtmf_reverse_twist);
1906                         } else {
1907                                 dtmf_reverse_twist = cfg_twist;
1908                         }
1909                 } else if (!strcasecmp(v->name, "relax_dtmf_normal_twist")) {
1910                         if (sscanf(v->value, "%30f", &cfg_twist) < 1) {
1911                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1912                         } else if ((cfg_twist < 2.0) || (cfg_twist > 100.0)) {          /* < 3.0dB or > 20dB */
1913                                 ast_log(LOG_WARNING, "Invalid relax_dtmf_normal_twist value '%.2f' specified, using default of %.2f\n", cfg_twist, relax_dtmf_normal_twist);
1914                         } else {
1915                                 relax_dtmf_normal_twist = cfg_twist;
1916                         }
1917                 } else if (!strcasecmp(v->name, "relax_dtmf_reverse_twist")) {
1918                         if (sscanf(v->value, "%30f", &cfg_twist) < 1) {
1919                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1920                         } else if ((cfg_twist < 2.0) || (cfg_twist > 100.0)) {          /* < 3.0dB or > 20dB */
1921                                 ast_log(LOG_WARNING, "Invalid relax_dtmf_reverse_twist value '%.2f' specified, using default of %.2f\n", cfg_twist, relax_dtmf_reverse_twist);
1922                         } else {
1923                                 relax_dtmf_reverse_twist = cfg_twist;
1924                         }
1925                 } else if (!strcasecmp(v->name, "dtmf_hits_to_begin")) {
1926                         if (sscanf(v->value, "%30d", &cfg_threshold) < 1) {
1927                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1928                         } else if (cfg_threshold < 1) {         /* must be 1 or greater */
1929                                 ast_log(LOG_WARNING, "Invalid dtmf_hits_to_begin value '%d' specified, using default of %d\n", cfg_threshold, dtmf_hits_to_begin);
1930                         } else {
1931                                 dtmf_hits_to_begin = cfg_threshold;
1932                         }
1933                 } else if (!strcasecmp(v->name, "dtmf_misses_to_end")) {
1934                         if (sscanf(v->value, "%30d", &cfg_threshold) < 1) {
1935                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
1936                         } else if (cfg_threshold < 1) {         /* must be 1 or greater */
1937                                 ast_log(LOG_WARNING, "Invalid dtmf_misses_to_end value '%d' specified, using default of %d\n", cfg_threshold, dtmf_misses_to_end);
1938                         } else {
1939                                 dtmf_misses_to_end = cfg_threshold;
1940                         }
1941                 }
1942         }
1943         ast_config_destroy(cfg);
1944
1945         return 0;
1946 }
1947
1948 int ast_dsp_get_threshold_from_settings(enum threshold which)
1949 {
1950         return thresholds[which];
1951 }
1952
1953 #ifdef TEST_FRAMEWORK
1954 static void test_tone_sample_gen(short *slin_buf, int samples, int rate, int freq, short amplitude)
1955 {
1956         int idx;
1957         double sample_step = 2.0 * M_PI * freq / rate;/* radians per step */
1958
1959         for (idx = 0; idx < samples; ++idx) {
1960                 slin_buf[idx] = amplitude * sin(sample_step * idx);
1961         }
1962 }
1963 #endif
1964
1965 #ifdef TEST_FRAMEWORK
1966 static void test_tone_sample_gen_add(short *slin_buf, int samples, int rate, int freq, short amplitude)
1967 {
1968         int idx;
1969         double sample_step = 2.0 * M_PI * freq / rate;/* radians per step */
1970
1971         for (idx = 0; idx < samples; ++idx) {
1972                 slin_buf[idx] += amplitude * sin(sample_step * idx);
1973         }
1974 }
1975 #endif
1976
1977 #ifdef TEST_FRAMEWORK
1978 static void test_dual_sample_gen(short *slin_buf, int samples, int rate, int f1, short a1, int f2, short a2)
1979 {
1980         test_tone_sample_gen(slin_buf, samples, rate, f1, a1);
1981         test_tone_sample_gen_add(slin_buf, samples, rate, f2, a2);
1982 }
1983 #endif
1984
1985 #ifdef TEST_FRAMEWORK
1986 #define TONE_AMPLITUDE_MAX      0x7fff  /* Max signed linear amplitude */
1987 #define TONE_AMPLITUDE_MIN      80              /* Min signed linear amplitude detectable */
1988
1989 static int test_tone_amplitude_sweep(struct ast_test *test, struct ast_dsp *dsp, tone_detect_state_t *tone_state)
1990 {
1991         short slin_buf[tone_state->block_size];
1992         int result;
1993         int idx;
1994         struct {
1995                 short amp_val;
1996                 int detect;
1997         } amp_tests[] = {
1998                 { .amp_val = TONE_AMPLITUDE_MAX,        .detect = 1, },
1999                 { .amp_val = 10000,                                     .detect = 1, },
2000                 { .amp_val = 1000,                                      .detect = 1, },
2001                 { .amp_val = 100,                                       .detect = 1, },
2002                 { .amp_val = TONE_AMPLITUDE_MIN,        .detect = 1, },
2003                 { .amp_val = 75,                                        .detect = 0, },
2004                 { .amp_val = 10,                                        .detect = 0, },
2005                 { .amp_val = 1,                                         .detect = 0, },
2006         };
2007
2008         result = 0;
2009
2010         for (idx = 0; idx < ARRAY_LEN(amp_tests); ++idx) {
2011                 int detected;
2012                 int duration;
2013
2014                 ast_debug(1, "Test %d Hz at amplitude %d\n",
2015                         tone_state->freq, amp_tests[idx].amp_val);
2016                 test_tone_sample_gen(slin_buf, tone_state->block_size, DEFAULT_SAMPLE_RATE,
2017                         tone_state->freq, amp_tests[idx].amp_val);
2018
2019                 detected = 0;
2020                 for (duration = 0; !detected && duration < tone_state->hits_required + 3; ++duration) {
2021                         detected = tone_detect(dsp, tone_state, slin_buf, tone_state->block_size) ? 1 : 0;
2022                 }
2023                 if (amp_tests[idx].detect != detected) {
2024                         /*
2025                          * Both messages are needed.  ast_debug for when figuring out
2026                          * what went wrong and the test update for normal output before
2027                          * you start debugging.  The different logging methods are not
2028                          * synchronized.
2029                          */
2030                         ast_debug(1,
2031                                 "Test %d Hz at amplitude %d failed.  Detected: %s\n",
2032                                 tone_state->freq, amp_tests[idx].amp_val,
2033                                 detected ? "yes" : "no");
2034                         ast_test_status_update(test,
2035                                 "Test %d Hz at amplitude %d failed.  Detected: %s\n",
2036                                 tone_state->freq, amp_tests[idx].amp_val,
2037                                 detected ? "yes" : "no");
2038                         result = -1;
2039                 }
2040                 tone_state->hit_count = 0;
2041         }
2042
2043         return result;
2044 }
2045 #endif
2046
2047 #ifdef TEST_FRAMEWORK
2048 static int test_dtmf_amplitude_sweep(struct ast_test *test, struct ast_dsp *dsp, int digit_index)
2049 {
2050         short slin_buf[DTMF_GSIZE];
2051         int result;
2052         int row;
2053         int column;
2054         int idx;
2055         struct {
2056                 short amp_val;
2057                 int digit;
2058         } amp_tests[] = {
2059                 /*
2060                  * XXX Since there is no current DTMF level detection issue.  This test
2061                  * just checks the current detection levels.
2062                  */
2063                 { .amp_val = TONE_AMPLITUDE_MAX/2,      .digit = dtmf_positions[digit_index], },
2064                 { .amp_val = 10000,                                     .digit = dtmf_positions[digit_index], },
2065                 { .amp_val = 1000,                                      .digit = dtmf_positions[digit_index], },
2066                 { .amp_val = 500,                                       .digit = dtmf_positions[digit_index], },
2067                 { .amp_val = 250,                                       .digit = dtmf_positions[digit_index], },
2068                 { .amp_val = 200,                                       .digit = dtmf_positions[digit_index], },
2069                 { .amp_val = 180,                                       .digit = dtmf_positions[digit_index], },
2070                 /* Various digits detect and not detect in this range */
2071                 { .amp_val = 170,                                       .digit = 0, },
2072                 { .amp_val = 100,                                       .digit = 0, },
2073                 /*
2074                  * Amplitudes below TONE_AMPLITUDE_MIN start having questionable detection
2075                  * over quantization and background noise.
2076                  */
2077                 { .amp_val = TONE_AMPLITUDE_MIN,        .digit = 0, },
2078                 { .amp_val = 75,                                        .digit = 0, },
2079                 { .amp_val = 10,                                        .digit = 0, },
2080                 { .amp_val = 1,                                         .digit = 0, },
2081         };
2082
2083         row = (digit_index >> 2) & 0x03;
2084         column = digit_index & 0x03;
2085
2086         result = 0;
2087
2088         for (idx = 0; idx < ARRAY_LEN(amp_tests); ++idx) {
2089                 int digit;
2090                 int duration;
2091
2092                 ast_debug(1, "Test '%c' at amplitude %d\n",
2093                         dtmf_positions[digit_index], amp_tests[idx].amp_val);
2094                 test_dual_sample_gen(slin_buf, ARRAY_LEN(slin_buf), DEFAULT_SAMPLE_RATE,
2095                         (int) dtmf_row[row], amp_tests[idx].amp_val,
2096                         (int) dtmf_col[column], amp_tests[idx].amp_val);
2097
2098                 digit = 0;
2099                 for (duration = 0; !digit && duration < 3; ++duration) {
2100                         digit = dtmf_detect(dsp, &dsp->digit_state, slin_buf, ARRAY_LEN(slin_buf),
2101                                 0, 0);
2102                 }
2103                 if (amp_tests[idx].digit != digit) {
2104                         /*
2105                          * Both messages are needed.  ast_debug for when figuring out
2106                          * what went wrong and the test update for normal output before
2107                          * you start debugging.  The different logging methods are not
2108                          * synchronized.
2109                          */
2110                         ast_debug(1,
2111                                 "Test '%c' at amplitude %d failed.  Detected Digit: '%c'\n",
2112                                 dtmf_positions[digit_index], amp_tests[idx].amp_val,
2113                                 digit ?: ' ');
2114                         ast_test_status_update(test,
2115                                 "Test '%c' at amplitude %d failed.  Detected Digit: '%c'\n",
2116                                 dtmf_positions[digit_index], amp_tests[idx].amp_val,
2117                                 digit ?: ' ');
2118                         result = -1;
2119                 }
2120                 ast_dsp_digitreset(dsp);
2121         }
2122
2123         return result;
2124 }
2125 #endif
2126
2127 #ifdef TEST_FRAMEWORK
2128 static int test_dtmf_twist_sweep(struct ast_test *test, struct ast_dsp *dsp, int digit_index)
2129 {
2130         short slin_buf[DTMF_GSIZE];
2131         int result;
2132         int row;
2133         int column;
2134         int idx;
2135         struct {
2136                 short amp_row;
2137                 short amp_col;
2138                 int digit;
2139         } twist_tests[] = {
2140                 /*
2141                  * XXX Since there is no current DTMF twist detection issue.  This test
2142                  * just checks the current detection levels.
2143                  *
2144                  * Normal twist has the column higher than the row amplitude.
2145                  * Reverse twist is the other way.
2146                  */
2147                 { .amp_row = 1000 + 1800, .amp_col = 1000 +    0, .digit = 0, },
2148                 { .amp_row = 1000 + 1700, .amp_col = 1000 +    0, .digit = 0, },
2149                 /* Various digits detect and not detect in this range */
2150                 { .amp_row = 1000 + 1400, .amp_col = 1000 +    0, .digit = dtmf_positions[digit_index], },
2151                 { .amp_row = 1000 + 1300, .amp_col = 1000 +    0, .digit = dtmf_positions[digit_index], },
2152                 { .amp_row = 1000 + 1200, .amp_col = 1000 +    0, .digit = dtmf_positions[digit_index], },
2153                 { .amp_row = 1000 + 1100, .amp_col = 1000 +    0, .digit = dtmf_positions[digit_index], },
2154                 { .amp_row = 1000 + 1000, .amp_col = 1000 +    0, .digit = dtmf_positions[digit_index], },
2155                 { .amp_row = 1000 +  100, .amp_col = 1000 +    0, .digit = dtmf_positions[digit_index], },
2156                 { .amp_row = 1000 +    0, .amp_col = 1000 +  100, .digit = dtmf_positions[digit_index], },
2157                 { .amp_row = 1000 +    0, .amp_col = 1000 +  200, .digit = dtmf_positions[digit_index], },
2158                 { .amp_row = 1000 +    0, .amp_col = 1000 +  300, .digit = dtmf_positions[digit_index], },
2159                 { .amp_row = 1000 +    0, .amp_col = 1000 +  400, .digit = dtmf_positions[digit_index], },
2160                 { .amp_row = 1000 +    0, .amp_col = 1000 +  500, .digit = dtmf_positions[digit_index], },
2161                 { .amp_row = 1000 +    0, .amp_col = 1000 +  550, .digit = dtmf_positions[digit_index], },
2162                 /* Various digits detect and not detect in this range */
2163                 { .amp_row = 1000 +    0, .amp_col = 1000 +  650, .digit = 0, },
2164                 { .amp_row = 1000 +    0, .amp_col = 1000 +  700, .digit = 0, },
2165                 { .amp_row = 1000 +    0, .amp_col = 1000 +  800, .digit = 0, },
2166         };
2167         float save_normal_twist;
2168         float save_reverse_twist;
2169
2170         save_normal_twist = dtmf_normal_twist;
2171         save_reverse_twist = dtmf_reverse_twist;
2172         dtmf_normal_twist = DEF_DTMF_NORMAL_TWIST;
2173         dtmf_reverse_twist = DEF_DTMF_REVERSE_TWIST;
2174
2175         row = (digit_index >> 2) & 0x03;
2176         column = digit_index & 0x03;
2177
2178         result = 0;
2179
2180         for (idx = 0; idx < ARRAY_LEN(twist_tests); ++idx) {
2181                 int digit;
2182                 int duration;
2183
2184                 ast_debug(1, "Test '%c' twist row %d col %d amplitudes\n",
2185                         dtmf_positions[digit_index],
2186                         twist_tests[idx].amp_row, twist_tests[idx].amp_col);
2187                 test_dual_sample_gen(slin_buf, ARRAY_LEN(slin_buf), DEFAULT_SAMPLE_RATE,
2188                         (int) dtmf_row[row], twist_tests[idx].amp_row,
2189                         (int) dtmf_col[column], twist_tests[idx].amp_col);
2190
2191                 digit = 0;
2192                 for (duration = 0; !digit && duration < 3; ++duration) {
2193                         digit = dtmf_detect(dsp, &dsp->digit_state, slin_buf, ARRAY_LEN(slin_buf),
2194                                 0, 0);
2195                 }
2196                 if (twist_tests[idx].digit != digit) {
2197                         /*
2198                          * Both messages are needed.  ast_debug for when figuring out
2199                          * what went wrong and the test update for normal output before
2200                          * you start debugging.  The different logging methods are not
2201                          * synchronized.
2202                          */
2203                         ast_debug(1,
2204                                 "Test '%c' twist row %d col %d amplitudes failed.  Detected Digit: '%c'\n",
2205                                 dtmf_positions[digit_index],
2206                                 twist_tests[idx].amp_row, twist_tests[idx].amp_col,
2207                                 digit ?: ' ');
2208                         ast_test_status_update(test,
2209                                 "Test '%c' twist row %d col %d amplitudes failed.  Detected Digit: '%c'\n",
2210                                 dtmf_positions[digit_index],
2211                                 twist_tests[idx].amp_row, twist_tests[idx].amp_col,
2212                                 digit ?: ' ');
2213                         result = -1;
2214                 }
2215                 ast_dsp_digitreset(dsp);
2216         }
2217
2218         dtmf_normal_twist = save_normal_twist;
2219         dtmf_reverse_twist = save_reverse_twist;
2220
2221         return result;
2222 }
2223 #endif
2224
2225 #ifdef TEST_FRAMEWORK
2226 static int test_tone_freq_sweep(struct ast_test *test, struct ast_dsp *dsp, tone_detect_state_t *tone_state, short amplitude)
2227 {
2228         short slin_buf[tone_state->block_size];
2229         int result;
2230         int freq;
2231         int lower_freq;
2232         int upper_freq;
2233
2234         /* Calculate detection frequency range */
2235         lower_freq = tone_state->freq - 4;
2236         upper_freq = tone_state->freq + 4;
2237
2238         result = 0;
2239
2240         /* Sweep frequencies loop. */
2241         for (freq = 100; freq <= 3500; freq += 1) {
2242                 int detected;
2243                 int duration;
2244                 int expect_detection;
2245
2246                 if (freq == tone_state->freq) {
2247                         /* This case is done by the amplitude sweep. */
2248                         continue;
2249                 }
2250
2251                 expect_detection = (lower_freq <= freq && freq <= upper_freq) ? 1 : 0;
2252
2253                 ast_debug(1, "Test %d Hz detection given %d Hz tone at amplitude %d.  Range:%d-%d Expect detect: %s\n",
2254                         tone_state->freq, freq, amplitude, lower_freq, upper_freq,
2255                         expect_detection ? "yes" : "no");
2256                 test_tone_sample_gen(slin_buf, tone_state->block_size, DEFAULT_SAMPLE_RATE, freq,
2257                         amplitude);
2258
2259                 detected = 0;
2260                 for (duration = 0; !detected && duration < tone_state->hits_required + 3; ++duration) {
2261                         detected = tone_detect(dsp, tone_state, slin_buf, tone_state->block_size) ? 1 : 0;
2262                 }
2263                 if (expect_detection != detected) {
2264                         /*
2265                          * Both messages are needed.  ast_debug for when figuring out
2266                          * what went wrong and the test update for normal output before
2267                          * you start debugging.  The different logging methods are not
2268                          * synchronized.
2269                          */
2270                         ast_debug(1,
2271                                 "Test %d Hz detection given %d Hz tone at amplitude %d failed.  Range:%d-%d Detected: %s\n",
2272                                 tone_state->freq, freq, amplitude, lower_freq, upper_freq,
2273                                 detected ? "yes" : "no");
2274                         ast_test_status_update(test,
2275                                 "Test %d Hz detection given %d Hz tone at amplitude %d failed.  Range:%d-%d Detected: %s\n",
2276                                 tone_state->freq, freq, amplitude, lower_freq, upper_freq,
2277                                 detected ? "yes" : "no");
2278                         result = -1;
2279                 }
2280                 tone_state->hit_count = 0;
2281         }
2282
2283         return result;
2284 }
2285 #endif
2286
2287 #ifdef TEST_FRAMEWORK
2288 AST_TEST_DEFINE(test_dsp_fax_detect)
2289 {
2290         struct ast_dsp *dsp;
2291         enum ast_test_result_state result;
2292
2293         switch (cmd) {
2294         case TEST_INIT:
2295                 info->name = "fax";
2296                 info->category = "/main/dsp/";
2297                 info->summary = "DSP fax tone detect unit test";
2298                 info->description =
2299                         "Tests fax tone detection code.";
2300                 return AST_TEST_NOT_RUN;
2301         case TEST_EXECUTE:
2302                 break;
2303         }
2304
2305         dsp = ast_dsp_new();
2306         if (!dsp) {
2307                 return AST_TEST_FAIL;
2308         }
2309
2310         result = AST_TEST_PASS;
2311
2312         /* Test CNG tone amplitude detection */
2313         if (test_tone_amplitude_sweep(test, dsp, &dsp->cng_tone_state)) {
2314                 result = AST_TEST_FAIL;
2315         }
2316
2317         /* Test CED tone amplitude detection */
2318         if (test_tone_amplitude_sweep(test, dsp, &dsp->ced_tone_state)) {
2319                 result = AST_TEST_FAIL;
2320         }
2321
2322         /* Test CNG tone frequency detection */
2323         if (test_tone_freq_sweep(test, dsp, &dsp->cng_tone_state, TONE_AMPLITUDE_MAX)) {
2324                 result = AST_TEST_FAIL;
2325         }
2326         if (test_tone_freq_sweep(test, dsp, &dsp->cng_tone_state, TONE_AMPLITUDE_MIN)) {
2327                 result = AST_TEST_FAIL;
2328         }
2329
2330         /* Test CED tone frequency detection */
2331         if (test_tone_freq_sweep(test, dsp, &dsp->ced_tone_state, TONE_AMPLITUDE_MAX)) {
2332                 result = AST_TEST_FAIL;
2333         }
2334         if (test_tone_freq_sweep(test, dsp, &dsp->ced_tone_state, TONE_AMPLITUDE_MIN)) {
2335                 result = AST_TEST_FAIL;
2336         }
2337
2338         ast_dsp_free(dsp);
2339         return result;
2340 }
2341 #endif
2342
2343 #ifdef TEST_FRAMEWORK
2344 AST_TEST_DEFINE(test_dsp_dtmf_detect)
2345 {
2346         int idx;
2347         struct ast_dsp *dsp;
2348         enum ast_test_result_state result;
2349
2350         switch (cmd) {
2351         case TEST_INIT:
2352                 info->name = "dtmf";
2353                 info->category = "/main/dsp/";
2354                 info->summary = "DSP DTMF detect unit test";
2355                 info->description =
2356                         "Tests DTMF detection code.";
2357                 return AST_TEST_NOT_RUN;
2358         case TEST_EXECUTE:
2359                 break;
2360         }
2361
2362         dsp = ast_dsp_new();
2363         if (!dsp) {
2364                 return AST_TEST_FAIL;
2365         }
2366
2367         result = AST_TEST_PASS;
2368
2369         for (idx = 0; dtmf_positions[idx]; ++idx) {
2370                 if (test_dtmf_amplitude_sweep(test, dsp, idx)) {
2371                         result = AST_TEST_FAIL;
2372                 }
2373         }
2374
2375         for (idx = 0; dtmf_positions[idx]; ++idx) {
2376                 if (test_dtmf_twist_sweep(test, dsp, idx)) {
2377                         result = AST_TEST_FAIL;
2378                 }
2379         }
2380
2381         ast_dsp_free(dsp);
2382         return result;
2383 }
2384 #endif
2385
2386 #ifdef TEST_FRAMEWORK
2387 static void test_dsp_shutdown(void)
2388 {
2389         AST_TEST_UNREGISTER(test_dsp_fax_detect);
2390         AST_TEST_UNREGISTER(test_dsp_dtmf_detect);
2391 }
2392 #endif
2393
2394 int ast_dsp_init(void)
2395 {
2396         int res = _dsp_init(0);
2397
2398 #ifdef TEST_FRAMEWORK
2399         if (!res) {
2400                 AST_TEST_REGISTER(test_dsp_fax_detect);
2401                 AST_TEST_REGISTER(test_dsp_dtmf_detect);
2402
2403                 ast_register_cleanup(test_dsp_shutdown);
2404         }
2405 #endif
2406         return res;
2407 }
2408
2409 int ast_dsp_reload(void)
2410 {
2411         return _dsp_init(1);
2412 }