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