Largely refactor DSP tone detection routines.
[asterisk/asterisk.git] / main / dsp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * Goertzel routines are borrowed from Steve Underwood's tremendous work on the
9  * DTMF detector.
10  *
11  * See http://www.asterisk.org for more information about
12  * the Asterisk project. Please do not directly contact
13  * any of the maintainers of this project for assistance;
14  * the project provides a web site, mailing lists and IRC
15  * channels for your use.
16  *
17  * This program is free software, distributed under the terms of
18  * the GNU General Public License Version 2. See the LICENSE file
19  * at the top of the source tree.
20  */
21
22 /*! \file
23  *
24  * \brief Convenience Signal Processing routines
25  *
26  * \author Mark Spencer <markster@digium.com>
27  * \author Steve Underwood <steveu@coppice.org>
28  */
29
30 /* Some routines from tone_detect.c by Steven Underwood as published under the zapata library */
31 /*
32         tone_detect.c - General telephony tone detection, and specific
33                         detection of DTMF.
34
35         Copyright (C) 2001  Steve Underwood <steveu@coppice.org>
36
37         Despite my general liking of the GPL, I place this code in the
38         public domain for the benefit of all mankind - even the slimy
39         ones who might try to proprietize my work and use it to my
40         detriment.
41 */
42
43 #include "asterisk.h"
44
45 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
46
47 #include <math.h>
48
49 #include "asterisk/frame.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/dsp.h"
52 #include "asterisk/ulaw.h"
53 #include "asterisk/alaw.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/options.h"
56
57 /*! Number of goertzels for progress detect */
58 enum gsamp_size {
59         GSAMP_SIZE_NA = 183,                    /*!< North America - 350, 440, 480, 620, 950, 1400, 1800 Hz */
60         GSAMP_SIZE_CR = 188,                    /*!< Costa Rica, Brazil - Only care about 425 Hz */
61         GSAMP_SIZE_UK = 160                     /*!< UK disconnect goertzel feed - should trigger 400hz */
62 };
63
64 enum prog_mode {
65         PROG_MODE_NA = 0,
66         PROG_MODE_CR,
67         PROG_MODE_UK
68 };
69
70 enum freq_index { 
71         /*! For US modes { */
72         HZ_350 = 0,
73         HZ_440,
74         HZ_480,
75         HZ_620,
76         HZ_950,
77         HZ_1400,
78         HZ_1800, /*!< } */
79
80         /*! For CR/BR modes */
81         HZ_425 = 0,
82
83         /*! For UK mode */
84         HZ_400 = 0
85 };
86
87 static struct progalias {
88         char *name;
89         enum prog_mode mode;
90 } aliases[] = {
91         { "us", PROG_MODE_NA },
92         { "ca", PROG_MODE_NA },
93         { "cr", PROG_MODE_CR },
94         { "br", PROG_MODE_CR },
95         { "uk", PROG_MODE_UK },
96 };
97
98 static struct progress {
99         enum gsamp_size size;
100         int freqs[7];
101 } modes[] = {
102         { GSAMP_SIZE_NA, { 350, 440, 480, 620, 950, 1400, 1800 } },     /*!< North America */
103         { GSAMP_SIZE_CR, { 425 } },                                     /*!< Costa Rica, Brazil */
104         { GSAMP_SIZE_UK, { 400 } },                                     /*!< UK */
105 };
106
107 #define DEFAULT_THRESHOLD       512
108
109 enum busy_detect {
110         BUSY_PERCENT = 10,      /*!< The percentage difference between the two last silence periods */
111         BUSY_PAT_PERCENT = 7,   /*!< The percentage difference between measured and actual pattern */
112         BUSY_THRESHOLD = 100,   /*!< Max number of ms difference between max and min times in busy */
113         BUSY_MIN = 75,          /*!< Busy must be at least 80 ms in half-cadence */
114         BUSY_MAX =3100          /*!< Busy can't be longer than 3100 ms in half-cadence */
115 };
116
117 /*! Remember last 15 units */
118 #define DSP_HISTORY             15
119
120 #define TONE_THRESH             10.0    /*!< How much louder the tone should be than channel energy */
121 #define TONE_MIN_THRESH         1e8     /*!< How much tone there should be at least to attempt */
122
123 /*! All THRESH_XXX values are in GSAMP_SIZE chunks (us = 22ms) */
124 enum gsamp_thresh {
125         THRESH_RING = 8,                /*!< Need at least 150ms ring to accept */
126         THRESH_TALK = 2,                /*!< Talk detection does not work continuously */
127         THRESH_BUSY = 4,                /*!< Need at least 80ms to accept */
128         THRESH_CONGESTION = 4,          /*!< Need at least 80ms to accept */
129         THRESH_HANGUP = 60,             /*!< Need at least 1300ms to accept hangup */
130         THRESH_RING2ANSWER = 300        /*!< Timeout from start of ring to answer (about 6600 ms) */
131 };
132
133 #define MAX_DTMF_DIGITS         128
134
135 /* Basic DTMF specs:
136  *
137  * Minimum tone on = 40ms
138  * Minimum tone off = 50ms
139  * Maximum digit rate = 10 per second
140  * Normal twist <= 8dB accepted
141  * Reverse twist <= 4dB accepted
142  * S/N >= 15dB will detect OK
143  * Attenuation <= 26dB will detect OK
144  * Frequency tolerance +- 1.5% will detect, +-3.5% will reject
145  */
146
147 #define DTMF_THRESHOLD          8.0e7
148 #define FAX_THRESHOLD           8.0e7
149 #define FAX_2ND_HARMONIC        2.0     /* 4dB */
150 #define DTMF_NORMAL_TWIST       6.3     /* 8dB */
151 #ifdef  RADIO_RELAX
152 #define DTMF_REVERSE_TWIST          ((digitmode & DSP_DIGITMODE_RELAXDTMF) ? 6.5 : 2.5)     /* 4dB normal */
153 #else
154 #define DTMF_REVERSE_TWIST          ((digitmode & DSP_DIGITMODE_RELAXDTMF) ? 4.0 : 2.5)     /* 4dB normal */
155 #endif
156 #define DTMF_RELATIVE_PEAK_ROW  6.3     /* 8dB */
157 #define DTMF_RELATIVE_PEAK_COL  6.3     /* 8dB */
158 #define DTMF_2ND_HARMONIC_ROW       ((digitmode & DSP_DIGITMODE_RELAXDTMF) ? 1.7 : 2.5)     /* 4dB normal */
159 #define DTMF_2ND_HARMONIC_COL   63.1    /* 18dB */
160 #define DTMF_TO_TOTAL_ENERGY    42.0
161
162 #define BELL_MF_THRESHOLD       1.6e9
163 #define BELL_MF_TWIST           4.0     /* 6dB */
164 #define BELL_MF_RELATIVE_PEAK   12.6    /* 11dB */
165
166 #if defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
167 #error You cant use BUSYDETECT_TONEONLY together with BUSYDETECT_COMPARE_TONE_AND_SILENCE
168 #endif
169
170 /* The CNG signal consists of the transmission of 1100 Hz for 1/2 second,
171  * followed by a 3 second silent (2100 Hz OFF) period.
172  */
173 #define FAX_TONE_CNG_FREQ       1100
174 #define FAX_TONE_CNG_DURATION   500
175 #define FAX_TONE_CNG_DB         16
176
177 /* This signal may be sent by the Terminating FAX machine anywhere between
178  * 1.8 to 2.5 seconds AFTER answering the call.  The CED signal consists
179  * of a 2100 Hz tone that is from 2.6 to 4 seconds in duration.
180 */
181 #define FAX_TONE_CED_FREQ       2100
182 #define FAX_TONE_CED_DURATION   2600
183 #define FAX_TONE_CED_DB         16
184
185 #define SAMPLE_RATE             8000
186
187 /* How many samples a frame has.  This constant is used when calculating
188  * Goertzel block size for tone_detect.  It is only important if we want to
189  * remove (squelch) the tone. In this case it is important to have block
190  * size not to exceed size of voice frame.  Otherwise by the moment the tone
191  * is detected it is too late to squelch it from previous frames.
192  */
193 #define SAMPLES_IN_FRAME        160
194
195
196 typedef struct {
197         int v2;
198         int v3;
199         int chunky;
200         int fac;
201         int samples;
202 } goertzel_state_t;
203
204 typedef struct {
205         int value;
206         int power;
207 } goertzel_result_t;
208
209 typedef struct
210 {
211         int freq;
212         int block_size;
213         int squelch;            /* Remove (squelch) tone */
214         goertzel_state_t tone;
215         float energy;           /* Accumulated energy of the current block */
216         int samples_pending;    /* Samples remain to complete the current block */
217
218         int hits_required;      /* How many successive blocks with tone we are looking for */
219         float threshold;        /* Energy of the tone relative to energy from all other signals to consider a hit */
220
221         int hit_count;          /* How many successive blocks we consider tone present */
222         int last_hit;           /* Indicates if the last processed block was a hit */
223
224 } tone_detect_state_t;
225
226 typedef struct
227 {
228         goertzel_state_t row_out[4];
229         goertzel_state_t col_out[4];
230         int lasthit;
231         int current_hit;
232         float energy;
233         int current_sample;
234 } dtmf_detect_state_t;
235
236 typedef struct
237 {
238         goertzel_state_t tone_out[6];
239         int current_hit;
240         int hits[5];
241         int current_sample;
242 } mf_detect_state_t;
243
244 typedef struct
245 {
246         char digits[MAX_DTMF_DIGITS + 1];
247         int current_digits;
248         int detected_digits;
249         int lost_digits;
250
251         union {
252                 dtmf_detect_state_t dtmf;
253                 mf_detect_state_t mf;
254         } td;
255 } digit_detect_state_t;
256
257 static float dtmf_row[] =
258 {
259         697.0,  770.0,  852.0,  941.0
260 };
261 static float dtmf_col[] =
262 {
263         1209.0, 1336.0, 1477.0, 1633.0
264 };
265
266 static float mf_tones[] =
267 {
268         700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
269 };
270
271 static char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
272
273 static char bell_mf_positions[] = "1247C-358A--69*---0B----#";
274
275 static inline void goertzel_sample(goertzel_state_t *s, short sample)
276 {
277         int v1;
278         
279         v1 = s->v2;
280         s->v2 = s->v3;
281         
282         s->v3 = (s->fac * s->v2) >> 15;
283         s->v3 = s->v3 - v1 + (sample >> s->chunky);
284         if (abs(s->v3) > 32768) {
285                 s->chunky++;
286                 s->v3 = s->v3 >> 1;
287                 s->v2 = s->v2 >> 1;
288                 v1 = v1 >> 1;
289         }
290 }
291
292 static inline void goertzel_update(goertzel_state_t *s, short *samps, int count)
293 {
294         int i;
295         
296         for (i=0;i<count;i++) 
297                 goertzel_sample(s, samps[i]);
298 }
299
300
301 static inline float goertzel_result(goertzel_state_t *s)
302 {
303         goertzel_result_t r;
304         r.value = (s->v3 * s->v3) + (s->v2 * s->v2);
305         r.value -= ((s->v2 * s->v3) >> 15) * s->fac;
306         r.power = s->chunky * 2;
307         return (float)r.value * (float)(1 << r.power);
308 }
309
310 static inline void goertzel_init(goertzel_state_t *s, float freq, int samples)
311 {
312         s->v2 = s->v3 = s->chunky = 0.0;
313         s->fac = (int)(32768.0 * 2.0 * cos(2.0 * M_PI * freq / SAMPLE_RATE));
314         s->samples = samples;
315 }
316
317 static inline void goertzel_reset(goertzel_state_t *s)
318 {
319         s->v2 = s->v3 = s->chunky = 0.0;
320 }
321
322 struct ast_dsp {
323         struct ast_frame f;
324         int threshold;
325         int totalsilence;
326         int totalnoise;
327         int features;
328         int ringtimeout;
329         int busymaybe;
330         int busycount;
331         int busy_tonelength;
332         int busy_quietlength;
333         int historicnoise[DSP_HISTORY];
334         int historicsilence[DSP_HISTORY];
335         goertzel_state_t freqs[7];
336         int freqcount;
337         int gsamps;
338         enum gsamp_size gsamp_size;
339         enum prog_mode progmode;
340         int tstate;
341         int tcount;
342         int digitmode;
343         int faxmode;
344         int thinkdigit;
345         float genergy;
346         digit_detect_state_t digit_state;
347         tone_detect_state_t cng_tone_state;
348         tone_detect_state_t ced_tone_state;
349 };
350
351 static void ast_tone_detect_init(tone_detect_state_t *s, int freq, int duration, int amp)
352 {
353         int duration_samples;
354         float x;
355         int periods_in_block;
356
357         s->freq = freq;
358
359         /* Desired tone duration in samples */
360         duration_samples = duration * SAMPLE_RATE / 1000;
361         /* We want to allow 10% deviation of tone duration */
362         duration_samples = duration_samples * 9 / 10;
363
364         /* If we want to remove tone, it is important to have block size not
365            to exceed frame size. Otherwise by the moment tone is detected it is too late
366            to squelch it from previous frames */
367         s->block_size = SAMPLES_IN_FRAME;
368
369         periods_in_block = s->block_size * freq / SAMPLE_RATE;
370
371         /* Make sure we will have at least 5 periods at target frequency for analisys.
372            This may make block larger than expected packet and will make squelching impossible
373            but at least we will be detecting the tone */
374         if (periods_in_block < 5)
375                 periods_in_block = 5;
376
377         /* Now calculate final block size. It will contain integer number of periods */
378         s->block_size = periods_in_block * SAMPLE_RATE / freq;
379
380         /* tone_detect is currently only used to detect fax tones and we
381            do not need suqlching the fax tones */
382         s->squelch = 0;
383
384         /* Account for the first and the last block to be incomplete
385            and thus no tone will be detected in them */
386         s->hits_required = (duration_samples - (s->block_size - 1)) / s->block_size;
387
388         goertzel_init(&s->tone, freq, s->block_size);
389
390         s->samples_pending = s->block_size;
391         s->hit_count = 0;
392         s->last_hit = 0;
393         s->energy = 0.0;
394
395         /* We want tone energy to be amp decibels above the rest of the signal (the noise).
396            According to Parseval's theorem the energy computed in time domain equals to energy
397            computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
398            from the energy in the time domain we will get energy of the remaining signal (without the tone
399            we are detecting). We will be checking that
400                 10*log(Ew / (Et - Ew)) > amp
401            Calculate threshold so that we will be actually checking
402                 Ew > Et * threshold
403         */
404
405         x = pow(10.0, amp / 10.0);
406         s->threshold = x / (x + 1);
407
408         ast_debug(1, "Setup tone %d Hz, %d ms, block_size=%d, hits_required=%d\n", freq, duration, s->block_size, s->hits_required);
409 }
410
411 static void ast_fax_detect_init(struct ast_dsp *s)
412 {
413         ast_tone_detect_init(&s->cng_tone_state, FAX_TONE_CNG_FREQ, FAX_TONE_CNG_DURATION, FAX_TONE_CNG_DB);
414         ast_tone_detect_init(&s->ced_tone_state, FAX_TONE_CED_FREQ, FAX_TONE_CED_DURATION, FAX_TONE_CED_DB);
415 }
416
417 static void ast_dtmf_detect_init (dtmf_detect_state_t *s)
418 {
419         int i;
420
421         s->lasthit = 0;
422         s->current_hit = 0;
423         for (i = 0;  i < 4;  i++) {
424                 goertzel_init (&s->row_out[i], dtmf_row[i], 102);
425                 goertzel_init (&s->col_out[i], dtmf_col[i], 102);
426                 s->energy = 0.0;
427         }
428         s->current_sample = 0;
429 }
430
431 static void ast_mf_detect_init (mf_detect_state_t *s)
432 {
433         int i;
434         s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
435         for (i = 0;  i < 6;  i++) {
436                 goertzel_init (&s->tone_out[i], mf_tones[i], 160);
437         }
438         s->current_sample = 0;
439         s->current_hit = 0;
440 }
441
442 static void ast_digit_detect_init(digit_detect_state_t *s, int mf)
443 {
444         s->current_digits = 0;
445         s->detected_digits = 0;
446         s->lost_digits = 0;
447         s->digits[0] = '\0';
448
449         if (mf)
450                 ast_mf_detect_init(&s->td.mf);
451         else
452                 ast_dtmf_detect_init(&s->td.dtmf);
453 }
454
455 static int tone_detect(tone_detect_state_t *s, int16_t *amp, int samples, 
456                  int *writeback)
457 {
458         float tone_energy;
459         int i;
460         int hit = 0;
461         int limit;
462         int res = 0;
463         int16_t *ptr;
464
465         while (1) {
466                 /* Process in blocks. */
467                 limit = (samples < s->samples_pending) ? samples : s->samples_pending;
468
469                 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
470                         /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
471                         s->energy += (int32_t) *ptr * (int32_t) *ptr;
472
473                         goertzel_sample(&s->tone, *ptr);
474                 }
475
476                 s->samples_pending -= limit;
477
478                 if (s->samples_pending) {
479                         /* Finished incomplete (last) block */
480                         if (s->last_hit && s->squelch) {
481                                 /* If we had a hit last time, go ahead and clear this out since likely it
482                                    will be another hit */
483                                 memset(amp, 0, sizeof(*amp) * limit);
484                                 if (writeback)
485                                         *writeback = 1;
486                         }
487                         break;
488                 }
489
490
491                 tone_energy = goertzel_result(&s->tone);
492
493                 /* Scale to make comparable */
494                 tone_energy *= 2.0;
495                 s->energy *= s->block_size;
496
497                 ast_debug(10, "tone %d, Ew=%f, Et=%f, s/n=%10.2f\n", s->freq, tone_energy, s->energy, tone_energy / (s->energy - tone_energy));
498                 hit = 0;
499                 if (tone_energy > s->energy * s->threshold) {
500
501                         ast_debug(10, "Hit! count=%d\n", s->hit_count);
502                         hit = 1;
503
504                         if (s->squelch) {
505                                 /* Zero out frame data */
506                                 memset(amp, 0, sizeof(*amp) * limit);
507                                 if (writeback)
508                                         *writeback = 1;
509                         }
510                 }
511
512                 if (s->hit_count)
513                         s->hit_count++;
514
515                 if (hit == s->last_hit) {
516                         if (!hit) {
517                                 /* Two successive misses. Tone ended */
518                                 s->hit_count = 0;
519                         } else if (!s->hit_count) {
520                                 s->hit_count++;
521                         }
522
523                 }
524
525                 if (s->hit_count == s->hits_required) {
526                         ast_debug(1, "%d Hz done detected\n", s->freq);
527                         res = 1;
528                 }
529
530                 s->last_hit = hit;
531
532                 /* Reset for the next block */
533                 goertzel_reset(&s->tone);
534
535                 /* Advance to the next block */
536                 s->energy = 0.0;
537                 s->samples_pending = s->block_size;
538
539                 amp += limit;
540                 samples -= limit;
541         }
542
543         return res;
544 }
545
546 static void store_digit(digit_detect_state_t *s, char digit)
547 {
548         s->detected_digits++;
549         if (s->current_digits < MAX_DTMF_DIGITS) {
550                 s->digits[s->current_digits++] = digit;
551                 s->digits[s->current_digits] = '\0';
552         } else {
553                 ast_log(LOG_WARNING, "Digit lost due to full buffer\n");
554                 s->lost_digits++;
555         }
556 }
557
558 static int dtmf_detect(digit_detect_state_t *s, int16_t amp[], int samples, 
559                  int digitmode, int *writeback)
560 {
561         float row_energy[4];
562         float col_energy[4];
563         float famp;
564         int i;
565         int j;
566         int sample;
567         int best_row;
568         int best_col;
569         int hit;
570         int limit;
571
572         hit = 0;
573         for (sample = 0;  sample < samples;  sample = limit) {
574                 /* 102 is optimised to meet the DTMF specs. */
575                 if ((samples - sample) >= (102 - s->td.dtmf.current_sample))
576                         limit = sample + (102 - s->td.dtmf.current_sample);
577                 else
578                         limit = samples;
579                 /* The following unrolled loop takes only 35% (rough estimate) of the 
580                    time of a rolled loop on the machine on which it was developed */
581                 for (j = sample; j < limit; j++) {
582                         famp = amp[j];
583                         s->td.dtmf.energy += famp*famp;
584                         /* With GCC 2.95, the following unrolled code seems to take about 35%
585                            (rough estimate) as long as a neat little 0-3 loop */
586                         goertzel_sample(s->td.dtmf.row_out, amp[j]);
587                         goertzel_sample(s->td.dtmf.col_out, amp[j]);
588                         goertzel_sample(s->td.dtmf.row_out + 1, amp[j]);
589                         goertzel_sample(s->td.dtmf.col_out + 1, amp[j]);
590                         goertzel_sample(s->td.dtmf.row_out + 2, amp[j]);
591                         goertzel_sample(s->td.dtmf.col_out + 2, amp[j]);
592                         goertzel_sample(s->td.dtmf.row_out + 3, amp[j]);
593                         goertzel_sample(s->td.dtmf.col_out + 3, amp[j]);
594                 }
595                 s->td.dtmf.current_sample += (limit - sample);
596                 if (s->td.dtmf.current_sample < 102) {
597                         if (hit && !((digitmode & DSP_DIGITMODE_NOQUELCH))) {
598                                 /* If we had a hit last time, go ahead and clear this out since likely it
599                                    will be another hit */
600                                 for (i=sample;i<limit;i++) 
601                                         amp[i] = 0;
602                                 *writeback = 1;
603                         }
604                         continue;
605                 }
606                 /* We are at the end of a DTMF detection block */
607                 /* Find the peak row and the peak column */
608                 row_energy[0] = goertzel_result (&s->td.dtmf.row_out[0]);
609                 col_energy[0] = goertzel_result (&s->td.dtmf.col_out[0]);
610
611                 for (best_row = best_col = 0, i = 1;  i < 4;  i++) {
612                         row_energy[i] = goertzel_result (&s->td.dtmf.row_out[i]);
613                         if (row_energy[i] > row_energy[best_row])
614                                 best_row = i;
615                         col_energy[i] = goertzel_result (&s->td.dtmf.col_out[i]);
616                         if (col_energy[i] > col_energy[best_col])
617                                 best_col = i;
618                 }
619                 hit = 0;
620                 /* Basic signal level test and the twist test */
621                 if (row_energy[best_row] >= DTMF_THRESHOLD && 
622                     col_energy[best_col] >= DTMF_THRESHOLD &&
623                     col_energy[best_col] < row_energy[best_row]*DTMF_REVERSE_TWIST &&
624                     col_energy[best_col]*DTMF_NORMAL_TWIST > row_energy[best_row]) {
625                         /* Relative peak test */
626                         for (i = 0;  i < 4;  i++) {
627                                 if ((i != best_col &&
628                                     col_energy[i]*DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
629                                     (i != best_row 
630                                      && row_energy[i]*DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
631                                         break;
632                                 }
633                         }
634                         /* ... and fraction of total energy test */
635                         if (i >= 4 &&
636                             (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY*s->td.dtmf.energy) {
637                                 /* Got a hit */
638                                 hit = dtmf_positions[(best_row << 2) + best_col];
639                                 if (!(digitmode & DSP_DIGITMODE_NOQUELCH)) {
640                                         /* Zero out frame data if this is part DTMF */
641                                         for (i=sample;i<limit;i++) 
642                                                 amp[i] = 0;
643                                         *writeback = 1;
644                                 }
645                         }
646                 } 
647
648                 /* The logic in the next test is:
649                    For digits we need two successive identical clean detects, with
650                    something different preceeding it. This can work with
651                    back to back differing digits. More importantly, it
652                    can work with nasty phones that give a very wobbly start
653                    to a digit */
654                 if (hit != s->td.dtmf.current_hit) {
655                         if (hit && s->td.dtmf.lasthit == hit) {
656                                 s->td.dtmf.current_hit = hit;
657                                 store_digit(s, hit);
658                         } else if (s->td.dtmf.lasthit != s->td.dtmf.current_hit) {
659                                 s->td.dtmf.current_hit = 0;
660                         }
661                 }
662                 s->td.dtmf.lasthit = hit;
663
664                 /* Reinitialise the detector for the next block */
665                 for (i = 0;  i < 4;  i++) {
666                         goertzel_reset(&s->td.dtmf.row_out[i]);
667                         goertzel_reset(&s->td.dtmf.col_out[i]);
668                 }
669                 s->td.dtmf.energy = 0.0;
670                 s->td.dtmf.current_sample = 0;
671         }
672         return (s->td.dtmf.current_hit);        /* return the debounced hit */
673 }
674
675 /* MF goertzel size */
676 #define MF_GSIZE 120
677
678 static int mf_detect(digit_detect_state_t *s, int16_t amp[],
679                  int samples, int digitmode, int *writeback)
680 {
681         float energy[6];
682         int best;
683         int second_best;
684         float famp;
685         int i;
686         int j;
687         int sample;
688         int hit;
689         int limit;
690
691         hit = 0;
692         for (sample = 0;  sample < samples;  sample = limit) {
693                 /* 80 is optimised to meet the MF specs. */
694                 if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample))
695                         limit = sample + (MF_GSIZE - s->td.mf.current_sample);
696                 else
697                         limit = samples;
698                 /* The following unrolled loop takes only 35% (rough estimate) of the 
699                    time of a rolled loop on the machine on which it was developed */
700                 for (j = sample;  j < limit;  j++) {
701                         famp = amp[j];
702                         /* With GCC 2.95, the following unrolled code seems to take about 35%
703                            (rough estimate) as long as a neat little 0-3 loop */
704                         goertzel_sample(s->td.mf.tone_out, amp[j]);
705                         goertzel_sample(s->td.mf.tone_out + 1, amp[j]);
706                         goertzel_sample(s->td.mf.tone_out + 2, amp[j]);
707                         goertzel_sample(s->td.mf.tone_out + 3, amp[j]);
708                         goertzel_sample(s->td.mf.tone_out + 4, amp[j]);
709                         goertzel_sample(s->td.mf.tone_out + 5, amp[j]);
710                 }
711                 s->td.mf.current_sample += (limit - sample);
712                 if (s->td.mf.current_sample < MF_GSIZE) {
713                         if (hit && !((digitmode & DSP_DIGITMODE_NOQUELCH))) {
714                                 /* If we had a hit last time, go ahead and clear this out since likely it
715                                    will be another hit */
716                                 for (i=sample;i<limit;i++) 
717                                         amp[i] = 0;
718                                 *writeback = 1;
719                         }
720                         continue;
721                 }
722                 /* We're at the end of an MF detection block.  */
723                 /* Find the two highest energies. The spec says to look for
724                    two tones and two tones only. Taking this literally -ie
725                    only two tones pass the minimum threshold - doesn't work
726                    well. The sinc function mess, due to rectangular windowing
727                    ensure that! Find the two highest energies and ensure they
728                    are considerably stronger than any of the others. */
729                 energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
730                 energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
731                 if (energy[0] > energy[1]) {
732                         best = 0;
733                         second_best = 1;
734                 } else {
735                         best = 1;
736                         second_best = 0;
737                 }
738                 /*endif*/
739                 for (i=2;i<6;i++) {
740                         energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
741                         if (energy[i] >= energy[best]) {
742                                 second_best = best;
743                                 best = i;
744                         } else if (energy[i] >= energy[second_best]) {
745                                 second_best = i;
746                         }
747                 }
748                 /* Basic signal level and twist tests */
749                 hit = 0;
750                 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
751                     && energy[best] < energy[second_best]*BELL_MF_TWIST
752                     && energy[best]*BELL_MF_TWIST > energy[second_best]) {
753                         /* Relative peak test */
754                         hit = -1;
755                         for (i=0;i<6;i++) {
756                                 if (i != best && i != second_best) {
757                                         if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
758                                                 /* The best two are not clearly the best */
759                                                 hit = 0;
760                                                 break;
761                                         }
762                                 }
763                         }
764                 }
765                 if (hit) {
766                         /* Get the values into ascending order */
767                         if (second_best < best) {
768                                 i = best;
769                                 best = second_best;
770                                 second_best = i;
771                         }
772                         best = best*5 + second_best - 1;
773                         hit = bell_mf_positions[best];
774                         /* Look for two successive similar results */
775                         /* The logic in the next test is:
776                            For KP we need 4 successive identical clean detects, with
777                            two blocks of something different preceeding it. For anything
778                            else we need two successive identical clean detects, with
779                            two blocks of something different preceeding it. */
780                         if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
781                            ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
782                             (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] && 
783                             hit != s->td.mf.hits[0]))) {
784                                 store_digit(s, hit);
785                         }
786                 }
787
788
789                 if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
790                         /* Two successive block without a hit terminate current digit */
791                         s->td.mf.current_hit = 0;
792                 }
793
794                 s->td.mf.hits[0] = s->td.mf.hits[1];
795                 s->td.mf.hits[1] = s->td.mf.hits[2];
796                 s->td.mf.hits[2] = s->td.mf.hits[3];
797                 s->td.mf.hits[3] = s->td.mf.hits[4];
798                 s->td.mf.hits[4] = hit;
799                 /* Reinitialise the detector for the next block */
800                 for (i = 0;  i < 6;  i++)
801                         goertzel_reset(&s->td.mf.tone_out[i]);
802                 s->td.mf.current_sample = 0;
803         }
804
805         return (s->td.mf.current_hit); /* return the debounced hit */
806 }
807
808 static int __ast_dsp_digitdetect(struct ast_dsp *dsp, short *s, int len, int *writeback)
809 {
810         int res = 0;
811         
812         if ((dsp->features & DSP_FEATURE_DTMF_DETECT) && (dsp->digitmode & DSP_DIGITMODE_MF))
813                 res = mf_detect(&dsp->digit_state, s, len, dsp->digitmode & DSP_DIGITMODE_RELAXDTMF, writeback);
814         else if (dsp->features & DSP_FEATURE_DTMF_DETECT)
815                 res = dtmf_detect(&dsp->digit_state, s, len, dsp->digitmode & DSP_DIGITMODE_RELAXDTMF, writeback);
816
817         if ((dsp->features & DSP_FEATURE_FAX_DETECT) && (dsp->faxmode & DSP_FAXMODE_DETECT_CNG)) {
818                 if (tone_detect(&dsp->cng_tone_state, s, len, NULL)) {
819                         store_digit(&dsp->digit_state, 'f');
820                         res = 'f';
821                 }
822         }
823
824         if ((dsp->features & DSP_FEATURE_FAX_DETECT) && (dsp->faxmode & DSP_FAXMODE_DETECT_CED)) {
825                 if (tone_detect(&dsp->ced_tone_state, s, len, NULL)) {
826                         store_digit(&dsp->digit_state, 'e');
827                         res = 'e';
828                 }
829         }
830
831         return res;
832 }
833
834 int ast_dsp_digitdetect(struct ast_dsp *dsp, struct ast_frame *inf)
835 {
836         short *s;
837         int len;
838         int ign=0;
839
840         if (inf->frametype != AST_FRAME_VOICE) {
841                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
842                 return 0;
843         }
844         if (inf->subclass != AST_FORMAT_SLINEAR) {
845                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
846                 return 0;
847         }
848         s = inf->data;
849         len = inf->datalen / 2;
850         return __ast_dsp_digitdetect(dsp, s, len, &ign);
851 }
852
853 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
854 {
855         /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
856         /* Make sure absolute levels are high enough */
857         if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH))
858                 return 0;
859         /* Amplify ignored stuff */
860         i2 *= TONE_THRESH;
861         i1 *= TONE_THRESH;
862         e *= TONE_THRESH;
863         /* Check first tone */
864         if ((p1 < i1) || (p1 < i2) || (p1 < e))
865                 return 0;
866         /* And second */
867         if ((p2 < i1) || (p2 < i2) || (p2 < e))
868                 return 0;
869         /* Guess it's there... */
870         return 1;
871 }
872
873 int ast_dsp_getdigits(struct ast_dsp *dsp, char *buf, int max)
874 {
875         if (max > dsp->digit_state.current_digits)
876                 max = dsp->digit_state.current_digits;
877         if (max > 0) {
878                 memcpy(buf, dsp->digit_state.digits, max);
879                 memmove(dsp->digit_state.digits, dsp->digit_state.digits + max, dsp->digit_state.current_digits - max);
880                 dsp->digit_state.current_digits -= max;
881         }
882         buf[max] = '\0';
883         return  max;
884 }
885
886 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
887 {
888         int x;
889         int y;
890         int pass;
891         int newstate = DSP_TONE_STATE_SILENCE;
892         int res = 0;
893         while (len) {
894                 /* Take the lesser of the number of samples we need and what we have */
895                 pass = len;
896                 if (pass > dsp->gsamp_size - dsp->gsamps) 
897                         pass = dsp->gsamp_size - dsp->gsamps;
898                 for (x=0;x<pass;x++) {
899                         for (y=0;y<dsp->freqcount;y++) 
900                                 goertzel_sample(&dsp->freqs[y], s[x]);
901                         dsp->genergy += s[x] * s[x];
902                 }
903                 s += pass;
904                 dsp->gsamps += pass;
905                 len -= pass;
906                 if (dsp->gsamps == dsp->gsamp_size) {
907                         float hz[7];
908                         for (y=0;y<7;y++)
909                                 hz[y] = goertzel_result(&dsp->freqs[y]);
910                         switch (dsp->progmode) {
911                         case PROG_MODE_NA:
912                                 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
913                                         newstate = DSP_TONE_STATE_BUSY;
914                                 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
915                                         newstate = DSP_TONE_STATE_RINGING;
916                                 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
917                                         newstate = DSP_TONE_STATE_DIALTONE;
918                                 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
919                                         newstate = DSP_TONE_STATE_SPECIAL1;
920                                 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
921                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL1)
922                                                 newstate = DSP_TONE_STATE_SPECIAL2;
923                                 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
924                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL2)
925                                                 newstate = DSP_TONE_STATE_SPECIAL3;
926                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
927                                         newstate = DSP_TONE_STATE_TALKING;
928                                 } else
929                                         newstate = DSP_TONE_STATE_SILENCE;
930                                 break;
931                         case PROG_MODE_CR:
932                                 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
933                                         newstate = DSP_TONE_STATE_RINGING;
934                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
935                                         newstate = DSP_TONE_STATE_TALKING;
936                                 } else
937                                         newstate = DSP_TONE_STATE_SILENCE;
938                                 break;
939                         case PROG_MODE_UK:
940                                 if (hz[HZ_400] > TONE_MIN_THRESH * TONE_THRESH) {
941                                         newstate = DSP_TONE_STATE_HUNGUP;
942                                 }
943                                 break;
944                         default:
945                                 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
946                         }
947                         if (newstate == dsp->tstate) {
948                                 dsp->tcount++;
949                                 if (dsp->ringtimeout)
950                                         dsp->ringtimeout++;
951                                 switch (dsp->tstate) {
952                                         case DSP_TONE_STATE_RINGING:
953                                                 if ((dsp->features & DSP_PROGRESS_RINGING) &&
954                                                     (dsp->tcount==THRESH_RING)) {
955                                                         res = AST_CONTROL_RINGING;
956                                                         dsp->ringtimeout= 1;
957                                                 }
958                                                 break;
959                                         case DSP_TONE_STATE_BUSY:
960                                                 if ((dsp->features & DSP_PROGRESS_BUSY) &&
961                                                     (dsp->tcount==THRESH_BUSY)) {
962                                                         res = AST_CONTROL_BUSY;
963                                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
964                                                 }
965                                                 break;
966                                         case DSP_TONE_STATE_TALKING:
967                                                 if ((dsp->features & DSP_PROGRESS_TALK) &&
968                                                     (dsp->tcount==THRESH_TALK)) {
969                                                         res = AST_CONTROL_ANSWER;
970                                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
971                                                 }
972                                                 break;
973                                         case DSP_TONE_STATE_SPECIAL3:
974                                                 if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
975                                                     (dsp->tcount==THRESH_CONGESTION)) {
976                                                         res = AST_CONTROL_CONGESTION;
977                                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
978                                                 }
979                                                 break;
980                                         case DSP_TONE_STATE_HUNGUP:
981                                                 if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
982                                                     (dsp->tcount==THRESH_HANGUP)) {
983                                                         res = AST_CONTROL_HANGUP;
984                                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
985                                                 }
986                                                 break;
987                                 }
988                                 if (dsp->ringtimeout==THRESH_RING2ANSWER) {
989                                         ast_debug(1, "Consider call as answered because of timeout after last ring\n");
990                                         res = AST_CONTROL_ANSWER;
991                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
992                                 }
993                         } else {
994                                 ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
995                                 ast_debug(5, "Start state %d\n", newstate);
996                                 dsp->tstate = newstate;
997                                 dsp->tcount = 1;
998                         }
999                         
1000                         /* Reset goertzel */                                            
1001                         for (x=0;x<7;x++)
1002                                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1003                         dsp->gsamps = 0;
1004                         dsp->genergy = 0.0;
1005                 }
1006         }
1007
1008         return res;
1009 }
1010
1011 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1012 {
1013         if (inf->frametype != AST_FRAME_VOICE) {
1014                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1015                 return 0;
1016         }
1017         if (inf->subclass != AST_FORMAT_SLINEAR) {
1018                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1019                 return 0;
1020         }
1021         return __ast_dsp_call_progress(dsp, inf->data, inf->datalen / 2);
1022 }
1023
1024 static int __ast_dsp_silence(struct ast_dsp *dsp, short *s, int len, int *totalsilence)
1025 {
1026         int accum;
1027         int x;
1028         int res = 0;
1029
1030         if (!len)
1031                 return 0;
1032         accum = 0;
1033         for (x=0;x<len; x++) 
1034                 accum += abs(s[x]);
1035         accum /= len;
1036         if (accum < dsp->threshold) {
1037                 /* Silent */
1038                 dsp->totalsilence += len/8;
1039                 if (dsp->totalnoise) {
1040                         /* Move and save history */
1041                         memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount +1, dsp->busycount*sizeof(dsp->historicnoise[0]));
1042                         dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1043 /* we don't want to check for busydetect that frequently */
1044 #if 0
1045                         dsp->busymaybe = 1;
1046 #endif
1047                 }
1048                 dsp->totalnoise = 0;
1049                 res = 1;
1050         } else {
1051                 /* Not silent */
1052                 dsp->totalnoise += len/8;
1053                 if (dsp->totalsilence) {
1054                         int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1055                         int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1056                         /* Move and save history */
1057                         memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount*sizeof(dsp->historicsilence[0]));
1058                         dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1059                         /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1060                         if (silence1 < silence2) {
1061                                 if (silence1 + silence1*BUSY_PERCENT/100 >= silence2)
1062                                         dsp->busymaybe = 1;
1063                                 else 
1064                                         dsp->busymaybe = 0;
1065                         } else {
1066                                 if (silence1 - silence1*BUSY_PERCENT/100 <= silence2)
1067                                         dsp->busymaybe = 1;
1068                                 else 
1069                                         dsp->busymaybe = 0;
1070                         }
1071                 }
1072                 dsp->totalsilence = 0;
1073         }
1074         if (totalsilence)
1075                 *totalsilence = dsp->totalsilence;
1076         return res;
1077 }
1078
1079 int ast_dsp_busydetect(struct ast_dsp *dsp)
1080 {
1081         int res = 0, x;
1082 #ifndef BUSYDETECT_TONEONLY
1083         int avgsilence = 0, hitsilence = 0;
1084 #endif
1085         int avgtone = 0, hittone = 0;
1086         if (!dsp->busymaybe)
1087                 return res;
1088         for (x=DSP_HISTORY - dsp->busycount;x<DSP_HISTORY;x++) {
1089 #ifndef BUSYDETECT_TONEONLY
1090                 avgsilence += dsp->historicsilence[x];
1091 #endif
1092                 avgtone += dsp->historicnoise[x];
1093         }
1094 #ifndef BUSYDETECT_TONEONLY
1095         avgsilence /= dsp->busycount;
1096 #endif
1097         avgtone /= dsp->busycount;
1098         for (x=DSP_HISTORY - dsp->busycount;x<DSP_HISTORY;x++) {
1099 #ifndef BUSYDETECT_TONEONLY
1100                 if (avgsilence > dsp->historicsilence[x]) {
1101                         if (avgsilence - (avgsilence*BUSY_PERCENT/100) <= dsp->historicsilence[x])
1102                                 hitsilence++;
1103                 } else {
1104                         if (avgsilence + (avgsilence*BUSY_PERCENT/100) >= dsp->historicsilence[x])
1105                                 hitsilence++;
1106                 }
1107 #endif
1108                 if (avgtone > dsp->historicnoise[x]) {
1109                         if (avgtone - (avgtone*BUSY_PERCENT/100) <= dsp->historicnoise[x])
1110                                 hittone++;
1111                 } else {
1112                         if (avgtone + (avgtone*BUSY_PERCENT/100) >= dsp->historicnoise[x])
1113                                 hittone++;
1114                 }
1115         }
1116 #ifndef BUSYDETECT_TONEONLY
1117         if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) && 
1118             (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) && 
1119             (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1120 #else
1121         if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1122 #endif
1123 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1124                 if (avgtone > avgsilence) {
1125                         if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence)
1126                                 res = 1;
1127                 } else {
1128                         if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence)
1129                                 res = 1;
1130                 }
1131 #else
1132                 res = 1;
1133 #endif
1134         }
1135         /* If we know the expected busy tone length, check we are in the range */
1136         if (res && (dsp->busy_tonelength > 0)) {
1137                 if (abs(avgtone - dsp->busy_tonelength) > (dsp->busy_tonelength*BUSY_PAT_PERCENT/100)) {
1138 #ifdef BUSYDETECT_DEBUG
1139                         ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
1140                                 avgtone, dsp->busy_tonelength);
1141 #endif
1142                         res = 0;
1143                 }
1144         }
1145 #ifndef BUSYDETECT_TONEONLY
1146         /* If we know the expected busy tone silent-period length, check we are in the range */
1147         if (res && (dsp->busy_quietlength > 0)) {
1148                 if (abs(avgsilence - dsp->busy_quietlength) > (dsp->busy_quietlength*BUSY_PAT_PERCENT/100)) {
1149 #ifdef BUSYDETECT_DEBUG
1150                 ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
1151                         avgsilence, dsp->busy_quietlength);
1152 #endif
1153                         res = 0;
1154                 }
1155         }
1156 #endif
1157 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
1158         if (res) {
1159                 ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1160         } else {
1161                 ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1162         }
1163 #endif
1164         return res;
1165 }
1166
1167 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1168 {
1169         short *s;
1170         int len;
1171         
1172         if (f->frametype != AST_FRAME_VOICE) {
1173                 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1174                 return 0;
1175         }
1176         if (f->subclass != AST_FORMAT_SLINEAR) {
1177                 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear frames :(\n");
1178                 return 0;
1179         }
1180         s = f->data;
1181         len = f->datalen/2;
1182         return __ast_dsp_silence(dsp, s, len, totalsilence);
1183 }
1184
1185 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1186 {
1187         int silence;
1188         int res;
1189         int digit;
1190         int x;
1191         short *shortdata;
1192         unsigned char *odata;
1193         int len;
1194         int writeback = 0;
1195
1196 #define FIX_INF(inf) do { \
1197                 if (writeback) { \
1198                         switch (inf->subclass) { \
1199                         case AST_FORMAT_SLINEAR: \
1200                                 break; \
1201                         case AST_FORMAT_ULAW: \
1202                                 for (x=0;x<len;x++) \
1203                                         odata[x] = AST_LIN2MU((unsigned short)shortdata[x]); \
1204                                 break; \
1205                         case AST_FORMAT_ALAW: \
1206                                 for (x=0;x<len;x++) \
1207                                         odata[x] = AST_LIN2A((unsigned short)shortdata[x]); \
1208                                 break; \
1209                         } \
1210                 } \
1211         } while(0) 
1212
1213         if (!af)
1214                 return NULL;
1215         if (af->frametype != AST_FRAME_VOICE)
1216                 return af;
1217         odata = af->data;
1218         len = af->datalen;
1219         /* Make sure we have short data */
1220         switch (af->subclass) {
1221         case AST_FORMAT_SLINEAR:
1222                 shortdata = af->data;
1223                 len = af->datalen / 2;
1224                 break;
1225         case AST_FORMAT_ULAW:
1226                 shortdata = alloca(af->datalen * 2);
1227                 for (x = 0;x < len; x++) 
1228                         shortdata[x] = AST_MULAW(odata[x]);
1229                 break;
1230         case AST_FORMAT_ALAW:
1231                 shortdata = alloca(af->datalen * 2);
1232                 for (x = 0; x < len; x++) 
1233                         shortdata[x] = AST_ALAW(odata[x]);
1234                 break;
1235         default:
1236                 ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(af->subclass));
1237                 return af;
1238         }
1239         silence = __ast_dsp_silence(dsp, shortdata, len, NULL);
1240         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1241                 memset(&dsp->f, 0, sizeof(dsp->f));
1242                 dsp->f.frametype = AST_FRAME_NULL;
1243                 ast_frfree(af);
1244                 return &dsp->f;
1245         }
1246         if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1247                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1248                 memset(&dsp->f, 0, sizeof(dsp->f));
1249                 dsp->f.frametype = AST_FRAME_CONTROL;
1250                 dsp->f.subclass = AST_CONTROL_BUSY;
1251                 ast_frfree(af);
1252                 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", chan->name);
1253                 return &dsp->f;
1254         }
1255         if (((dsp->features & DSP_FEATURE_DTMF_DETECT) || (dsp->features & DSP_FEATURE_FAX_DETECT))) {
1256                 digit = __ast_dsp_digitdetect(dsp, shortdata, len, &writeback);
1257 #if 0
1258                 if (digit)
1259                         printf("Performing digit detection returned %d, digitmode is %d\n", digit, dsp->digitmode);
1260 #endif
1261                 if (dsp->digitmode & (DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX)) {
1262                         if (!dsp->thinkdigit) {
1263                                 if (digit) {
1264                                         /* Looks like we might have something.  
1265                                          * Request a conference mute for the moment */
1266                                         memset(&dsp->f, 0, sizeof(dsp->f));
1267                                         dsp->f.frametype = AST_FRAME_DTMF;
1268                                         dsp->f.subclass = 'm';
1269                                         dsp->thinkdigit = 'x';
1270                                         FIX_INF(af);
1271                                         if (chan)
1272                                                 ast_queue_frame(chan, af);
1273                                         ast_frfree(af);
1274                                         return &dsp->f;
1275                                 }
1276                         } else {
1277                                 if (digit) {
1278                                         /* Thought we saw one last time.  Pretty sure we really have now */
1279                                         if ((dsp->thinkdigit != 'x') && (dsp->thinkdigit != digit)) {
1280                                                 /* If we found a digit, and we're changing digits, go
1281                                                    ahead and send this one, but DON'T stop confmute because
1282                                                    we're detecting something else, too... */
1283                                                 memset(&dsp->f, 0, sizeof(dsp->f));
1284                                                 dsp->f.frametype = AST_FRAME_DTMF_END;
1285                                                 dsp->f.subclass = dsp->thinkdigit;
1286                                                 FIX_INF(af);
1287                                                 if (chan)
1288                                                         ast_queue_frame(chan, af);
1289                                                 ast_frfree(af);
1290                                         } else {
1291                                                 dsp->thinkdigit = digit;
1292                                                 memset(&dsp->f, 0, sizeof(dsp->f));
1293                                                 dsp->f.frametype = AST_FRAME_DTMF_BEGIN;
1294                                                 dsp->f.subclass = dsp->thinkdigit;
1295                                                 FIX_INF(af);
1296                                                 if (chan)
1297                                                         ast_queue_frame(chan, af);
1298                                                 ast_frfree(af);
1299                                         }
1300                                         return &dsp->f;
1301                                 } else {
1302                                         memset(&dsp->f, 0, sizeof(dsp->f));
1303                                         if (dsp->thinkdigit != 'x') {
1304                                                 /* If we found a digit, send it now */
1305                                                 dsp->f.frametype = AST_FRAME_DTMF_END;
1306                                                 dsp->f.subclass = dsp->thinkdigit;
1307                                                 dsp->thinkdigit = 0;
1308                                         } else {
1309                                                 dsp->f.frametype = AST_FRAME_DTMF;
1310                                                 dsp->f.subclass = 'u';
1311                                                 dsp->thinkdigit = 0;
1312                                         }
1313                                         FIX_INF(af);
1314                                         if (chan)
1315                                                 ast_queue_frame(chan, af);
1316                                         ast_frfree(af);
1317                                         return &dsp->f;
1318                                 }
1319                         }
1320                 } else if (dsp->digit_state.current_digits > 1 ||
1321                         (dsp->digit_state.current_digits == 1 && digit != dsp->digit_state.digits[0])) {
1322                         /* Since we basically generate DTMF_END frames we do it only when a digit
1323                            has finished. */
1324
1325                         memset(&dsp->f, 0, sizeof(dsp->f));
1326                         dsp->f.frametype = AST_FRAME_DTMF;
1327                         dsp->f.subclass = dsp->digit_state.digits[0];
1328                         memmove(dsp->digit_state.digits, dsp->digit_state.digits + 1, dsp->digit_state.current_digits);
1329                         dsp->digit_state.current_digits--;
1330                         FIX_INF(af);
1331                         if (chan)
1332                                 ast_queue_frame(chan, af);
1333                         ast_frfree(af);
1334                         return &dsp->f;
1335                 }
1336         }
1337         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1338                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1339                 if (res) {
1340                         switch (res) {
1341                         case AST_CONTROL_ANSWER:
1342                         case AST_CONTROL_BUSY:
1343                         case AST_CONTROL_RINGING:
1344                         case AST_CONTROL_CONGESTION:
1345                         case AST_CONTROL_HANGUP:
1346                                 memset(&dsp->f, 0, sizeof(dsp->f));
1347                                 dsp->f.frametype = AST_FRAME_CONTROL;
1348                                 dsp->f.subclass = res;
1349                                 dsp->f.src = "dsp_progress";
1350                                 if (chan) 
1351                                         ast_queue_frame(chan, &dsp->f);
1352                                 break;
1353                         default:
1354                                 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1355                         }
1356                 }
1357         }
1358         FIX_INF(af);
1359         return af;
1360 }
1361
1362 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1363 {
1364         int max = 0;
1365         int x;
1366         
1367         dsp->gsamp_size = modes[dsp->progmode].size;
1368         dsp->gsamps = 0;
1369         for (x = 0; x < sizeof(modes[dsp->progmode].freqs) / sizeof(modes[dsp->progmode].freqs[0]); x++) {
1370                 if (modes[dsp->progmode].freqs[x]) {
1371                         goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->gsamp_size);
1372                         max = x + 1;
1373                 }
1374         }
1375         dsp->freqcount = max;
1376         dsp->ringtimeout= 0;
1377 }
1378
1379 struct ast_dsp *ast_dsp_new(void)
1380 {
1381         struct ast_dsp *dsp;
1382         
1383         if ((dsp = ast_calloc(1, sizeof(*dsp)))) {              
1384                 dsp->threshold = DEFAULT_THRESHOLD;
1385                 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1386                 dsp->busycount = DSP_HISTORY;
1387                 dsp->digitmode = DSP_DIGITMODE_DTMF;
1388                 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1389                 /* Initialize digit detector */
1390                 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF);
1391                 /* Initialize initial DSP progress detect parameters */
1392                 ast_dsp_prog_reset(dsp);
1393                 /* Initialize fax detector */
1394                 ast_fax_detect_init(dsp);
1395         }
1396         return dsp;
1397 }
1398
1399 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1400 {
1401         dsp->features = features;
1402 }
1403
1404 void ast_dsp_free(struct ast_dsp *dsp)
1405 {
1406         ast_free(dsp);
1407 }
1408
1409 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1410 {
1411         dsp->threshold = threshold;
1412 }
1413
1414 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1415 {
1416         if (cadences < 4)
1417                 cadences = 4;
1418         if (cadences > DSP_HISTORY)
1419                 cadences = DSP_HISTORY;
1420         dsp->busycount = cadences;
1421 }
1422
1423 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, int tonelength, int quietlength)
1424 {
1425         dsp->busy_tonelength = tonelength;
1426         dsp->busy_quietlength = quietlength;
1427         ast_debug(1, "dsp busy pattern set to %d,%d\n", tonelength, quietlength);
1428 }
1429
1430 void ast_dsp_digitreset(struct ast_dsp *dsp)
1431 {
1432         int i;
1433         
1434         dsp->thinkdigit = 0;
1435         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1436                 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1437                 /* Reinitialise the detector for the next block */
1438                 for (i = 0;  i < 6;  i++) {
1439                         goertzel_reset(&s->tone_out[i]);
1440                 }
1441                 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = s->current_hit = 0;
1442                 s->current_sample = 0;
1443         } else {
1444                 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1445                 /* Reinitialise the detector for the next block */
1446                 for (i = 0;  i < 4;  i++) {
1447                         goertzel_reset(&s->row_out[i]);
1448                         goertzel_reset(&s->col_out[i]);
1449                 }
1450                 s->lasthit = s->current_hit = 0;
1451                 s->energy = 0.0;
1452                 s->current_sample = 0;
1453         }
1454
1455         dsp->digit_state.digits[0] = '\0';
1456         dsp->digit_state.current_digits = 0;
1457 }
1458
1459 void ast_dsp_reset(struct ast_dsp *dsp)
1460 {
1461         int x;
1462         
1463         dsp->totalsilence = 0;
1464         dsp->gsamps = 0;
1465         for (x=0;x<4;x++)
1466                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1467         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1468         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));      
1469         dsp->ringtimeout= 0;
1470 }
1471
1472 int ast_dsp_digitmode(struct ast_dsp *dsp, int digitmode)
1473 {
1474         int new;
1475         int old;
1476         
1477         old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1478         new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1479         if (old != new) {
1480                 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1481                 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF);
1482         }
1483         dsp->digitmode = digitmode;
1484         return 0;
1485 }
1486
1487 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1488 {
1489         if (dsp->faxmode != faxmode) {
1490                 ast_fax_detect_init(dsp);
1491         }
1492         dsp->faxmode = faxmode;
1493         return 0;
1494 }
1495
1496 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1497 {
1498         int x;
1499         
1500         for (x = 0; x < ARRAY_LEN(aliases); x++) {
1501                 if (!strcasecmp(aliases[x].name, zone)) {
1502                         dsp->progmode = aliases[x].mode;
1503                         ast_dsp_prog_reset(dsp);
1504                         return 0;
1505                 }
1506         }
1507         return -1;
1508 }
1509
1510 int ast_dsp_get_tstate(struct ast_dsp *dsp) 
1511 {
1512         return dsp->tstate;
1513 }
1514
1515 int ast_dsp_get_tcount(struct ast_dsp *dsp) 
1516 {
1517         return dsp->tcount;
1518 }