Improvements to DSP callprogress=yes code (#5009)
[asterisk/asterisk.git] / 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 <sys/types.h>
44 #include <stdlib.h>
45 #include <unistd.h>
46 #include <string.h>
47 #include <math.h>
48 #include <errno.h>
49 #include <stdio.h>
50
51 #include "asterisk.h"
52
53 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
54
55 #include "asterisk/frame.h"
56 #include "asterisk/channel.h"
57 #include "asterisk/logger.h"
58 #include "asterisk/dsp.h"
59 #include "asterisk/ulaw.h"
60 #include "asterisk/alaw.h"
61
62 /* Number of goertzels for progress detect */
63 #define GSAMP_SIZE_NA 183                       /* North America - 350, 440, 480, 620, 950, 1400, 1800 Hz */
64 #define GSAMP_SIZE_CR 188                       /* Costa Rica, Brazil - Only care about 425 Hz */
65 #define GSAMP_SIZE_UK 160                       /* UK disconnect goertzel feed - shoud trigger 400hz */
66
67 #define PROG_MODE_NA            0
68 #define PROG_MODE_CR            1       
69 #define PROG_MODE_UK            2       
70
71 /* For US modes */
72 #define HZ_350  0
73 #define HZ_440  1
74 #define HZ_480  2
75 #define HZ_620  3
76 #define HZ_950  4
77 #define HZ_1400 5
78 #define HZ_1800 6
79
80 /* For CR/BR modes */
81 #define HZ_425  0
82
83 /* For UK mode */
84 #define HZ_400  0
85
86 static struct progalias {
87         char *name;
88         int 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         int 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 } },
103         { GSAMP_SIZE_UK, { 400 } },
104 };
105
106 #define DEFAULT_THRESHOLD       512
107
108 #define BUSY_PERCENT            10      /* The percentage difference between the two last silence periods */
109 #define BUSY_PAT_PERCENT        7       /* The percentage difference between measured and actual pattern */
110 #define BUSY_THRESHOLD          100     /* Max number of ms difference between max and min times in busy */
111 #define BUSY_MIN                75      /* Busy must be at least 80 ms in half-cadence */
112 #define BUSY_MAX                3100    /* Busy can't be longer than 3100 ms in half-cadence */
113
114 /* Remember last 15 units */
115 #define DSP_HISTORY             15
116
117 /* Define if you want the fax detector -- NOT RECOMMENDED IN -STABLE */
118 #define FAX_DETECT
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 #define THRESH_RING             8       /* Need at least 150ms ring to accept */
125 #define THRESH_TALK             2       /* Talk detection does not work continously */
126 #define THRESH_BUSY             4       /* Need at least 80ms to accept */
127 #define THRESH_CONGESTION       4       /* Need at least 80ms to accept */
128 #define THRESH_HANGUP           60      /* Need at least 1300ms to accept hangup */
129 #define 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 #ifdef OLD_DSP_ROUTINES
162 #define MF_THRESHOLD            8.0e7
163 #define MF_NORMAL_TWIST         5.3     /* 8dB */
164 #define MF_REVERSE_TWIST        4.0     /* was 2.5 */
165 #define MF_RELATIVE_PEAK        5.3     /* 8dB */
166 #define MF_2ND_HARMONIC         1.7     /* was 2.5  */
167 #else
168 #define BELL_MF_THRESHOLD       1.6e9
169 #define BELL_MF_TWIST           4.0     /* 6dB */
170 #define BELL_MF_RELATIVE_PEAK   12.6    /* 11dB */
171 #endif
172
173 #if !defined(BUSYDETECT_MARTIN) && !defined(BUSYDETECT) && !defined(BUSYDETECT_TONEONLY) && !defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
174 #define BUSYDETECT_MARTIN
175 #endif
176
177 typedef struct {
178         float v2;
179         float v3;
180         float fac;
181 #ifndef OLD_DSP_ROUTINES
182         int samples;
183 #endif  
184 } goertzel_state_t;
185
186 typedef struct
187 {
188         goertzel_state_t row_out[4];
189         goertzel_state_t col_out[4];
190 #ifdef FAX_DETECT
191         goertzel_state_t fax_tone;
192 #endif
193 #ifdef OLD_DSP_ROUTINES
194         goertzel_state_t row_out2nd[4];
195         goertzel_state_t col_out2nd[4];
196 #ifdef FAX_DETECT
197         goertzel_state_t fax_tone2nd;    
198 #endif
199         int hit1;
200         int hit2;
201         int hit3;
202         int hit4;
203 #else
204         int hits[3];
205 #endif  
206         int mhit;
207         float energy;
208         int current_sample;
209
210         char digits[MAX_DTMF_DIGITS + 1];
211         
212         int current_digits;
213         int detected_digits;
214         int lost_digits;
215         int digit_hits[16];
216 #ifdef FAX_DETECT
217         int fax_hits;
218 #endif
219 } dtmf_detect_state_t;
220
221 typedef struct
222 {
223         goertzel_state_t tone_out[6];
224         int mhit;
225 #ifdef OLD_DSP_ROUTINES
226         int hit1;
227         int hit2;
228         int hit3;
229         int hit4;
230         goertzel_state_t tone_out2nd[6];
231         float energy;
232 #else
233         int hits[5];
234 #endif
235         int current_sample;
236         
237         char digits[MAX_DTMF_DIGITS + 1];
238
239         int current_digits;
240         int detected_digits;
241         int lost_digits;
242 #ifdef FAX_DETECT
243         int fax_hits;
244 #endif
245 } mf_detect_state_t;
246
247 static float dtmf_row[] =
248 {
249         697.0,  770.0,  852.0,  941.0
250 };
251 static float dtmf_col[] =
252 {
253         1209.0, 1336.0, 1477.0, 1633.0
254 };
255
256 static float mf_tones[] =
257 {
258         700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
259 };
260
261 #ifdef FAX_DETECT
262 static float fax_freq = 1100.0;
263 #endif
264
265 static char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
266
267 #ifdef OLD_DSP_ROUTINES
268 static char mf_hit[6][6] = {
269         /*  700 + */ {   0, '1', '2', '4', '7', 'C' },
270         /*  900 + */ { '1',   0, '3', '5', '8', 'A' },
271         /* 1100 + */ { '2', '3',   0, '6', '9', '*' },
272         /* 1300 + */ { '4', '5', '6',   0, '0', 'B' },
273         /* 1500 + */ { '7', '8', '9', '0',  0, '#' },
274         /* 1700 + */ { 'C', 'A', '*', 'B', '#',  0  },
275 };
276 #else
277 static char bell_mf_positions[] = "1247C-358A--69*---0B----#";
278 #endif
279
280 static inline void goertzel_sample(goertzel_state_t *s, short sample)
281 {
282         float v1;
283         float fsamp  = sample;
284         
285         v1 = s->v2;
286         s->v2 = s->v3;
287         s->v3 = s->fac * s->v2 - v1 + fsamp;
288 }
289
290 static inline void goertzel_update(goertzel_state_t *s, short *samps, int count)
291 {
292         int i;
293         
294         for (i=0;i<count;i++) 
295                 goertzel_sample(s, samps[i]);
296 }
297
298
299 static inline float goertzel_result(goertzel_state_t *s)
300 {
301         return s->v3 * s->v3 + s->v2 * s->v2 - s->v2 * s->v3 * s->fac;
302 }
303
304 static inline void goertzel_init(goertzel_state_t *s, float freq, int samples)
305 {
306         s->v2 = s->v3 = 0.0;
307         s->fac = 2.0 * cos(2.0 * M_PI * (freq / 8000.0));
308 #ifndef OLD_DSP_ROUTINES
309         s->samples = samples;
310 #endif
311 }
312
313 static inline void goertzel_reset(goertzel_state_t *s)
314 {
315         s->v2 = s->v3 = 0.0;
316 }
317
318 struct ast_dsp {
319         struct ast_frame f;
320         int threshold;
321         int totalsilence;
322         int totalnoise;
323         int features;
324         int ringtimeout;
325         int busymaybe;
326         int busycount;
327         int busy_tonelength;
328         int busy_quietlength;
329         int historicnoise[DSP_HISTORY];
330         int historicsilence[DSP_HISTORY];
331         goertzel_state_t freqs[7];
332         int freqcount;
333         int gsamps;
334         int gsamp_size;
335         int progmode;
336         int tstate;
337         int tcount;
338         int digitmode;
339         int thinkdigit;
340         float genergy;
341         union {
342                 dtmf_detect_state_t dtmf;
343                 mf_detect_state_t mf;
344         } td;
345 };
346
347 static void ast_dtmf_detect_init (dtmf_detect_state_t *s)
348 {
349         int i;
350
351 #ifdef OLD_DSP_ROUTINES
352         s->hit1 = 
353         s->mhit = 
354         s->hit3 =
355         s->hit4 = 
356         s->hit2 = 0;
357 #else
358         s->hits[0] = s->hits[1] = s->hits[2] = 0;
359 #endif
360         for (i = 0;  i < 4;  i++) {
361                 goertzel_init (&s->row_out[i], dtmf_row[i], 102);
362                 goertzel_init (&s->col_out[i], dtmf_col[i], 102);
363 #ifdef OLD_DSP_ROUTINES
364                 goertzel_init (&s->row_out2nd[i], dtmf_row[i] * 2.0, 102);
365                 goertzel_init (&s->col_out2nd[i], dtmf_col[i] * 2.0, 102);
366 #endif  
367                 s->energy = 0.0;
368         }
369 #ifdef FAX_DETECT
370         /* Same for the fax dector */
371         goertzel_init (&s->fax_tone, fax_freq, 102);
372
373 #ifdef OLD_DSP_ROUTINES
374         /* Same for the fax dector 2nd harmonic */
375         goertzel_init (&s->fax_tone2nd, fax_freq * 2.0, 102);
376 #endif  
377 #endif /* FAX_DETECT */
378         s->current_sample = 0;
379         s->detected_digits = 0;
380         s->current_digits = 0;
381         memset(&s->digits, 0, sizeof(s->digits));
382         s->lost_digits = 0;
383         s->digits[0] = '\0';
384 }
385
386 static void ast_mf_detect_init (mf_detect_state_t *s)
387 {
388         int i;
389 #ifdef OLD_DSP_ROUTINES
390         s->hit1 = 
391         s->hit2 = 0;
392 #else   
393         s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
394 #endif
395         for (i = 0;  i < 6;  i++) {
396                 goertzel_init (&s->tone_out[i], mf_tones[i], 160);
397 #ifdef OLD_DSP_ROUTINES
398                 goertzel_init (&s->tone_out2nd[i], mf_tones[i] * 2.0, 160);
399                 s->energy = 0.0;
400 #endif
401         }
402         s->current_digits = 0;
403         memset(&s->digits, 0, sizeof(s->digits));
404         s->current_sample = 0;
405         s->detected_digits = 0;
406         s->lost_digits = 0;
407         s->digits[0] = '\0';
408         s->mhit = 0;
409 }
410
411 static int dtmf_detect (dtmf_detect_state_t *s, int16_t amp[], int samples, 
412                  int digitmode, int *writeback, int faxdetect)
413 {
414         float row_energy[4];
415         float col_energy[4];
416 #ifdef FAX_DETECT
417         float fax_energy;
418 #ifdef OLD_DSP_ROUTINES
419         float fax_energy_2nd;
420 #endif  
421 #endif /* FAX_DETECT */
422         float famp;
423         float v1;
424         int i;
425         int j;
426         int sample;
427         int best_row;
428         int best_col;
429         int hit;
430         int limit;
431
432         hit = 0;
433         for (sample = 0;  sample < samples;  sample = limit) {
434                 /* 102 is optimised to meet the DTMF specs. */
435                 if ((samples - sample) >= (102 - s->current_sample))
436                         limit = sample + (102 - s->current_sample);
437                 else
438                         limit = samples;
439 #if defined(USE_3DNOW)
440                 _dtmf_goertzel_update (s->row_out, amp + sample, limit - sample);
441                 _dtmf_goertzel_update (s->col_out, amp + sample, limit - sample);
442 #ifdef OLD_DSP_ROUTINES
443                 _dtmf_goertzel_update (s->row_out2nd, amp + sample, limit2 - sample);
444                 _dtmf_goertzel_update (s->col_out2nd, amp + sample, limit2 - sample);
445 #endif          
446                 /* XXX Need to fax detect for 3dnow too XXX */
447                 #warning "Fax Support Broken"
448 #else
449                 /* The following unrolled loop takes only 35% (rough estimate) of the 
450                    time of a rolled loop on the machine on which it was developed */
451                 for (j=sample;j<limit;j++) {
452                         famp = amp[j];
453                         s->energy += famp*famp;
454                         /* With GCC 2.95, the following unrolled code seems to take about 35%
455                            (rough estimate) as long as a neat little 0-3 loop */
456                         v1 = s->row_out[0].v2;
457                         s->row_out[0].v2 = s->row_out[0].v3;
458                         s->row_out[0].v3 = s->row_out[0].fac*s->row_out[0].v2 - v1 + famp;
459                         v1 = s->col_out[0].v2;
460                         s->col_out[0].v2 = s->col_out[0].v3;
461                         s->col_out[0].v3 = s->col_out[0].fac*s->col_out[0].v2 - v1 + famp;
462                         v1 = s->row_out[1].v2;
463                         s->row_out[1].v2 = s->row_out[1].v3;
464                         s->row_out[1].v3 = s->row_out[1].fac*s->row_out[1].v2 - v1 + famp;
465                         v1 = s->col_out[1].v2;
466                         s->col_out[1].v2 = s->col_out[1].v3;
467                         s->col_out[1].v3 = s->col_out[1].fac*s->col_out[1].v2 - v1 + famp;
468                         v1 = s->row_out[2].v2;
469                         s->row_out[2].v2 = s->row_out[2].v3;
470                         s->row_out[2].v3 = s->row_out[2].fac*s->row_out[2].v2 - v1 + famp;
471                         v1 = s->col_out[2].v2;
472                         s->col_out[2].v2 = s->col_out[2].v3;
473                         s->col_out[2].v3 = s->col_out[2].fac*s->col_out[2].v2 - v1 + famp;
474                         v1 = s->row_out[3].v2;
475                         s->row_out[3].v2 = s->row_out[3].v3;
476                         s->row_out[3].v3 = s->row_out[3].fac*s->row_out[3].v2 - v1 + famp;
477                         v1 = s->col_out[3].v2;
478                         s->col_out[3].v2 = s->col_out[3].v3;
479                         s->col_out[3].v3 = s->col_out[3].fac*s->col_out[3].v2 - v1 + famp;
480 #ifdef FAX_DETECT
481                         /* Update fax tone */
482                         v1 = s->fax_tone.v2;
483                         s->fax_tone.v2 = s->fax_tone.v3;
484                         s->fax_tone.v3 = s->fax_tone.fac*s->fax_tone.v2 - v1 + famp;
485 #endif /* FAX_DETECT */
486 #ifdef OLD_DSP_ROUTINES
487                         v1 = s->col_out2nd[0].v2;
488                         s->col_out2nd[0].v2 = s->col_out2nd[0].v3;
489                         s->col_out2nd[0].v3 = s->col_out2nd[0].fac*s->col_out2nd[0].v2 - v1 + famp;
490                         v1 = s->row_out2nd[0].v2;
491                         s->row_out2nd[0].v2 = s->row_out2nd[0].v3;
492                         s->row_out2nd[0].v3 = s->row_out2nd[0].fac*s->row_out2nd[0].v2 - v1 + famp;
493                         v1 = s->col_out2nd[1].v2;
494                         s->col_out2nd[1].v2 = s->col_out2nd[1].v3;
495                         s->col_out2nd[1].v3 = s->col_out2nd[1].fac*s->col_out2nd[1].v2 - v1 + famp;
496                         v1 = s->row_out2nd[1].v2;
497                         s->row_out2nd[1].v2 = s->row_out2nd[1].v3;
498                         s->row_out2nd[1].v3 = s->row_out2nd[1].fac*s->row_out2nd[1].v2 - v1 + famp;
499                         v1 = s->col_out2nd[2].v2;
500                         s->col_out2nd[2].v2 = s->col_out2nd[2].v3;
501                         s->col_out2nd[2].v3 = s->col_out2nd[2].fac*s->col_out2nd[2].v2 - v1 + famp;
502                         v1 = s->row_out2nd[2].v2;
503                         s->row_out2nd[2].v2 = s->row_out2nd[2].v3;
504                         s->row_out2nd[2].v3 = s->row_out2nd[2].fac*s->row_out2nd[2].v2 - v1 + famp;
505                         v1 = s->col_out2nd[3].v2;
506                         s->col_out2nd[3].v2 = s->col_out2nd[3].v3;
507                         s->col_out2nd[3].v3 = s->col_out2nd[3].fac*s->col_out2nd[3].v2 - v1 + famp;
508                         v1 = s->row_out2nd[3].v2;
509                         s->row_out2nd[3].v2 = s->row_out2nd[3].v3;
510                         s->row_out2nd[3].v3 = s->row_out2nd[3].fac*s->row_out2nd[3].v2 - v1 + famp;
511 #ifdef FAX_DETECT
512                         /* Update fax tone */            
513                         v1 = s->fax_tone.v2;
514                         s->fax_tone2nd.v2 = s->fax_tone2nd.v3;
515                         s->fax_tone2nd.v3 = s->fax_tone2nd.fac*s->fax_tone2nd.v2 - v1 + famp;
516 #endif /* FAX_DETECT */
517 #endif
518                 }
519 #endif
520                 s->current_sample += (limit - sample);
521                 if (s->current_sample < 102) {
522                         if (hit && !((digitmode & DSP_DIGITMODE_NOQUELCH))) {
523                                 /* If we had a hit last time, go ahead and clear this out since likely it
524                                    will be another hit */
525                                 for (i=sample;i<limit;i++) 
526                                         amp[i] = 0;
527                                 *writeback = 1;
528                         }
529                         continue;
530                 }
531 #ifdef FAX_DETECT
532                 /* Detect the fax energy, too */
533                 fax_energy = goertzel_result(&s->fax_tone);
534 #endif
535                 /* We are at the end of a DTMF detection block */
536                 /* Find the peak row and the peak column */
537                 row_energy[0] = goertzel_result (&s->row_out[0]);
538                 col_energy[0] = goertzel_result (&s->col_out[0]);
539
540                 for (best_row = best_col = 0, i = 1;  i < 4;  i++) {
541                         row_energy[i] = goertzel_result (&s->row_out[i]);
542                         if (row_energy[i] > row_energy[best_row])
543                                 best_row = i;
544                         col_energy[i] = goertzel_result (&s->col_out[i]);
545                         if (col_energy[i] > col_energy[best_col])
546                                 best_col = i;
547                 }
548                 hit = 0;
549                 /* Basic signal level test and the twist test */
550                 if (row_energy[best_row] >= DTMF_THRESHOLD && 
551                     col_energy[best_col] >= DTMF_THRESHOLD &&
552                     col_energy[best_col] < row_energy[best_row]*DTMF_REVERSE_TWIST &&
553                     col_energy[best_col]*DTMF_NORMAL_TWIST > row_energy[best_row]) {
554                         /* Relative peak test */
555                         for (i = 0;  i < 4;  i++) {
556                                 if ((i != best_col &&
557                                     col_energy[i]*DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
558                                     (i != best_row 
559                                      && row_energy[i]*DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
560                                         break;
561                                 }
562                         }
563 #ifdef OLD_DSP_ROUTINES
564                         /* ... and second harmonic test */
565                         if (i >= 4 && 
566                             (row_energy[best_row] + col_energy[best_col]) > 42.0*s->energy &&
567                             goertzel_result(&s->col_out2nd[best_col])*DTMF_2ND_HARMONIC_COL < col_energy[best_col]
568                             && goertzel_result(&s->row_out2nd[best_row])*DTMF_2ND_HARMONIC_ROW < row_energy[best_row]) {
569 #else
570                         /* ... and fraction of total energy test */
571                         if (i >= 4 &&
572                             (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY*s->energy) {
573 #endif
574                                 /* Got a hit */
575                                 hit = dtmf_positions[(best_row << 2) + best_col];
576                                 if (!(digitmode & DSP_DIGITMODE_NOQUELCH)) {
577                                         /* Zero out frame data if this is part DTMF */
578                                         for (i=sample;i<limit;i++) 
579                                                 amp[i] = 0;
580                                         *writeback = 1;
581                                 }
582                                 /* Look for two successive similar results */
583                                 /* The logic in the next test is:
584                                    We need two successive identical clean detects, with
585                                    something different preceeding it. This can work with
586                                    back to back differing digits. More importantly, it
587                                    can work with nasty phones that give a very wobbly start
588                                    to a digit */
589 #ifdef OLD_DSP_ROUTINES
590                                 if (hit == s->hit3  &&  s->hit3 != s->hit2) {
591                                         s->mhit = hit;
592                                         s->digit_hits[(best_row << 2) + best_col]++;
593                                         s->detected_digits++;
594                                         if (s->current_digits < MAX_DTMF_DIGITS) {
595                                                 s->digits[s->current_digits++] = hit;
596                                                 s->digits[s->current_digits] = '\0';
597                                         } else {
598                                                 s->lost_digits++;
599                                         }
600                                 }
601 #else                           
602                                 if (hit == s->hits[2]  &&  hit != s->hits[1]  &&  hit != s->hits[0]) {
603                                         s->mhit = hit;
604                                         s->digit_hits[(best_row << 2) + best_col]++;
605                                         s->detected_digits++;
606                                         if (s->current_digits < MAX_DTMF_DIGITS) {
607                                                 s->digits[s->current_digits++] = hit;
608                                                 s->digits[s->current_digits] = '\0';
609                                         } else {
610                                                 s->lost_digits++;
611                                         }
612                                 }
613 #endif
614                         }
615                 } 
616 #ifdef FAX_DETECT
617                 if (!hit && (fax_energy >= FAX_THRESHOLD) && 
618                         (fax_energy >= DTMF_TO_TOTAL_ENERGY*s->energy) &&
619                         (faxdetect)) {
620 #if 0
621                         printf("Fax energy/Second Harmonic: %f\n", fax_energy);
622 #endif                                  
623                         /* XXX Probably need better checking than just this the energy XXX */
624                         hit = 'f';
625                         s->fax_hits++;
626                 } else {
627                         if (s->fax_hits > 5) {
628                                 hit = 'f';
629                                 s->mhit = 'f';
630                                 s->detected_digits++;
631                                 if (s->current_digits < MAX_DTMF_DIGITS) {
632                                         s->digits[s->current_digits++] = hit;
633                                         s->digits[s->current_digits] = '\0';
634                                 } else {
635                                         s->lost_digits++;
636                                 }
637                         }
638                         s->fax_hits = 0;
639                 }
640 #endif /* FAX_DETECT */
641 #ifdef OLD_DSP_ROUTINES
642                 s->hit1 = s->hit2;
643                 s->hit2 = s->hit3;
644                 s->hit3 = hit;
645 #else
646                 s->hits[0] = s->hits[1];
647                 s->hits[1] = s->hits[2];
648                 s->hits[2] = hit;
649 #endif          
650                 /* Reinitialise the detector for the next block */
651                 for (i = 0;  i < 4;  i++) {
652                         goertzel_reset(&s->row_out[i]);
653                         goertzel_reset(&s->col_out[i]);
654 #ifdef OLD_DSP_ROUTINES
655                         goertzel_reset(&s->row_out2nd[i]);
656                         goertzel_reset(&s->col_out2nd[i]);
657 #endif                  
658                 }
659 #ifdef FAX_DETECT
660                 goertzel_reset (&s->fax_tone);
661 #ifdef OLD_DSP_ROUTINES
662                 goertzel_reset (&s->fax_tone2nd);
663 #endif                  
664 #endif
665                 s->energy = 0.0;
666                 s->current_sample = 0;
667         }
668         if ((!s->mhit) || (s->mhit != hit)) {
669                 s->mhit = 0;
670                 return(0);
671         }
672         return (hit);
673 }
674
675 /* MF goertzel size */
676 #ifdef OLD_DSP_ROUTINES
677 #define MF_GSIZE 160
678 #else
679 #define MF_GSIZE 120
680 #endif
681
682 static int mf_detect (mf_detect_state_t *s, int16_t amp[],
683                  int samples, int digitmode, int *writeback)
684 {
685 #ifdef OLD_DSP_ROUTINES
686         float tone_energy[6];
687         int best1;
688         int best2;
689         float max;
690         int sofarsogood;
691 #else
692         float energy[6];
693         int best;
694         int second_best;
695 #endif
696         float famp;
697         float v1;
698         int i;
699         int j;
700         int sample;
701         int hit;
702         int limit;
703
704         hit = 0;
705         for (sample = 0;  sample < samples;  sample = limit) {
706                 /* 80 is optimised to meet the MF specs. */
707                 if ((samples - sample) >= (MF_GSIZE - s->current_sample))
708                         limit = sample + (MF_GSIZE - s->current_sample);
709                 else
710                         limit = samples;
711 #if defined(USE_3DNOW)
712                 _dtmf_goertzel_update (s->row_out, amp + sample, limit - sample);
713                 _dtmf_goertzel_update (s->col_out, amp + sample, limit - sample);
714 #ifdef OLD_DSP_ROUTINES
715                 _dtmf_goertzel_update (s->row_out2nd, amp + sample, limit2 - sample);
716                 _dtmf_goertzel_update (s->col_out2nd, amp + sample, limit2 - sample);
717 #endif
718                 /* XXX Need to fax detect for 3dnow too XXX */
719                 #warning "Fax Support Broken"
720 #else
721                 /* The following unrolled loop takes only 35% (rough estimate) of the 
722                    time of a rolled loop on the machine on which it was developed */
723                 for (j = sample;  j < limit;  j++) {
724                         famp = amp[j];
725 #ifdef OLD_DSP_ROUTINES
726                         s->energy += famp*famp;
727 #endif
728                         /* With GCC 2.95, the following unrolled code seems to take about 35%
729                            (rough estimate) as long as a neat little 0-3 loop */
730                         v1 = s->tone_out[0].v2;
731                         s->tone_out[0].v2 = s->tone_out[0].v3;
732                         s->tone_out[0].v3 = s->tone_out[0].fac*s->tone_out[0].v2 - v1 + famp;
733                         v1 = s->tone_out[1].v2;
734                         s->tone_out[1].v2 = s->tone_out[1].v3;
735                         s->tone_out[1].v3 = s->tone_out[1].fac*s->tone_out[1].v2 - v1 + famp;
736                         v1 = s->tone_out[2].v2;
737                         s->tone_out[2].v2 = s->tone_out[2].v3;
738                         s->tone_out[2].v3 = s->tone_out[2].fac*s->tone_out[2].v2 - v1 + famp;
739                         v1 = s->tone_out[3].v2;
740                         s->tone_out[3].v2 = s->tone_out[3].v3;
741                         s->tone_out[3].v3 = s->tone_out[3].fac*s->tone_out[3].v2 - v1 + famp;
742                         v1 = s->tone_out[4].v2;
743                         s->tone_out[4].v2 = s->tone_out[4].v3;
744                         s->tone_out[4].v3 = s->tone_out[4].fac*s->tone_out[4].v2 - v1 + famp;
745                         v1 = s->tone_out[5].v2;
746                         s->tone_out[5].v2 = s->tone_out[5].v3;
747                         s->tone_out[5].v3 = s->tone_out[5].fac*s->tone_out[5].v2 - v1 + famp;
748 #ifdef OLD_DSP_ROUTINES
749                         v1 = s->tone_out2nd[0].v2;
750                         s->tone_out2nd[0].v2 = s->tone_out2nd[0].v3;
751                         s->tone_out2nd[0].v3 = s->tone_out2nd[0].fac*s->tone_out2nd[0].v2 - v1 + famp;
752                         v1 = s->tone_out2nd[1].v2;
753                         s->tone_out2nd[1].v2 = s->tone_out2nd[1].v3;
754                         s->tone_out2nd[1].v3 = s->tone_out2nd[1].fac*s->tone_out2nd[1].v2 - v1 + famp;
755                         v1 = s->tone_out2nd[2].v2;
756                         s->tone_out2nd[2].v2 = s->tone_out2nd[2].v3;
757                         s->tone_out2nd[2].v3 = s->tone_out2nd[2].fac*s->tone_out2nd[2].v2 - v1 + famp;
758                         v1 = s->tone_out2nd[3].v2;
759                         s->tone_out2nd[3].v2 = s->tone_out2nd[3].v3;
760                         s->tone_out2nd[3].v3 = s->tone_out2nd[3].fac*s->tone_out2nd[3].v2 - v1 + famp;
761                         v1 = s->tone_out2nd[4].v2;
762                         s->tone_out2nd[4].v2 = s->tone_out2nd[4].v3;
763                         s->tone_out2nd[4].v3 = s->tone_out2nd[4].fac*s->tone_out2nd[2].v2 - v1 + famp;
764                         v1 = s->tone_out2nd[3].v2;
765                         s->tone_out2nd[5].v2 = s->tone_out2nd[6].v3;
766                         s->tone_out2nd[5].v3 = s->tone_out2nd[6].fac*s->tone_out2nd[3].v2 - v1 + famp;
767 #endif
768                 }
769 #endif
770                 s->current_sample += (limit - sample);
771                 if (s->current_sample < MF_GSIZE) {
772                         if (hit && !((digitmode & DSP_DIGITMODE_NOQUELCH))) {
773                                 /* If we had a hit last time, go ahead and clear this out since likely it
774                                    will be another hit */
775                                 for (i=sample;i<limit;i++) 
776                                         amp[i] = 0;
777                                 *writeback = 1;
778                         }
779                         continue;
780                 }
781 #ifdef OLD_DSP_ROUTINES         
782                 /* We're at the end of an MF detection block.  Go ahead and calculate
783                    all the energies. */
784                 for (i=0;i<6;i++) {
785                         tone_energy[i] = goertzel_result(&s->tone_out[i]);
786                 }
787                 /* Find highest */
788                 best1 = 0;
789                 max = tone_energy[0];
790                 for (i=1;i<6;i++) {
791                         if (tone_energy[i] > max) {
792                                 max = tone_energy[i];
793                                 best1 = i;
794                         }
795                 }
796
797                 /* Find 2nd highest */
798                 if (best1) {
799                         max = tone_energy[0];
800                         best2 = 0;
801                 } else {
802                         max = tone_energy[1];
803                         best2 = 1;
804                 }
805
806                 for (i=0;i<6;i++) {
807                         if (i == best1) continue;
808                         if (tone_energy[i] > max) {
809                                 max = tone_energy[i];
810                                 best2 = i;
811                         }
812                 }
813                 hit = 0;
814                 if (best1 != best2) 
815                         sofarsogood=1;
816                 else 
817                         sofarsogood=0;
818                 /* Check for relative energies */
819                 for (i=0;i<6;i++) {
820                         if (i == best1) 
821                                 continue;
822                         if (i == best2) 
823                                 continue;
824                         if (tone_energy[best1] < tone_energy[i] * MF_RELATIVE_PEAK) {
825                                 sofarsogood = 0;
826                                 break;
827                         }
828                         if (tone_energy[best2] < tone_energy[i] * MF_RELATIVE_PEAK) {
829                                 sofarsogood = 0;
830                                 break;
831                         }
832                 }
833                 
834                 if (sofarsogood) {
835                         /* Check for 2nd harmonic */
836                         if (goertzel_result(&s->tone_out2nd[best1]) * MF_2ND_HARMONIC > tone_energy[best1]) 
837                                 sofarsogood = 0;
838                         else if (goertzel_result(&s->tone_out2nd[best2]) * MF_2ND_HARMONIC > tone_energy[best2])
839                                 sofarsogood = 0;
840                 }
841                 if (sofarsogood) {
842                         hit = mf_hit[best1][best2];
843                         if (!(digitmode & DSP_DIGITMODE_NOQUELCH)) {
844                                 /* Zero out frame data if this is part DTMF */
845                                 for (i=sample;i<limit;i++) 
846                                         amp[i] = 0;
847                                 *writeback = 1;
848                         }
849                         /* Look for two consecutive clean hits */
850                         if ((hit == s->hit3) && (s->hit3 != s->hit2)) {
851                                 s->mhit = hit;
852                                 s->detected_digits++;
853                                 if (s->current_digits < MAX_DTMF_DIGITS - 2) {
854                                         s->digits[s->current_digits++] = hit;
855                                         s->digits[s->current_digits] = '\0';
856                                 } else {
857                                         s->lost_digits++;
858                                 }
859                         }
860                 }
861                 
862                 s->hit1 = s->hit2;
863                 s->hit2 = s->hit3;
864                 s->hit3 = hit;
865                 /* Reinitialise the detector for the next block */
866                 for (i = 0;  i < 6;  i++) {
867                         goertzel_reset(&s->tone_out[i]);
868                         goertzel_reset(&s->tone_out2nd[i]);
869                 }
870                 s->energy = 0.0;
871                 s->current_sample = 0;
872         }
873 #else
874                 /* We're at the end of an MF detection block.  */
875                 /* Find the two highest energies. The spec says to look for
876                    two tones and two tones only. Taking this literally -ie
877                    only two tones pass the minimum threshold - doesn't work
878                    well. The sinc function mess, due to rectangular windowing
879                    ensure that! Find the two highest energies and ensure they
880                    are considerably stronger than any of the others. */
881                 energy[0] = goertzel_result(&s->tone_out[0]);
882                 energy[1] = goertzel_result(&s->tone_out[1]);
883                 if (energy[0] > energy[1]) {
884                         best = 0;
885                         second_best = 1;
886                 } else {
887                         best = 1;
888                         second_best = 0;
889                 }
890                 /*endif*/
891                 for (i=2;i<6;i++) {
892                         energy[i] = goertzel_result(&s->tone_out[i]);
893                         if (energy[i] >= energy[best]) {
894                                 second_best = best;
895                                 best = i;
896                         } else if (energy[i] >= energy[second_best]) {
897                                 second_best = i;
898                         }
899                 }
900                 /* Basic signal level and twist tests */
901                 hit = 0;
902                 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
903                     && energy[best] < energy[second_best]*BELL_MF_TWIST
904                     && energy[best]*BELL_MF_TWIST > energy[second_best]) {
905                         /* Relative peak test */
906                         hit = -1;
907                         for (i=0;i<6;i++) {
908                                 if (i != best && i != second_best) {
909                                         if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
910                                                 /* The best two are not clearly the best */
911                                                 hit = 0;
912                                                 break;
913                                         }
914                                 }
915                         }
916                 }
917                 if (hit) {
918                         /* Get the values into ascending order */
919                         if (second_best < best) {
920                                 i = best;
921                                 best = second_best;
922                                 second_best = i;
923                         }
924                         best = best*5 + second_best - 1;
925                         hit = bell_mf_positions[best];
926                         /* Look for two successive similar results */
927                         /* The logic in the next test is:
928                            For KP we need 4 successive identical clean detects, with
929                            two blocks of something different preceeding it. For anything
930                            else we need two successive identical clean detects, with
931                            two blocks of something different preceeding it. */
932                         if (hit == s->hits[4] && hit == s->hits[3] &&
933                            ((hit != '*' && hit != s->hits[2] && hit != s->hits[1])||
934                             (hit == '*' && hit == s->hits[2] && hit != s->hits[1] && 
935                             hit != s->hits[0]))) {
936                                 s->detected_digits++;
937                                 if (s->current_digits < MAX_DTMF_DIGITS) {
938                                         s->digits[s->current_digits++] = hit;
939                                         s->digits[s->current_digits] = '\0';
940                                 } else {
941                                         s->lost_digits++;
942                                 }
943                         }
944                 } else {
945                         hit = 0;
946                 }
947                 s->hits[0] = s->hits[1];
948                 s->hits[1] = s->hits[2];
949                 s->hits[2] = s->hits[3];
950                 s->hits[3] = s->hits[4];
951                 s->hits[4] = hit;
952                 /* Reinitialise the detector for the next block */
953                 for (i = 0;  i < 6;  i++)
954                         goertzel_reset(&s->tone_out[i]);
955                 s->current_sample = 0;
956         }
957 #endif  
958         if ((!s->mhit) || (s->mhit != hit)) {
959                 s->mhit = 0;
960                 return(0);
961         }
962         return (hit);
963 }
964
965 static int __ast_dsp_digitdetect(struct ast_dsp *dsp, short *s, int len, int *writeback)
966 {
967         int res;
968         
969         if (dsp->digitmode & DSP_DIGITMODE_MF)
970                 res = mf_detect(&dsp->td.mf, s, len, dsp->digitmode & DSP_DIGITMODE_RELAXDTMF, writeback);
971         else
972                 res = dtmf_detect(&dsp->td.dtmf, s, len, dsp->digitmode & DSP_DIGITMODE_RELAXDTMF, writeback, dsp->features & DSP_FEATURE_FAX_DETECT);
973         return res;
974 }
975
976 int ast_dsp_digitdetect(struct ast_dsp *dsp, struct ast_frame *inf)
977 {
978         short *s;
979         int len;
980         int ign=0;
981
982         if (inf->frametype != AST_FRAME_VOICE) {
983                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
984                 return 0;
985         }
986         if (inf->subclass != AST_FORMAT_SLINEAR) {
987                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
988                 return 0;
989         }
990         s = inf->data;
991         len = inf->datalen / 2;
992         return __ast_dsp_digitdetect(dsp, s, len, &ign);
993 }
994
995 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
996 {
997         /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
998         /* Make sure absolute levels are high enough */
999         if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH))
1000                 return 0;
1001         /* Amplify ignored stuff */
1002         i2 *= TONE_THRESH;
1003         i1 *= TONE_THRESH;
1004         e *= TONE_THRESH;
1005         /* Check first tone */
1006         if ((p1 < i1) || (p1 < i2) || (p1 < e))
1007                 return 0;
1008         /* And second */
1009         if ((p2 < i1) || (p2 < i2) || (p2 < e))
1010                 return 0;
1011         /* Guess it's there... */
1012         return 1;
1013 }
1014
1015 int ast_dsp_getdigits (struct ast_dsp *dsp, char *buf, int max)
1016 {
1017         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1018                 if (max > dsp->td.mf.current_digits)
1019                         max = dsp->td.mf.current_digits;
1020                 if (max > 0) {
1021                         memcpy(buf, dsp->td.mf.digits, max);
1022                         memmove(dsp->td.mf.digits, dsp->td.mf.digits + max, dsp->td.mf.current_digits - max);
1023                         dsp->td.mf.current_digits -= max;
1024                 }
1025                 buf[max] = '\0';
1026                 return  max;
1027         } else {
1028                 if (max > dsp->td.dtmf.current_digits)
1029                         max = dsp->td.dtmf.current_digits;
1030                 if (max > 0) {
1031                         memcpy (buf, dsp->td.dtmf.digits, max);
1032                         memmove (dsp->td.dtmf.digits, dsp->td.dtmf.digits + max, dsp->td.dtmf.current_digits - max);
1033                         dsp->td.dtmf.current_digits -= max;
1034                 }
1035                 buf[max] = '\0';
1036                 return  max;
1037         }
1038 }
1039
1040 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
1041 {
1042         int x;
1043         int y;
1044         int pass;
1045         int newstate = DSP_TONE_STATE_SILENCE;
1046         int res = 0;
1047         while(len) {
1048                 /* Take the lesser of the number of samples we need and what we have */
1049                 pass = len;
1050                 if (pass > dsp->gsamp_size - dsp->gsamps) 
1051                         pass = dsp->gsamp_size - dsp->gsamps;
1052                 for (x=0;x<pass;x++) {
1053                         for (y=0;y<dsp->freqcount;y++) 
1054                                 goertzel_sample(&dsp->freqs[y], s[x]);
1055                         dsp->genergy += s[x] * s[x];
1056                 }
1057                 s += pass;
1058                 dsp->gsamps += pass;
1059                 len -= pass;
1060                 if (dsp->gsamps == dsp->gsamp_size) {
1061                         float hz[7];
1062                         for (y=0;y<7;y++)
1063                                 hz[y] = goertzel_result(&dsp->freqs[y]);
1064 #if 0
1065                         printf("\n350:     425:     440:     480:     620:     950:     1400:    1800:    Energy:   \n");
1066                         printf("%.2e %.2e %.2e %.2e %.2e %.2e %.2e %.2e %.2e\n", 
1067                                 hz[HZ_350], hz[HZ_425], hz[HZ_440], hz[HZ_480], hz[HZ_620], hz[HZ_950], hz[HZ_1400], hz[HZ_1800], dsp->genergy);
1068 #endif
1069                         switch(dsp->progmode) {
1070                         case PROG_MODE_NA:
1071                                 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
1072                                         newstate = DSP_TONE_STATE_BUSY;
1073                                 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
1074                                         newstate = DSP_TONE_STATE_RINGING;
1075                                 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
1076                                         newstate = DSP_TONE_STATE_DIALTONE;
1077                                 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
1078                                         newstate = DSP_TONE_STATE_SPECIAL1;
1079                                 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
1080                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL1)
1081                                                 newstate = DSP_TONE_STATE_SPECIAL2;
1082                                 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
1083                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL2)
1084                                                 newstate = DSP_TONE_STATE_SPECIAL3;
1085                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1086                                         newstate = DSP_TONE_STATE_TALKING;
1087                                 } else
1088                                         newstate = DSP_TONE_STATE_SILENCE;
1089                                 break;
1090                         case PROG_MODE_CR:
1091                                 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
1092                                         newstate = DSP_TONE_STATE_RINGING;
1093                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1094                                         newstate = DSP_TONE_STATE_TALKING;
1095                                 } else
1096                                         newstate = DSP_TONE_STATE_SILENCE;
1097                                 break;
1098                         case PROG_MODE_UK:
1099                                 if (hz[HZ_400] > TONE_MIN_THRESH * TONE_THRESH) {
1100                                         newstate = DSP_TONE_STATE_HUNGUP;
1101                                 }
1102                                 break;
1103                         default:
1104                                 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
1105                         }
1106                         if (newstate == dsp->tstate) {
1107                                 dsp->tcount++;
1108                                 if (dsp->ringtimeout)
1109                                         dsp->ringtimeout++;
1110                                 switch (dsp->tstate) {
1111                                         case DSP_TONE_STATE_RINGING:
1112                                                 if ((dsp->features & DSP_PROGRESS_RINGING) &&
1113                                                     (dsp->tcount==THRESH_RING)) {
1114                                                         res = AST_CONTROL_RINGING;
1115                                                         dsp->ringtimeout= 1;
1116                                                 }
1117                                                 break;
1118                                         case DSP_TONE_STATE_BUSY:
1119                                                 if ((dsp->features & DSP_PROGRESS_BUSY) &&
1120                                                     (dsp->tcount==THRESH_BUSY)) {
1121                                                         res = AST_CONTROL_BUSY;
1122                                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1123                                                 }
1124                                                 break;
1125                                         case DSP_TONE_STATE_TALKING:
1126                                                 if ((dsp->features & DSP_PROGRESS_TALK) &&
1127                                                     (dsp->tcount==THRESH_TALK)) {
1128                                                         res = AST_CONTROL_ANSWER;
1129                                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1130                                                 }
1131                                                 break;
1132                                         case DSP_TONE_STATE_SPECIAL3:
1133                                                 if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
1134                                                     (dsp->tcount==THRESH_CONGESTION)) {
1135                                                         res = AST_CONTROL_CONGESTION;
1136                                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1137                                                 }
1138                                                 break;
1139                                         case DSP_TONE_STATE_HUNGUP:
1140                                                 if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
1141                                                     (dsp->tcount==THRESH_HANGUP)) {
1142                                                         res = AST_CONTROL_HANGUP;
1143                                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1144                                                 }
1145                                                 break;
1146                                 }
1147                                 if (dsp->ringtimeout==THRESH_RING2ANSWER) {
1148 #if 0
1149                                         ast_log(LOG_NOTICE, "Consider call as answered because of timeout after last ring\n");
1150 #endif
1151                                         res = AST_CONTROL_ANSWER;
1152                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1153                                 }
1154                         } else {
1155 #if 0
1156                                 ast_log(LOG_NOTICE, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
1157                                 ast_log(LOG_NOTICE, "Start state %d\n", newstate);
1158 #endif
1159                                 dsp->tstate = newstate;
1160                                 dsp->tcount = 1;
1161                         }
1162                         
1163                         /* Reset goertzel */                                            
1164                         for (x=0;x<7;x++)
1165                                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1166                         dsp->gsamps = 0;
1167                         dsp->genergy = 0.0;
1168                 }
1169         }
1170 #if 0
1171         if (res)
1172                 printf("Returning %d\n", res);
1173 #endif          
1174         return res;
1175 }
1176
1177 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1178 {
1179         if (inf->frametype != AST_FRAME_VOICE) {
1180                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1181                 return 0;
1182         }
1183         if (inf->subclass != AST_FORMAT_SLINEAR) {
1184                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1185                 return 0;
1186         }
1187         return __ast_dsp_call_progress(dsp, inf->data, inf->datalen / 2);
1188 }
1189
1190 static int __ast_dsp_silence(struct ast_dsp *dsp, short *s, int len, int *totalsilence)
1191 {
1192         int accum;
1193         int x;
1194         int res = 0;
1195
1196         if (!len)
1197                 return 0;
1198         accum = 0;
1199         for (x=0;x<len; x++) 
1200                 accum += abs(s[x]);
1201         accum /= len;
1202         if (accum < dsp->threshold) {
1203                 /* Silent */
1204                 dsp->totalsilence += len/8;
1205                 if (dsp->totalnoise) {
1206                         /* Move and save history */
1207                         memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount +1, dsp->busycount*sizeof(dsp->historicnoise[0]));
1208                         dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1209 /* we don't want to check for busydetect that frequently */
1210 #if 0
1211                         dsp->busymaybe = 1;
1212 #endif
1213                 }
1214                 dsp->totalnoise = 0;
1215                 res = 1;
1216         } else {
1217                 /* Not silent */
1218                 dsp->totalnoise += len/8;
1219                 if (dsp->totalsilence) {
1220                         int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1221                         int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1222                         /* Move and save history */
1223                         memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount*sizeof(dsp->historicsilence[0]));
1224                         dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1225                         /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1226                         if (silence1 < silence2) {
1227                                 if (silence1 + silence1*BUSY_PERCENT/100 >= silence2)
1228                                         dsp->busymaybe = 1;
1229                                 else 
1230                                         dsp->busymaybe = 0;
1231                         } else {
1232                                 if (silence1 - silence1*BUSY_PERCENT/100 <= silence2)
1233                                         dsp->busymaybe = 1;
1234                                 else 
1235                                         dsp->busymaybe = 0;
1236                         }
1237                 }
1238                 dsp->totalsilence = 0;
1239         }
1240         if (totalsilence)
1241                 *totalsilence = dsp->totalsilence;
1242         return res;
1243 }
1244
1245 #ifdef BUSYDETECT_MARTIN
1246 int ast_dsp_busydetect(struct ast_dsp *dsp)
1247 {
1248         int res = 0, x;
1249 #ifndef BUSYDETECT_TONEONLY
1250         int avgsilence = 0, hitsilence = 0;
1251 #endif
1252         int avgtone = 0, hittone = 0;
1253         if (!dsp->busymaybe)
1254                 return res;
1255         for (x=DSP_HISTORY - dsp->busycount;x<DSP_HISTORY;x++) {
1256 #ifndef BUSYDETECT_TONEONLY
1257                 avgsilence += dsp->historicsilence[x];
1258 #endif
1259                 avgtone += dsp->historicnoise[x];
1260         }
1261 #ifndef BUSYDETECT_TONEONLY
1262         avgsilence /= dsp->busycount;
1263 #endif
1264         avgtone /= dsp->busycount;
1265         for (x=DSP_HISTORY - dsp->busycount;x<DSP_HISTORY;x++) {
1266 #ifndef BUSYDETECT_TONEONLY
1267                 if (avgsilence > dsp->historicsilence[x]) {
1268                         if (avgsilence - (avgsilence*BUSY_PERCENT/100) <= dsp->historicsilence[x])
1269                                 hitsilence++;
1270                 } else {
1271                         if (avgsilence + (avgsilence*BUSY_PERCENT/100) >= dsp->historicsilence[x])
1272                                 hitsilence++;
1273                 }
1274 #endif
1275                 if (avgtone > dsp->historicnoise[x]) {
1276                         if (avgtone - (avgtone*BUSY_PERCENT/100) <= dsp->historicnoise[x])
1277                                 hittone++;
1278                 } else {
1279                         if (avgtone + (avgtone*BUSY_PERCENT/100) >= dsp->historicnoise[x])
1280                                 hittone++;
1281                 }
1282         }
1283 #ifndef BUSYDETECT_TONEONLY
1284         if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) && 
1285             (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) && 
1286             (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1287 #else
1288         if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1289 #endif
1290 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1291 #ifdef BUSYDETECT_TONEONLY
1292 #error You cant use BUSYDETECT_TONEONLY together with BUSYDETECT_COMPARE_TONE_AND_SILENCE
1293 #endif
1294                 if (avgtone > avgsilence) {
1295                         if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence)
1296                                 res = 1;
1297                 } else {
1298                         if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence)
1299                                 res = 1;
1300                 }
1301 #else
1302                 res = 1;
1303 #endif
1304         }
1305         /* If we know the expected busy tone length, check we are in the range */
1306         if (res && (dsp->busy_tonelength > 0)) {
1307                 if (abs(avgtone - dsp->busy_tonelength) > (dsp->busy_tonelength*BUSY_PAT_PERCENT/100)) {
1308 #if 0
1309                         ast_log(LOG_NOTICE, "busy detector: avgtone of %d not close enough to desired %d\n",
1310                                                 avgtone, dsp->busy_tonelength);
1311 #endif
1312                         res = 0;
1313                 }
1314         }
1315         /* If we know the expected busy tone silent-period length, check we are in the range */
1316         if (res && (dsp->busy_quietlength > 0)) {
1317                 if (abs(avgsilence - dsp->busy_quietlength) > (dsp->busy_quietlength*BUSY_PAT_PERCENT/100)) {
1318 #if 0
1319                         ast_log(LOG_NOTICE, "busy detector: avgsilence of %d not close enough to desired %d\n",
1320                                                 avgsilence, dsp->busy_quietlength);
1321 #endif
1322                         res = 0;
1323                 }
1324         }
1325 #if 1
1326         if (res)
1327                 ast_log(LOG_DEBUG, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1328 #endif
1329         return res;
1330 }
1331 #endif
1332
1333 #ifdef BUSYDETECT
1334 int ast_dsp_busydetect(struct ast_dsp *dsp)
1335 {
1336         int x;
1337         int res = 0;
1338         int max, min;
1339
1340 #if 0
1341         if (dsp->busy_hits > 5);
1342         return 0;
1343 #endif
1344         if (dsp->busymaybe) {
1345 #if 0
1346                 printf("Maybe busy!\n");
1347 #endif          
1348                 dsp->busymaybe = 0;
1349                 min = 9999;
1350                 max = 0;
1351                 for (x=DSP_HISTORY - dsp->busycount;x<DSP_HISTORY;x++) {
1352 #if 0
1353                         printf("Silence: %d, Noise: %d\n", dsp->historicsilence[x], dsp->historicnoise[x]);
1354 #endif                  
1355                         if (dsp->historicsilence[x] < min)
1356                                 min = dsp->historicsilence[x];
1357                         if (dsp->historicnoise[x] < min)
1358                                 min = dsp->historicnoise[x];
1359                         if (dsp->historicsilence[x] > max)
1360                                 max = dsp->historicsilence[x];
1361                         if (dsp->historicnoise[x] > max)
1362                                 max = dsp->historicnoise[x];
1363                 }
1364                 if ((max - min < BUSY_THRESHOLD) && (max < BUSY_MAX) && (min > BUSY_MIN)) {
1365 #if 0
1366                         printf("Busy!\n");
1367 #endif                  
1368                         res = 1;
1369                 }
1370 #if 0
1371                 printf("Min: %d, max: %d\n", min, max);
1372 #endif          
1373         }
1374         return res;
1375 }
1376 #endif
1377
1378 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1379 {
1380         short *s;
1381         int len;
1382         
1383         if (f->frametype != AST_FRAME_VOICE) {
1384                 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1385                 return 0;
1386         }
1387         if (f->subclass != AST_FORMAT_SLINEAR) {
1388                 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear frames :(\n");
1389                 return 0;
1390         }
1391         s = f->data;
1392         len = f->datalen/2;
1393         return __ast_dsp_silence(dsp, s, len, totalsilence);
1394 }
1395
1396 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1397 {
1398         int silence;
1399         int res;
1400         int digit;
1401         int x;
1402         short *shortdata;
1403         unsigned char *odata;
1404         int len;
1405         int writeback = 0;
1406
1407 #define FIX_INF(inf) do { \
1408                 if (writeback) { \
1409                         switch(inf->subclass) { \
1410                         case AST_FORMAT_SLINEAR: \
1411                                 break; \
1412                         case AST_FORMAT_ULAW: \
1413                                 for (x=0;x<len;x++) \
1414                                         odata[x] = AST_LIN2MU((unsigned short)shortdata[x]); \
1415                                 break; \
1416                         case AST_FORMAT_ALAW: \
1417                                 for (x=0;x<len;x++) \
1418                                         odata[x] = AST_LIN2A((unsigned short)shortdata[x]); \
1419                                 break; \
1420                         } \
1421                 } \
1422         } while(0) 
1423
1424         if (!af)
1425                 return NULL;
1426         if (af->frametype != AST_FRAME_VOICE)
1427                 return af;
1428         odata = af->data;
1429         len = af->datalen;
1430         /* Make sure we have short data */
1431         switch(af->subclass) {
1432         case AST_FORMAT_SLINEAR:
1433                 shortdata = af->data;
1434                 len = af->datalen / 2;
1435                 break;
1436         case AST_FORMAT_ULAW:
1437                 shortdata = alloca(af->datalen * 2);
1438                 if (!shortdata) {
1439                         ast_log(LOG_WARNING, "Unable to allocate stack space for data: %s\n", strerror(errno));
1440                         return af;
1441                 }
1442                 for (x=0;x<len;x++) 
1443                         shortdata[x] = AST_MULAW(odata[x]);
1444                 break;
1445         case AST_FORMAT_ALAW:
1446                 shortdata = alloca(af->datalen * 2);
1447                 if (!shortdata) {
1448                         ast_log(LOG_WARNING, "Unable to allocate stack space for data: %s\n", strerror(errno));
1449                         return af;
1450                 }
1451                 for (x=0;x<len;x++) 
1452                         shortdata[x] = AST_ALAW(odata[x]);
1453                 break;
1454         default:
1455                 ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(af->subclass));
1456                 return af;
1457         }
1458         silence = __ast_dsp_silence(dsp, shortdata, len, NULL);
1459         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1460                 memset(&dsp->f, 0, sizeof(dsp->f));
1461                 dsp->f.frametype = AST_FRAME_NULL;
1462                 return &dsp->f;
1463         }
1464         if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1465                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1466                 memset(&dsp->f, 0, sizeof(dsp->f));
1467                 dsp->f.frametype = AST_FRAME_CONTROL;
1468                 dsp->f.subclass = AST_CONTROL_BUSY;
1469                 ast_log(LOG_DEBUG, "Requesting Hangup because the busy tone was detected on channel %s\n", chan->name);
1470                 return &dsp->f;
1471         }
1472         if ((dsp->features & DSP_FEATURE_DTMF_DETECT)) {
1473                 digit = __ast_dsp_digitdetect(dsp, shortdata, len, &writeback);
1474 #if 0
1475                 if (digit)
1476                         printf("Performing digit detection returned %d, digitmode is %d\n", digit, dsp->digitmode);
1477 #endif                  
1478                 if (dsp->digitmode & (DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX)) {
1479                         if (!dsp->thinkdigit) {
1480                                 if (digit) {
1481                                         /* Looks like we might have something.  
1482                                          * Request a conference mute for the moment */
1483                                         memset(&dsp->f, 0, sizeof(dsp->f));
1484                                         dsp->f.frametype = AST_FRAME_DTMF;
1485                                         dsp->f.subclass = 'm';
1486                                         dsp->thinkdigit = 'x';
1487                                         FIX_INF(af);
1488                                         if (chan)
1489                                                 ast_queue_frame(chan, af);
1490                                         ast_frfree(af);
1491                                         return &dsp->f;
1492                                 }
1493                         } else {
1494                                 if (digit) {
1495                                         /* Thought we saw one last time.  Pretty sure we really have now */
1496                                         if (dsp->thinkdigit) {
1497                                                 if ((dsp->thinkdigit != 'x') && (dsp->thinkdigit != digit)) {
1498                                                         /* If we found a digit, and we're changing digits, go
1499                                                            ahead and send this one, but DON'T stop confmute because
1500                                                            we're detecting something else, too... */
1501                                                         memset(&dsp->f, 0, sizeof(dsp->f));
1502                                                         dsp->f.frametype = AST_FRAME_DTMF;
1503                                                         dsp->f.subclass = dsp->thinkdigit;
1504                                                         FIX_INF(af);
1505                                                         if (chan)
1506                                                                 ast_queue_frame(chan, af);
1507                                                         ast_frfree(af);
1508                                                 }
1509                                                 dsp->thinkdigit = digit;
1510                                                 return &dsp->f;
1511                                         }
1512                                         dsp->thinkdigit = digit;
1513                                 } else {
1514                                         if (dsp->thinkdigit) {
1515                                                 memset(&dsp->f, 0, sizeof(dsp->f));
1516                                                 if (dsp->thinkdigit != 'x') {
1517                                                         /* If we found a digit, send it now */
1518                                                         dsp->f.frametype = AST_FRAME_DTMF;
1519                                                         dsp->f.subclass = dsp->thinkdigit;
1520                                                         dsp->thinkdigit = 0;
1521                                                 } else {
1522                                                         dsp->f.frametype = AST_FRAME_DTMF;
1523                                                         dsp->f.subclass = 'u';
1524                                                         dsp->thinkdigit = 0;
1525                                                 }
1526                                                 FIX_INF(af);
1527                                                 if (chan)
1528                                                         ast_queue_frame(chan, af);
1529                                                 ast_frfree(af);
1530                                                 return &dsp->f;
1531                                         }
1532                                 }
1533                         }
1534                 } else if (!digit) {
1535                         /* Only check when there is *not* a hit... */
1536                         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1537                                 if (dsp->td.mf.current_digits) {
1538                                         memset(&dsp->f, 0, sizeof(dsp->f));
1539                                         dsp->f.frametype = AST_FRAME_DTMF;
1540                                         dsp->f.subclass = dsp->td.mf.digits[0];
1541                                         memmove(dsp->td.mf.digits, dsp->td.mf.digits + 1, dsp->td.mf.current_digits);
1542                                         dsp->td.mf.current_digits--;
1543                                         FIX_INF(af);
1544                                         if (chan)
1545                                                 ast_queue_frame(chan, af);
1546                                         ast_frfree(af);
1547                                         return &dsp->f;
1548                                 }
1549                         } else {
1550                                 if (dsp->td.dtmf.current_digits) {
1551                                         memset(&dsp->f, 0, sizeof(dsp->f));
1552                                         dsp->f.frametype = AST_FRAME_DTMF;
1553                                         dsp->f.subclass = dsp->td.dtmf.digits[0];
1554                                         memmove(dsp->td.dtmf.digits, dsp->td.dtmf.digits + 1, dsp->td.dtmf.current_digits);
1555                                         dsp->td.dtmf.current_digits--;
1556                                         FIX_INF(af);
1557                                         if (chan)
1558                                                 ast_queue_frame(chan, af);
1559                                         ast_frfree(af);
1560                                         return &dsp->f;
1561                                 }
1562                         }
1563                 }
1564         }
1565         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1566                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1567                 if (res) {
1568                         switch(res) {
1569                         case AST_CONTROL_ANSWER:
1570                         case AST_CONTROL_BUSY:
1571                         case AST_CONTROL_RINGING:
1572                         case AST_CONTROL_CONGESTION:
1573                         case AST_CONTROL_HANGUP:
1574                                 memset(&dsp->f, 0, sizeof(dsp->f));
1575                                 dsp->f.frametype = AST_FRAME_CONTROL;
1576                                 dsp->f.subclass = res;
1577                                 dsp->f.src = "dsp_progress";
1578                                 if (chan) 
1579                                         ast_queue_frame(chan, &dsp->f);
1580                                 break;
1581                         default:
1582                                 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1583                         }
1584                 }
1585         }
1586         FIX_INF(af);
1587         return af;
1588 }
1589
1590 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1591 {
1592         int max = 0;
1593         int x;
1594         
1595         dsp->gsamp_size = modes[dsp->progmode].size;
1596         dsp->gsamps = 0;
1597         for (x=0;x<sizeof(modes[dsp->progmode].freqs) / sizeof(modes[dsp->progmode].freqs[0]);x++) {
1598                 if (modes[dsp->progmode].freqs[x]) {
1599                         goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->gsamp_size);
1600                         max = x + 1;
1601                 }
1602         }
1603         dsp->freqcount = max;
1604         dsp->ringtimeout= 0;
1605 }
1606
1607 struct ast_dsp *ast_dsp_new(void)
1608 {
1609         struct ast_dsp *dsp;
1610
1611         dsp = malloc(sizeof(struct ast_dsp));
1612         if (dsp) {
1613                 memset(dsp, 0, sizeof(struct ast_dsp));
1614                 dsp->threshold = DEFAULT_THRESHOLD;
1615                 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1616                 dsp->busycount = DSP_HISTORY;
1617                 /* Initialize DTMF detector */
1618                 ast_dtmf_detect_init(&dsp->td.dtmf);
1619                 /* Initialize initial DSP progress detect parameters */
1620                 ast_dsp_prog_reset(dsp);
1621         }
1622         return dsp;
1623 }
1624
1625 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1626 {
1627         dsp->features = features;
1628 }
1629
1630 void ast_dsp_free(struct ast_dsp *dsp)
1631 {
1632         free(dsp);
1633 }
1634
1635 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1636 {
1637         dsp->threshold = threshold;
1638 }
1639
1640 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1641 {
1642         if (cadences < 4)
1643                 cadences = 4;
1644         if (cadences > DSP_HISTORY)
1645                 cadences = DSP_HISTORY;
1646         dsp->busycount = cadences;
1647 }
1648
1649 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, int tonelength, int quietlength)
1650 {
1651         dsp->busy_tonelength = tonelength;
1652         dsp->busy_quietlength = quietlength;
1653         ast_log(LOG_DEBUG, "dsp busy pattern set to %d,%d\n", tonelength, quietlength);
1654 }
1655
1656 void ast_dsp_digitreset(struct ast_dsp *dsp)
1657 {
1658         int i;
1659         
1660         dsp->thinkdigit = 0;
1661         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1662                 memset(dsp->td.mf.digits, 0, sizeof(dsp->td.mf.digits));
1663                 dsp->td.mf.current_digits = 0;
1664                 /* Reinitialise the detector for the next block */
1665                 for (i = 0;  i < 6;  i++) {
1666                         goertzel_reset(&dsp->td.mf.tone_out[i]);
1667 #ifdef OLD_DSP_ROUTINES
1668                         goertzel_reset(&dsp->td.mf.tone_out2nd[i]);
1669 #endif                  
1670                 }
1671 #ifdef OLD_DSP_ROUTINES
1672                 dsp->td.mf.energy = 0.0;
1673                 dsp->td.mf.hit1 = dsp->td.mf.hit2 = dsp->td.mf.hit3 = dsp->td.mf.hit4 = dsp->td.mf.mhit = 0;
1674 #else
1675                 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;
1676 #endif          
1677                 dsp->td.mf.current_sample = 0;
1678         } else {
1679                 memset(dsp->td.dtmf.digits, 0, sizeof(dsp->td.dtmf.digits));
1680                 dsp->td.dtmf.current_digits = 0;
1681                 /* Reinitialise the detector for the next block */
1682                 for (i = 0;  i < 4;  i++) {
1683                         goertzel_reset(&dsp->td.dtmf.row_out[i]);
1684                         goertzel_reset(&dsp->td.dtmf.col_out[i]);
1685 #ifdef OLD_DSP_ROUTINES
1686                         goertzel_reset(&dsp->td.dtmf.row_out2nd[i]);
1687                         goertzel_reset(&dsp->td.dtmf.col_out2nd[i]);
1688 #endif                  
1689                 }
1690 #ifdef FAX_DETECT
1691                 goertzel_reset (&dsp->td.dtmf.fax_tone);
1692 #endif
1693 #ifdef OLD_DSP_ROUTINES
1694 #ifdef FAX_DETECT
1695                 goertzel_reset (&dsp->td.dtmf.fax_tone2nd);
1696 #endif
1697                 dsp->td.dtmf.hit1 = dsp->td.dtmf.hit2 = dsp->td.dtmf.hit3 = dsp->td.dtmf.hit4 = dsp->td.dtmf.mhit = 0;
1698 #else
1699                 dsp->td.dtmf.hits[2] = dsp->td.dtmf.hits[1] = dsp->td.dtmf.hits[0] =  dsp->td.dtmf.mhit = 0;
1700 #endif          
1701                 dsp->td.dtmf.energy = 0.0;
1702                 dsp->td.dtmf.current_sample = 0;
1703         }
1704 }
1705
1706 void ast_dsp_reset(struct ast_dsp *dsp)
1707 {
1708         int x;
1709         
1710         dsp->totalsilence = 0;
1711         dsp->gsamps = 0;
1712         for (x=0;x<4;x++)
1713                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1714         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1715         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));      
1716         dsp->ringtimeout= 0;
1717 }
1718
1719 int ast_dsp_digitmode(struct ast_dsp *dsp, int digitmode)
1720 {
1721         int new;
1722         int old;
1723         
1724         old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1725         new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1726         if (old != new) {
1727                 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1728                 if (new & DSP_DIGITMODE_MF)
1729                         ast_mf_detect_init(&dsp->td.mf);
1730                 else
1731                         ast_dtmf_detect_init(&dsp->td.dtmf);
1732         }
1733         dsp->digitmode = digitmode;
1734         return 0;
1735 }
1736
1737 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1738 {
1739         int x;
1740         
1741         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]);x++) {
1742                 if (!strcasecmp(aliases[x].name, zone)) {
1743                         dsp->progmode = aliases[x].mode;
1744                         ast_dsp_prog_reset(dsp);
1745                         return 0;
1746                 }
1747         }
1748         return -1;
1749 }
1750
1751 int ast_dsp_get_tstate(struct ast_dsp *dsp) 
1752 {
1753         return dsp->tstate;
1754 }
1755
1756 int ast_dsp_get_tcount(struct ast_dsp *dsp) 
1757 {
1758         return dsp->tcount;
1759 }