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