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