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