dsp_process was enhanced to work with alaw and ulaw in addition to slin.
[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_350UK = 0,
86         HZ_400UK,
87         HZ_440UK
88 };
89
90 static struct progalias {
91         char *name;
92         enum prog_mode mode;
93 } aliases[] = {
94         { "us", PROG_MODE_NA },
95         { "ca", PROG_MODE_NA },
96         { "cr", PROG_MODE_CR },
97         { "br", PROG_MODE_CR },
98         { "uk", PROG_MODE_UK },
99 };
100
101 static struct progress {
102         enum gsamp_size size;
103         int freqs[7];
104 } modes[] = {
105         { GSAMP_SIZE_NA, { 350, 440, 480, 620, 950, 1400, 1800 } },     /*!< North America */
106         { GSAMP_SIZE_CR, { 425 } },                                     /*!< Costa Rica, Brazil */
107         { GSAMP_SIZE_UK, { 350, 400, 440 } },                                   /*!< UK */
108 };
109
110 /*!\brief This value is the minimum threshold, calculated by averaging all
111  * of the samples within a frame, for which a frame is determined to either
112  * be silence (below the threshold) or noise (above the threshold).  Please
113  * note that while the default threshold is an even exponent of 2, there is
114  * no requirement that it be so.  The threshold will accept any value between
115  * 0 and 32767.
116  */
117 #define DEFAULT_THRESHOLD       512
118
119 enum busy_detect {
120         BUSY_PERCENT = 10,      /*!< The percentage difference between the two last silence periods */
121         BUSY_PAT_PERCENT = 7,   /*!< The percentage difference between measured and actual pattern */
122         BUSY_THRESHOLD = 100,   /*!< Max number of ms difference between max and min times in busy */
123         BUSY_MIN = 75,          /*!< Busy must be at least 80 ms in half-cadence */
124         BUSY_MAX =3100          /*!< Busy can't be longer than 3100 ms in half-cadence */
125 };
126
127 /*! Remember last 15 units */
128 #define DSP_HISTORY             15
129
130 #define TONE_THRESH             10.0    /*!< How much louder the tone should be than channel energy */
131 #define TONE_MIN_THRESH         1e8     /*!< How much tone there should be at least to attempt */
132
133 /*! All THRESH_XXX values are in GSAMP_SIZE chunks (us = 22ms) */
134 enum gsamp_thresh {
135         THRESH_RING = 8,                /*!< Need at least 150ms ring to accept */
136         THRESH_TALK = 2,                /*!< Talk detection does not work continuously */
137         THRESH_BUSY = 4,                /*!< Need at least 80ms to accept */
138         THRESH_CONGESTION = 4,          /*!< Need at least 80ms to accept */
139         THRESH_HANGUP = 60,             /*!< Need at least 1300ms to accept hangup */
140         THRESH_RING2ANSWER = 300        /*!< Timeout from start of ring to answer (about 6600 ms) */
141 };
142
143 #define MAX_DTMF_DIGITS         128
144
145 /* Basic DTMF specs:
146  *
147  * Minimum tone on = 40ms
148  * Minimum tone off = 50ms
149  * Maximum digit rate = 10 per second
150  * Normal twist <= 8dB accepted
151  * Reverse twist <= 4dB accepted
152  * S/N >= 15dB will detect OK
153  * Attenuation <= 26dB will detect OK
154  * Frequency tolerance +- 1.5% will detect, +-3.5% will reject
155  */
156
157 #define DTMF_THRESHOLD          8.0e7
158 #define FAX_THRESHOLD           8.0e7
159 #define FAX_2ND_HARMONIC        2.0     /* 4dB */
160 #define DTMF_NORMAL_TWIST       6.3     /* 8dB */
161 #ifdef  RADIO_RELAX
162 #define DTMF_REVERSE_TWIST          (relax ? 6.5 : 2.5)     /* 4dB normal */
163 #else
164 #define DTMF_REVERSE_TWIST          (relax ? 4.0 : 2.5)     /* 4dB normal */
165 #endif
166 #define DTMF_RELATIVE_PEAK_ROW  6.3     /* 8dB */
167 #define DTMF_RELATIVE_PEAK_COL  6.3     /* 8dB */
168 #define DTMF_2ND_HARMONIC_ROW       (relax ? 1.7 : 2.5)     /* 4dB normal */
169 #define DTMF_2ND_HARMONIC_COL   63.1    /* 18dB */
170 #define DTMF_TO_TOTAL_ENERGY    42.0
171
172 #define BELL_MF_THRESHOLD       1.6e9
173 #define BELL_MF_TWIST           4.0     /* 6dB */
174 #define BELL_MF_RELATIVE_PEAK   12.6    /* 11dB */
175
176 #if defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
177 #error You cant use BUSYDETECT_TONEONLY together with BUSYDETECT_COMPARE_TONE_AND_SILENCE
178 #endif
179
180 /* The CNG signal consists of the transmission of 1100 Hz for 1/2 second,
181  * followed by a 3 second silent (2100 Hz OFF) period.
182  */
183 #define FAX_TONE_CNG_FREQ       1100
184 #define FAX_TONE_CNG_DURATION   500
185 #define FAX_TONE_CNG_DB         16
186
187 /* This signal may be sent by the Terminating FAX machine anywhere between
188  * 1.8 to 2.5 seconds AFTER answering the call.  The CED signal consists
189  * of a 2100 Hz tone that is from 2.6 to 4 seconds in duration.
190 */
191 #define FAX_TONE_CED_FREQ       2100
192 #define FAX_TONE_CED_DURATION   2600
193 #define FAX_TONE_CED_DB         16
194
195 #define DEFAULT_SAMPLE_RATE             8000
196
197 /* MF goertzel size */
198 #define MF_GSIZE                120
199
200 /* DTMF goertzel size */
201 #define DTMF_GSIZE              102
202
203 /* How many successive hits needed to consider begin of a digit */
204 #define DTMF_HITS_TO_BEGIN      2
205 /* How many successive misses needed to consider end of a digit */
206 #define DTMF_MISSES_TO_END      3
207
208 /*!
209  * \brief The default silence threshold we will use if an alternate
210  * configured value is not present or is invalid.
211  */
212 static const int DEFAULT_SILENCE_THRESHOLD = 256;
213
214 #define CONFIG_FILE_NAME "dsp.conf"
215
216 typedef struct {
217         int v2;
218         int v3;
219         int chunky;
220         int fac;
221         int samples;
222 } goertzel_state_t;
223
224 typedef struct {
225         int value;
226         int power;
227 } goertzel_result_t;
228
229 typedef struct
230 {
231         int freq;
232         int block_size;
233         int squelch;            /* Remove (squelch) tone */
234         goertzel_state_t tone;
235         float energy;           /* Accumulated energy of the current block */
236         int samples_pending;    /* Samples remain to complete the current block */
237         int mute_samples;       /* How many additional samples needs to be muted to suppress already detected tone */
238
239         int hits_required;      /* How many successive blocks with tone we are looking for */
240         float threshold;        /* Energy of the tone relative to energy from all other signals to consider a hit */
241
242         int hit_count;          /* How many successive blocks we consider tone present */
243         int last_hit;           /* Indicates if the last processed block was a hit */
244
245 } tone_detect_state_t;
246
247 typedef struct
248 {
249         int block_size;
250         goertzel_state_t tone;
251         float energy;           /* Accumulated energy of the current block */
252         int samples_pending;    /* Samples remain to complete the current block */
253
254         float threshold;        /* Energy of the tone relative to energy from all other signals to consider a hit */
255
256         int hit_count;
257         int miss_count;
258
259 } v21_detect_state_t;
260
261 typedef struct
262 {
263         goertzel_state_t row_out[4];
264         goertzel_state_t col_out[4];
265         int hits_to_begin;              /* How many successive hits needed to consider begin of a digit */
266         int misses_to_end;              /* How many successive misses needed to consider end of a digit */
267         int hits;                       /* How many successive hits we have seen already */
268         int misses;                     /* How many successive misses we have seen already */
269         int lasthit;
270         int current_hit;
271         float energy;
272         int current_sample;
273         int mute_samples;
274 } dtmf_detect_state_t;
275
276 typedef struct
277 {
278         goertzel_state_t tone_out[6];
279         int current_hit;
280         int hits[5];
281         int current_sample;
282         int mute_samples;
283 } mf_detect_state_t;
284
285 typedef struct
286 {
287         char digits[MAX_DTMF_DIGITS + 1];
288         int digitlen[MAX_DTMF_DIGITS + 1];
289         int current_digits;
290         int detected_digits;
291         int lost_digits;
292
293         union {
294                 dtmf_detect_state_t dtmf;
295                 mf_detect_state_t mf;
296         } td;
297 } digit_detect_state_t;
298
299 static const float dtmf_row[] = {
300         697.0,  770.0,  852.0,  941.0
301 };
302 static const float dtmf_col[] = {
303         1209.0, 1336.0, 1477.0, 1633.0
304 };
305 static const float mf_tones[] = {
306         700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
307 };
308 static const char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
309 static const char bell_mf_positions[] = "1247C-358A--69*---0B----#";
310 static int thresholds[THRESHOLD_MAX];
311
312 static inline void goertzel_sample(goertzel_state_t *s, short sample)
313 {
314         int v1;
315         
316         v1 = s->v2;
317         s->v2 = s->v3;
318         
319         s->v3 = (s->fac * s->v2) >> 15;
320         s->v3 = s->v3 - v1 + (sample >> s->chunky);
321         if (abs(s->v3) > 32768) {
322                 s->chunky++;
323                 s->v3 = s->v3 >> 1;
324                 s->v2 = s->v2 >> 1;
325                 v1 = v1 >> 1;
326         }
327 }
328
329 static inline void goertzel_update(goertzel_state_t *s, short *samps, int count)
330 {
331         int i;
332         
333         for (i = 0; i < count; i++) {
334                 goertzel_sample(s, samps[i]);
335         }
336 }
337
338
339 static inline float goertzel_result(goertzel_state_t *s)
340 {
341         goertzel_result_t r;
342         r.value = (s->v3 * s->v3) + (s->v2 * s->v2);
343         r.value -= ((s->v2 * s->v3) >> 15) * s->fac;
344         r.power = s->chunky * 2;
345         return (float)r.value * (float)(1 << r.power);
346 }
347
348 static inline void goertzel_init(goertzel_state_t *s, float freq, int samples, unsigned int sample_rate)
349 {
350         s->v2 = s->v3 = s->chunky = 0.0;
351         s->fac = (int)(32768.0 * 2.0 * cos(2.0 * M_PI * freq / sample_rate));
352         s->samples = samples;
353 }
354
355 static inline void goertzel_reset(goertzel_state_t *s)
356 {
357         s->v2 = s->v3 = s->chunky = 0.0;
358 }
359
360 typedef struct {
361         int start;
362         int end;
363 } fragment_t;
364
365 /* Note on tone suppression (squelching). Individual detectors (DTMF/MF/generic tone)
366  * report fragmens of the frame in which detected tone resides and which needs
367  * to be "muted" in order to suppress the tone. To mark fragment for muting,
368  * detectors call mute_fragment passing fragment_t there. Multiple fragments
369  * can be marked and ast_dsp_process later will mute all of them.
370  *
371  * Note: When tone starts in the middle of a Goertzel block, it won't be properly
372  * detected in that block, only in the next. If we only mute the next block
373  * where tone is actually detected, the user will still hear beginning
374  * of the tone in preceeding block. This is why we usually want to mute some amount
375  * of samples preceeding and following the block where tone was detected.
376 */
377
378 struct ast_dsp {
379         struct ast_frame f;
380         int threshold;
381         int totalsilence;
382         int totalnoise;
383         int features;
384         int ringtimeout;
385         int busymaybe;
386         int busycount;
387         struct ast_dsp_busy_pattern busy_cadence;
388         int historicnoise[DSP_HISTORY];
389         int historicsilence[DSP_HISTORY];
390         goertzel_state_t freqs[7];
391         int freqcount;
392         int gsamps;
393         enum gsamp_size gsamp_size;
394         enum prog_mode progmode;
395         int tstate;
396         int tcount;
397         int digitmode;
398         int faxmode;
399         int dtmf_began;
400         int display_inband_dtmf_warning;
401         float genergy;
402         int mute_fragments;
403         unsigned int sample_rate;
404         fragment_t mute_data[5];
405         digit_detect_state_t digit_state;
406         tone_detect_state_t cng_tone_state;
407         tone_detect_state_t ced_tone_state;
408         v21_detect_state_t v21_state;
409 };
410
411 static void mute_fragment(struct ast_dsp *dsp, fragment_t *fragment)
412 {
413         if (dsp->mute_fragments >= ARRAY_LEN(dsp->mute_data)) {
414                 ast_log(LOG_ERROR, "Too many fragments to mute. Ignoring\n");
415                 return;
416         }
417
418         dsp->mute_data[dsp->mute_fragments++] = *fragment;
419 }
420
421 static void ast_tone_detect_init(tone_detect_state_t *s, int freq, int duration, int amp, unsigned int sample_rate)
422 {
423         int duration_samples;
424         float x;
425         int periods_in_block;
426
427         s->freq = freq;
428
429         /* Desired tone duration in samples */
430         duration_samples = duration * sample_rate / 1000;
431         /* We want to allow 10% deviation of tone duration */
432         duration_samples = duration_samples * 9 / 10;
433
434         /* If we want to remove tone, it is important to have block size not
435            to exceed frame size. Otherwise by the moment tone is detected it is too late
436            to squelch it from previous frames. Block size is 20ms at the given sample rate.*/
437         s->block_size = (20 * sample_rate) / 1000;
438
439         periods_in_block = s->block_size * freq / sample_rate;
440
441         /* Make sure we will have at least 5 periods at target frequency for analisys.
442            This may make block larger than expected packet and will make squelching impossible
443            but at least we will be detecting the tone */
444         if (periods_in_block < 5)
445                 periods_in_block = 5;
446
447         /* Now calculate final block size. It will contain integer number of periods */
448         s->block_size = periods_in_block * sample_rate / freq;
449
450         /* tone_detect is currently only used to detect fax tones and we
451            do not need suqlching the fax tones */
452         s->squelch = 0;
453
454         /* Account for the first and the last block to be incomplete
455            and thus no tone will be detected in them */
456         s->hits_required = (duration_samples - (s->block_size - 1)) / s->block_size;
457
458         goertzel_init(&s->tone, freq, s->block_size, sample_rate);
459
460         s->samples_pending = s->block_size;
461         s->hit_count = 0;
462         s->last_hit = 0;
463         s->energy = 0.0;
464
465         /* We want tone energy to be amp decibels above the rest of the signal (the noise).
466            According to Parseval's theorem the energy computed in time domain equals to energy
467            computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
468            from the energy in the time domain we will get energy of the remaining signal (without the tone
469            we are detecting). We will be checking that
470                 10*log(Ew / (Et - Ew)) > amp
471            Calculate threshold so that we will be actually checking
472                 Ew > Et * threshold
473         */
474
475         x = pow(10.0, amp / 10.0);
476         s->threshold = x / (x + 1);
477
478         ast_debug(1, "Setup tone %d Hz, %d ms, block_size=%d, hits_required=%d\n", freq, duration, s->block_size, s->hits_required);
479 }
480
481 static void ast_v21_detect_init(v21_detect_state_t *s, unsigned int sample_rate)
482 {
483         float x;
484         int periods_in_block;
485
486         /* If we want to remove tone, it is important to have block size not
487            to exceed frame size. Otherwise by the moment tone is detected it is too late
488            to squelch it from previous frames. Block size is 20ms at the given sample rate.*/
489         s->block_size = (20 * sample_rate) / 1000;
490
491         periods_in_block = s->block_size * 1850 / sample_rate;
492
493         /* Make sure we will have at least 5 periods at target frequency for analisys.
494            This may make block larger than expected packet and will make squelching impossible
495            but at least we will be detecting the tone */
496         if (periods_in_block < 5)
497                 periods_in_block = 5;
498
499         /* Now calculate final block size. It will contain integer number of periods */
500         s->block_size = periods_in_block * sample_rate / 1850;
501
502         goertzel_init(&s->tone, 1850.0, s->block_size, sample_rate);
503
504         s->samples_pending = s->block_size;
505         s->hit_count = 0;
506         s->miss_count = 0;
507         s->energy = 0.0;
508
509         /* We want tone energy to be amp decibels above the rest of the signal (the noise).
510            According to Parseval's theorem the energy computed in time domain equals to energy
511            computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
512            from the energy in the time domain we will get energy of the remaining signal (without the tone
513            we are detecting). We will be checking that
514                 10*log(Ew / (Et - Ew)) > amp
515            Calculate threshold so that we will be actually checking
516                 Ew > Et * threshold
517         */
518
519         x = pow(10.0, 16 / 10.0);
520         s->threshold = x / (x + 1);
521
522         ast_debug(1, "Setup v21 detector, block_size=%d\n", s->block_size);
523 }
524
525 static void ast_fax_detect_init(struct ast_dsp *s)
526 {
527         ast_tone_detect_init(&s->cng_tone_state, FAX_TONE_CNG_FREQ, FAX_TONE_CNG_DURATION, FAX_TONE_CNG_DB, s->sample_rate);
528         ast_tone_detect_init(&s->ced_tone_state, FAX_TONE_CED_FREQ, FAX_TONE_CED_DURATION, FAX_TONE_CED_DB, s->sample_rate);
529         ast_v21_detect_init(&s->v21_state, s->sample_rate);
530         if (s->faxmode & DSP_FAXMODE_DETECT_SQUELCH) {
531                 s->cng_tone_state.squelch = 1;
532                 s->ced_tone_state.squelch = 1;
533         }
534
535 }
536
537 static void ast_dtmf_detect_init (dtmf_detect_state_t *s, unsigned int sample_rate)
538 {
539         int i;
540
541         s->lasthit = 0;
542         s->current_hit = 0;
543         for (i = 0;  i < 4;  i++) {
544                 goertzel_init(&s->row_out[i], dtmf_row[i], DTMF_GSIZE, sample_rate);
545                 goertzel_init(&s->col_out[i], dtmf_col[i], DTMF_GSIZE, sample_rate);
546                 s->energy = 0.0;
547         }
548         s->current_sample = 0;
549         s->hits = 0;
550         s->misses = 0;
551
552         s->hits_to_begin = DTMF_HITS_TO_BEGIN;
553         s->misses_to_end = DTMF_MISSES_TO_END;
554 }
555
556 static void ast_mf_detect_init (mf_detect_state_t *s, unsigned int sample_rate)
557 {
558         int i;
559         s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
560         for (i = 0;  i < 6;  i++) {
561                 goertzel_init (&s->tone_out[i], mf_tones[i], 160, sample_rate);
562         }
563         s->current_sample = 0;
564         s->current_hit = 0;
565 }
566
567 static void ast_digit_detect_init(digit_detect_state_t *s, int mf, unsigned int sample_rate)
568 {
569         s->current_digits = 0;
570         s->detected_digits = 0;
571         s->lost_digits = 0;
572         s->digits[0] = '\0';
573
574         if (mf) {
575                 ast_mf_detect_init(&s->td.mf, sample_rate);
576         } else {
577                 ast_dtmf_detect_init(&s->td.dtmf, sample_rate);
578         }
579 }
580
581 /*! \brief Detect a v21 preamble.
582  * This code is derived from the tone_detect code and detects a pattern of 1850
583  * Hz tone found in a v21 preamble.
584  */
585 static int v21_detect(struct ast_dsp *dsp, v21_detect_state_t *s, int16_t *amp, int samples)
586 {
587         float tone_energy;
588         int i;
589         int hit = 0;
590         int limit;
591         int res = 0;
592         int16_t *ptr;
593         int start, end;
594
595         for (start = 0;  start < samples;  start = end) {
596                 /* Process in blocks. */
597                 limit = samples - start;
598                 if (limit > s->samples_pending) {
599                         limit = s->samples_pending;
600                 }
601                 end = start + limit;
602
603                 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
604                         /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
605                         s->energy += (int32_t) *ptr * (int32_t) *ptr;
606
607                         goertzel_sample(&s->tone, *ptr);
608                 }
609
610                 s->samples_pending -= limit;
611
612                 if (s->samples_pending) {
613                         /* Finished incomplete (last) block */
614                         break;
615                 }
616
617                 tone_energy = goertzel_result(&s->tone);
618
619                 /* Scale to make comparable */
620                 tone_energy *= 2.0;
621                 s->energy *= s->block_size;
622
623                 ast_debug(10, "v21 1850 Ew=%.2E, Et=%.2E, s/n=%10.2f\n", tone_energy, s->energy, tone_energy / (s->energy - tone_energy));
624
625                 hit = 0;
626                 if (tone_energy > s->energy * s->threshold) {
627                         ast_debug(10, "Hit! count=%d; miss_count=%d\n", s->hit_count, s->miss_count);
628                         hit = 1;
629                 }
630
631                 if (hit) {
632                         if (s->miss_count == 3) {
633                                 s->hit_count++;
634                         } else {
635                                 s->hit_count = 1;
636                         }
637
638                         s->miss_count = 0;
639                 } else {
640                         s->miss_count++;
641                         if (s->miss_count > 3) {
642                                 s->hit_count = 0;
643                         }
644                 }
645
646                 if (s->hit_count == 4) {
647                         ast_debug(1, "v21 preamble detected\n");
648                         res = 1;
649                 }
650
651                 /* Reinitialise the detector for the next block */
652                 goertzel_reset(&s->tone);
653
654                 /* Advance to the next block */
655                 s->energy = 0.0;
656                 s->samples_pending = s->block_size;
657
658                 amp += limit;
659         }
660
661         return res;
662 }
663
664 static int tone_detect(struct ast_dsp *dsp, tone_detect_state_t *s, int16_t *amp, int samples)
665 {
666         float tone_energy;
667         int i;
668         int hit = 0;
669         int limit;
670         int res = 0;
671         int16_t *ptr;
672         int start, end;
673         fragment_t mute = {0, 0};
674
675         if (s->squelch && s->mute_samples > 0) {
676                 mute.end = (s->mute_samples < samples) ? s->mute_samples : samples;
677                 s->mute_samples -= mute.end;
678         }
679
680         for (start = 0;  start < samples;  start = end) {
681                 /* Process in blocks. */
682                 limit = samples - start;
683                 if (limit > s->samples_pending) {
684                         limit = s->samples_pending;
685                 }
686                 end = start + limit;
687
688                 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
689                         /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
690                         s->energy += (int32_t) *ptr * (int32_t) *ptr;
691
692                         goertzel_sample(&s->tone, *ptr);
693                 }
694
695                 s->samples_pending -= limit;
696
697                 if (s->samples_pending) {
698                         /* Finished incomplete (last) block */
699                         break;
700                 }
701
702                 tone_energy = goertzel_result(&s->tone);
703
704                 /* Scale to make comparable */
705                 tone_energy *= 2.0;
706                 s->energy *= s->block_size;
707
708                 ast_debug(10, "tone %d, Ew=%.2E, Et=%.2E, s/n=%10.2f\n", s->freq, tone_energy, s->energy, tone_energy / (s->energy - tone_energy));
709                 hit = 0;
710                 if (tone_energy > s->energy * s->threshold) {
711                         ast_debug(10, "Hit! count=%d\n", s->hit_count);
712                         hit = 1;
713                 }
714
715                 if (s->hit_count) {
716                         s->hit_count++;
717                 }
718
719                 if (hit == s->last_hit) {
720                         if (!hit) {
721                                 /* Two successive misses. Tone ended */
722                                 s->hit_count = 0;
723                         } else if (!s->hit_count) {
724                                 s->hit_count++;
725                         }
726
727                 }
728
729                 if (s->hit_count == s->hits_required) {
730                         ast_debug(1, "%d Hz done detected\n", s->freq);
731                         res = 1;
732                 }
733
734                 s->last_hit = hit;
735
736                 /* If we had a hit in this block, include it into mute fragment */
737                 if (s->squelch && hit) {
738                         if (mute.end < start - s->block_size) {
739                                 /* There is a gap between fragments */
740                                 mute_fragment(dsp, &mute);
741                                 mute.start = (start > s->block_size) ? (start - s->block_size) : 0;
742                         }
743                         mute.end = end + s->block_size;
744                 }
745
746                 /* Reinitialise the detector for the next block */
747                 /* Reset for the next block */
748                 goertzel_reset(&s->tone);
749
750                 /* Advance to the next block */
751                 s->energy = 0.0;
752                 s->samples_pending = s->block_size;
753
754                 amp += limit;
755         }
756
757         if (s->squelch && mute.end) {
758                 if (mute.end > samples) {
759                         s->mute_samples = mute.end - samples;
760                         mute.end = samples;
761                 }
762                 mute_fragment(dsp, &mute);
763         }
764
765         return res;
766 }
767
768 static void store_digit(digit_detect_state_t *s, char digit)
769 {
770         s->detected_digits++;
771         if (s->current_digits < MAX_DTMF_DIGITS) {
772                 s->digitlen[s->current_digits] = 0;
773                 s->digits[s->current_digits++] = digit;
774                 s->digits[s->current_digits] = '\0';
775         } else {
776                 ast_log(LOG_WARNING, "Digit lost due to full buffer\n");
777                 s->lost_digits++;
778         }
779 }
780
781 static int dtmf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[], int samples, int squelch, int relax)
782 {
783         float row_energy[4];
784         float col_energy[4];
785         float famp;
786         int i;
787         int j;
788         int sample;
789         int best_row;
790         int best_col;
791         int hit;
792         int limit;
793         fragment_t mute = {0, 0};
794
795         if (squelch && s->td.dtmf.mute_samples > 0) {
796                 mute.end = (s->td.dtmf.mute_samples < samples) ? s->td.dtmf.mute_samples : samples;
797                 s->td.dtmf.mute_samples -= mute.end;
798         }
799
800         hit = 0;
801         for (sample = 0; sample < samples; sample = limit) {
802                 /* DTMF_GSIZE is optimised to meet the DTMF specs. */
803                 if ((samples - sample) >= (DTMF_GSIZE - s->td.dtmf.current_sample)) {
804                         limit = sample + (DTMF_GSIZE - s->td.dtmf.current_sample);
805                 } else {
806                         limit = samples;
807                 }
808                 /* The following unrolled loop takes only 35% (rough estimate) of the 
809                    time of a rolled loop on the machine on which it was developed */
810                 for (j = sample; j < limit; j++) {
811                         famp = amp[j];
812                         s->td.dtmf.energy += famp*famp;
813                         /* With GCC 2.95, the following unrolled code seems to take about 35%
814                            (rough estimate) as long as a neat little 0-3 loop */
815                         goertzel_sample(s->td.dtmf.row_out, amp[j]);
816                         goertzel_sample(s->td.dtmf.col_out, amp[j]);
817                         goertzel_sample(s->td.dtmf.row_out + 1, amp[j]);
818                         goertzel_sample(s->td.dtmf.col_out + 1, amp[j]);
819                         goertzel_sample(s->td.dtmf.row_out + 2, amp[j]);
820                         goertzel_sample(s->td.dtmf.col_out + 2, amp[j]);
821                         goertzel_sample(s->td.dtmf.row_out + 3, amp[j]);
822                         goertzel_sample(s->td.dtmf.col_out + 3, amp[j]);
823                 }
824                 s->td.dtmf.current_sample += (limit - sample);
825                 if (s->td.dtmf.current_sample < DTMF_GSIZE) {
826                         continue;
827                 }
828                 /* We are at the end of a DTMF detection block */
829                 /* Find the peak row and the peak column */
830                 row_energy[0] = goertzel_result (&s->td.dtmf.row_out[0]);
831                 col_energy[0] = goertzel_result (&s->td.dtmf.col_out[0]);
832
833                 for (best_row = best_col = 0, i = 1;  i < 4;  i++) {
834                         row_energy[i] = goertzel_result (&s->td.dtmf.row_out[i]);
835                         if (row_energy[i] > row_energy[best_row]) {
836                                 best_row = i;
837                         }
838                         col_energy[i] = goertzel_result (&s->td.dtmf.col_out[i]);
839                         if (col_energy[i] > col_energy[best_col]) {
840                                 best_col = i;
841                         }
842                 }
843                 hit = 0;
844                 /* Basic signal level test and the twist test */
845                 if (row_energy[best_row] >= DTMF_THRESHOLD && 
846                     col_energy[best_col] >= DTMF_THRESHOLD &&
847                     col_energy[best_col] < row_energy[best_row] * DTMF_REVERSE_TWIST &&
848                     col_energy[best_col] * DTMF_NORMAL_TWIST > row_energy[best_row]) {
849                         /* Relative peak test */
850                         for (i = 0;  i < 4;  i++) {
851                                 if ((i != best_col &&
852                                     col_energy[i] * DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
853                                     (i != best_row 
854                                      && row_energy[i] * DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
855                                         break;
856                                 }
857                         }
858                         /* ... and fraction of total energy test */
859                         if (i >= 4 &&
860                             (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY * s->td.dtmf.energy) {
861                                 /* Got a hit */
862                                 hit = dtmf_positions[(best_row << 2) + best_col];
863                         }
864                 } 
865
866                 if (s->td.dtmf.current_hit) {
867                         /* We are in the middle of a digit already */
868                         if (hit != s->td.dtmf.current_hit) {
869                                 s->td.dtmf.misses++;
870                                 if (s->td.dtmf.misses == s->td.dtmf.misses_to_end) {
871                                         /* There were enough misses to consider digit ended */
872                                         s->td.dtmf.current_hit = 0;
873                                 }
874                         } else {
875                                 s->td.dtmf.misses = 0;
876                                 /* Current hit was same as last, so increment digit duration (of last digit) */
877                                 s->digitlen[s->current_digits - 1] += DTMF_GSIZE;
878                         }
879                 }
880
881                 /* Look for a start of a new digit no matter if we are already in the middle of some
882                    digit or not. This is because hits_to_begin may be smaller than misses_to_end
883                    and we may find begin of new digit before we consider last one ended. */
884                 if (hit) {
885                         if (hit == s->td.dtmf.lasthit) {
886                                 s->td.dtmf.hits++;
887                         } else {
888                                 s->td.dtmf.hits = 1;
889                         }
890
891                         if (s->td.dtmf.hits == s->td.dtmf.hits_to_begin && hit != s->td.dtmf.current_hit) {
892                                 store_digit(s, hit);
893                                 s->td.dtmf.current_hit = hit;
894                                 s->td.dtmf.misses = 0;
895                         }
896                 } else {
897                         s->td.dtmf.hits = 0;
898                 }
899
900                 s->td.dtmf.lasthit = hit;
901
902                 /* If we had a hit in this block, include it into mute fragment */
903                 if (squelch && hit) {
904                         if (mute.end < sample - DTMF_GSIZE) {
905                                 /* There is a gap between fragments */
906                                 mute_fragment(dsp, &mute);
907                                 mute.start = (sample > DTMF_GSIZE) ? (sample - DTMF_GSIZE) : 0;
908                         }
909                         mute.end = limit + DTMF_GSIZE;
910                 }
911
912                 /* Reinitialise the detector for the next block */
913                 for (i = 0; i < 4; i++) {
914                         goertzel_reset(&s->td.dtmf.row_out[i]);
915                         goertzel_reset(&s->td.dtmf.col_out[i]);
916                 }
917                 s->td.dtmf.energy = 0.0;
918                 s->td.dtmf.current_sample = 0;
919         }
920
921         if (squelch && mute.end) {
922                 if (mute.end > samples) {
923                         s->td.dtmf.mute_samples = mute.end - samples;
924                         mute.end = samples;
925                 }
926                 mute_fragment(dsp, &mute);
927         }
928
929         return (s->td.dtmf.current_hit);        /* return the debounced hit */
930 }
931
932 static int mf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[],
933                  int samples, int squelch, int relax)
934 {
935         float energy[6];
936         int best;
937         int second_best;
938         int i;
939         int j;
940         int sample;
941         int hit;
942         int limit;
943         fragment_t mute = {0, 0};
944
945         if (squelch && s->td.mf.mute_samples > 0) {
946                 mute.end = (s->td.mf.mute_samples < samples) ? s->td.mf.mute_samples : samples;
947                 s->td.mf.mute_samples -= mute.end;
948         }
949
950         hit = 0;
951         for (sample = 0;  sample < samples;  sample = limit) {
952                 /* 80 is optimised to meet the MF specs. */
953                 /* XXX So then why is MF_GSIZE defined as 120? */
954                 if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample)) {
955                         limit = sample + (MF_GSIZE - s->td.mf.current_sample);
956                 } else {
957                         limit = samples;
958                 }
959                 /* The following unrolled loop takes only 35% (rough estimate) of the 
960                    time of a rolled loop on the machine on which it was developed */
961                 for (j = sample;  j < limit;  j++) {
962                         /* With GCC 2.95, the following unrolled code seems to take about 35%
963                            (rough estimate) as long as a neat little 0-3 loop */
964                         goertzel_sample(s->td.mf.tone_out, amp[j]);
965                         goertzel_sample(s->td.mf.tone_out + 1, amp[j]);
966                         goertzel_sample(s->td.mf.tone_out + 2, amp[j]);
967                         goertzel_sample(s->td.mf.tone_out + 3, amp[j]);
968                         goertzel_sample(s->td.mf.tone_out + 4, amp[j]);
969                         goertzel_sample(s->td.mf.tone_out + 5, amp[j]);
970                 }
971                 s->td.mf.current_sample += (limit - sample);
972                 if (s->td.mf.current_sample < MF_GSIZE) {
973                         continue;
974                 }
975                 /* We're at the end of an MF detection block.  */
976                 /* Find the two highest energies. The spec says to look for
977                    two tones and two tones only. Taking this literally -ie
978                    only two tones pass the minimum threshold - doesn't work
979                    well. The sinc function mess, due to rectangular windowing
980                    ensure that! Find the two highest energies and ensure they
981                    are considerably stronger than any of the others. */
982                 energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
983                 energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
984                 if (energy[0] > energy[1]) {
985                         best = 0;
986                         second_best = 1;
987                 } else {
988                         best = 1;
989                         second_best = 0;
990                 }
991                 /*endif*/
992                 for (i = 2; i < 6; i++) {
993                         energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
994                         if (energy[i] >= energy[best]) {
995                                 second_best = best;
996                                 best = i;
997                         } else if (energy[i] >= energy[second_best]) {
998                                 second_best = i;
999                         }
1000                 }
1001                 /* Basic signal level and twist tests */
1002                 hit = 0;
1003                 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
1004                     && energy[best] < energy[second_best]*BELL_MF_TWIST
1005                     && energy[best] * BELL_MF_TWIST > energy[second_best]) {
1006                         /* Relative peak test */
1007                         hit = -1;
1008                         for (i = 0; i < 6; i++) {
1009                                 if (i != best && i != second_best) {
1010                                         if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
1011                                                 /* The best two are not clearly the best */
1012                                                 hit = 0;
1013                                                 break;
1014                                         }
1015                                 }
1016                         }
1017                 }
1018                 if (hit) {
1019                         /* Get the values into ascending order */
1020                         if (second_best < best) {
1021                                 i = best;
1022                                 best = second_best;
1023                                 second_best = i;
1024                         }
1025                         best = best * 5 + second_best - 1;
1026                         hit = bell_mf_positions[best];
1027                         /* Look for two successive similar results */
1028                         /* The logic in the next test is:
1029                            For KP we need 4 successive identical clean detects, with
1030                            two blocks of something different preceeding it. For anything
1031                            else we need two successive identical clean detects, with
1032                            two blocks of something different preceeding it. */
1033                         if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
1034                            ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
1035                             (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] && 
1036                             hit != s->td.mf.hits[0]))) {
1037                                 store_digit(s, hit);
1038                         }
1039                 }
1040
1041
1042                 if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
1043                         /* Two successive block without a hit terminate current digit */
1044                         s->td.mf.current_hit = 0;
1045                 }
1046
1047                 s->td.mf.hits[0] = s->td.mf.hits[1];
1048                 s->td.mf.hits[1] = s->td.mf.hits[2];
1049                 s->td.mf.hits[2] = s->td.mf.hits[3];
1050                 s->td.mf.hits[3] = s->td.mf.hits[4];
1051                 s->td.mf.hits[4] = hit;
1052
1053                 /* If we had a hit in this block, include it into mute fragment */
1054                 if (squelch && hit) {
1055                         if (mute.end < sample - MF_GSIZE) {
1056                                 /* There is a gap between fragments */
1057                                 mute_fragment(dsp, &mute);
1058                                 mute.start = (sample > MF_GSIZE) ? (sample - MF_GSIZE) : 0;
1059                         }
1060                         mute.end = limit + DTMF_GSIZE;
1061                 }
1062
1063                 /* Reinitialise the detector for the next block */
1064                 for (i = 0;  i < 6;  i++)
1065                         goertzel_reset(&s->td.mf.tone_out[i]);
1066                 s->td.mf.current_sample = 0;
1067         }
1068
1069         if (squelch && mute.end) {
1070                 if (mute.end > samples) {
1071                         s->td.mf.mute_samples = mute.end - samples;
1072                         mute.end = samples;
1073                 }
1074                 mute_fragment(dsp, &mute);
1075         }
1076
1077         return (s->td.mf.current_hit); /* return the debounced hit */
1078 }
1079
1080 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
1081 {
1082         /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
1083         /* Make sure absolute levels are high enough */
1084         if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH)) {
1085                 return 0;
1086         }
1087         /* Amplify ignored stuff */
1088         i2 *= TONE_THRESH;
1089         i1 *= TONE_THRESH;
1090         e *= TONE_THRESH;
1091         /* Check first tone */
1092         if ((p1 < i1) || (p1 < i2) || (p1 < e)) {
1093                 return 0;
1094         }
1095         /* And second */
1096         if ((p2 < i1) || (p2 < i2) || (p2 < e)) {
1097                 return 0;
1098         }
1099         /* Guess it's there... */
1100         return 1;
1101 }
1102
1103 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
1104 {
1105         int x;
1106         int y;
1107         int pass;
1108         int newstate = DSP_TONE_STATE_SILENCE;
1109         int res = 0;
1110         while (len) {
1111                 /* Take the lesser of the number of samples we need and what we have */
1112                 pass = len;
1113                 if (pass > dsp->gsamp_size - dsp->gsamps) {
1114                         pass = dsp->gsamp_size - dsp->gsamps;
1115                 }
1116                 for (x = 0; x < pass; x++) {
1117                         for (y = 0; y < dsp->freqcount; y++) {
1118                                 goertzel_sample(&dsp->freqs[y], s[x]);
1119                         }
1120                         dsp->genergy += s[x] * s[x];
1121                 }
1122                 s += pass;
1123                 dsp->gsamps += pass;
1124                 len -= pass;
1125                 if (dsp->gsamps == dsp->gsamp_size) {
1126                         float hz[7];
1127                         for (y = 0; y < 7; y++) {
1128                                 hz[y] = goertzel_result(&dsp->freqs[y]);
1129                         }
1130                         switch (dsp->progmode) {
1131                         case PROG_MODE_NA:
1132                                 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
1133                                         newstate = DSP_TONE_STATE_BUSY;
1134                                 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
1135                                         newstate = DSP_TONE_STATE_RINGING;
1136                                 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
1137                                         newstate = DSP_TONE_STATE_DIALTONE;
1138                                 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
1139                                         newstate = DSP_TONE_STATE_SPECIAL1;
1140                                 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
1141                                         /* End of SPECIAL1 or middle of SPECIAL2 */
1142                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL1 || dsp->tstate == DSP_TONE_STATE_SPECIAL2) {
1143                                                 newstate = DSP_TONE_STATE_SPECIAL2;
1144                                         }
1145                                 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
1146                                         /* End of SPECIAL2 or middle of SPECIAL3 */
1147                                         if (dsp->tstate == DSP_TONE_STATE_SPECIAL2 || dsp->tstate == DSP_TONE_STATE_SPECIAL3) {
1148                                                 newstate = DSP_TONE_STATE_SPECIAL3;
1149                                         }
1150                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1151                                         newstate = DSP_TONE_STATE_TALKING;
1152                                 } else {
1153                                         newstate = DSP_TONE_STATE_SILENCE;
1154                                 }
1155                                 break;
1156                         case PROG_MODE_CR:
1157                                 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
1158                                         newstate = DSP_TONE_STATE_RINGING;
1159                                 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1160                                         newstate = DSP_TONE_STATE_TALKING;
1161                                 } else {
1162                                         newstate = DSP_TONE_STATE_SILENCE;
1163                                 }
1164                                 break;
1165                         case PROG_MODE_UK:
1166                                 if (hz[HZ_400UK] > TONE_MIN_THRESH * TONE_THRESH) {
1167                                         newstate = DSP_TONE_STATE_HUNGUP;
1168                                 } else if (pair_there(hz[HZ_350UK], hz[HZ_440UK], hz[HZ_400UK], hz[HZ_400UK], dsp->genergy)) {
1169                                         newstate = DSP_TONE_STATE_DIALTONE;
1170                                 }
1171                                 break;
1172                         default:
1173                                 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
1174                         }
1175                         if (newstate == dsp->tstate) {
1176                                 dsp->tcount++;
1177                                 if (dsp->ringtimeout) {
1178                                         dsp->ringtimeout++;
1179                                 }
1180                                 switch (dsp->tstate) {
1181                                 case DSP_TONE_STATE_RINGING:
1182                                         if ((dsp->features & DSP_PROGRESS_RINGING) &&
1183                                             (dsp->tcount == THRESH_RING)) {
1184                                                 res = AST_CONTROL_RINGING;
1185                                                 dsp->ringtimeout = 1;
1186                                         }
1187                                         break;
1188                                 case DSP_TONE_STATE_BUSY:
1189                                         if ((dsp->features & DSP_PROGRESS_BUSY) &&
1190                                             (dsp->tcount == THRESH_BUSY)) {
1191                                                 res = AST_CONTROL_BUSY;
1192                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1193                                         }
1194                                         break;
1195                                 case DSP_TONE_STATE_TALKING:
1196                                         if ((dsp->features & DSP_PROGRESS_TALK) &&
1197                                             (dsp->tcount == THRESH_TALK)) {
1198                                                 res = AST_CONTROL_ANSWER;
1199                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1200                                         }
1201                                         break;
1202                                 case DSP_TONE_STATE_SPECIAL3:
1203                                         if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
1204                                             (dsp->tcount == THRESH_CONGESTION)) {
1205                                                 res = AST_CONTROL_CONGESTION;
1206                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1207                                         }
1208                                         break;
1209                                 case DSP_TONE_STATE_HUNGUP:
1210                                         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
1211                                             (dsp->tcount == THRESH_HANGUP)) {
1212                                                 res = AST_CONTROL_HANGUP;
1213                                                 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1214                                         }
1215                                         break;
1216                                 }
1217                                 if (dsp->ringtimeout == THRESH_RING2ANSWER) {
1218                                         ast_debug(1, "Consider call as answered because of timeout after last ring\n");
1219                                         res = AST_CONTROL_ANSWER;
1220                                         dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1221                                 }
1222                         } else {
1223                                 ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
1224                                 ast_debug(5, "Start state %d\n", newstate);
1225                                 dsp->tstate = newstate;
1226                                 dsp->tcount = 1;
1227                         }
1228
1229                         /* Reset goertzel */
1230                         for (x = 0; x < 7; x++) {
1231                                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1232                         }
1233                         dsp->gsamps = 0;
1234                         dsp->genergy = 0.0;
1235                 }
1236         }
1237
1238         return res;
1239 }
1240
1241 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1242 {
1243         if (inf->frametype != AST_FRAME_VOICE) {
1244                 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1245                 return 0;
1246         }
1247         if (!ast_format_is_slinear(&inf->subclass.format)) {
1248                 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1249                 return 0;
1250         }
1251         return __ast_dsp_call_progress(dsp, inf->data.ptr, inf->datalen / 2);
1252 }
1253
1254 static int __ast_dsp_silence_noise(struct ast_dsp *dsp, short *s, int len, int *totalsilence, int *totalnoise, int *frames_energy)
1255 {
1256         int accum;
1257         int x;
1258         int res = 0;
1259
1260         if (!len) {
1261                 return 0;
1262         }
1263         accum = 0;
1264         for (x = 0; x < len; x++) {
1265                 accum += abs(s[x]);
1266         }
1267         accum /= len;
1268         if (accum < dsp->threshold) {
1269                 /* Silent */
1270                 dsp->totalsilence += len / (dsp->sample_rate / 1000);
1271                 if (dsp->totalnoise) {
1272                         /* Move and save history */
1273                         memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicnoise[0]));
1274                         dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1275 /* we don't want to check for busydetect that frequently */
1276 #if 0
1277                         dsp->busymaybe = 1;
1278 #endif
1279                 }
1280                 dsp->totalnoise = 0;
1281                 res = 1;
1282         } else {
1283                 /* Not silent */
1284                 dsp->totalnoise += len / (dsp->sample_rate / 1000);
1285                 if (dsp->totalsilence) {
1286                         int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1287                         int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1288                         /* Move and save history */
1289                         memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicsilence[0]));
1290                         dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1291                         /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1292                         if (silence1 < silence2) {
1293                                 if (silence1 + silence1 * BUSY_PERCENT / 100 >= silence2) {
1294                                         dsp->busymaybe = 1;
1295                                 } else {
1296                                         dsp->busymaybe = 0;
1297                                 }
1298                         } else {
1299                                 if (silence1 - silence1 * BUSY_PERCENT / 100 <= silence2) {
1300                                         dsp->busymaybe = 1;
1301                                 } else {
1302                                         dsp->busymaybe = 0;
1303                                 }
1304                         }
1305                 }
1306                 dsp->totalsilence = 0;
1307         }
1308         if (totalsilence) {
1309                 *totalsilence = dsp->totalsilence;
1310         }
1311         if (totalnoise) {
1312                 *totalnoise = dsp->totalnoise;
1313         }
1314         if (frames_energy) {
1315                 *frames_energy = accum;
1316         }
1317         return res;
1318 }
1319
1320 int ast_dsp_busydetect(struct ast_dsp *dsp)
1321 {
1322         int res = 0, x;
1323 #ifndef BUSYDETECT_TONEONLY
1324         int avgsilence = 0, hitsilence = 0;
1325 #endif
1326         int avgtone = 0, hittone = 0;
1327
1328         /* if we have a 4 length pattern, the way busymaybe is set doesn't help us. */
1329         if (dsp->busy_cadence.length != 4) {
1330                 if (!dsp->busymaybe) {
1331                         return res;
1332                 }
1333         }
1334
1335         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1336 #ifndef BUSYDETECT_TONEONLY
1337                 avgsilence += dsp->historicsilence[x];
1338 #endif
1339                 avgtone += dsp->historicnoise[x];
1340         }
1341 #ifndef BUSYDETECT_TONEONLY
1342         avgsilence /= dsp->busycount;
1343 #endif
1344         avgtone /= dsp->busycount;
1345         for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1346 #ifndef BUSYDETECT_TONEONLY
1347                 if (avgsilence > dsp->historicsilence[x]) {
1348                         if (avgsilence - (avgsilence * BUSY_PERCENT / 100) <= dsp->historicsilence[x]) {
1349                                 hitsilence++;
1350                         }
1351                 } else {
1352                         if (avgsilence + (avgsilence * BUSY_PERCENT / 100) >= dsp->historicsilence[x]) {
1353                                 hitsilence++;
1354                         }
1355                 }
1356 #endif
1357                 if (avgtone > dsp->historicnoise[x]) {
1358                         if (avgtone - (avgtone * BUSY_PERCENT / 100) <= dsp->historicnoise[x]) {
1359                                 hittone++;
1360                         }
1361                 } else {
1362                         if (avgtone + (avgtone * BUSY_PERCENT / 100) >= dsp->historicnoise[x]) {
1363                                 hittone++;
1364                         }
1365                 }
1366         }
1367 #ifndef BUSYDETECT_TONEONLY
1368         if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) && 
1369             (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) && 
1370             (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1371 #else
1372         if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1373 #endif
1374 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1375                 if (avgtone > avgsilence) {
1376                         if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence) {
1377                                 res = 1;
1378                         }
1379                 } else {
1380                         if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence) {
1381                                 res = 1;
1382                         }
1383                 }
1384 #else
1385                 res = 1;
1386 #endif
1387         }
1388
1389         /* If we have a 4-length pattern, we can go ahead and just check it in a different way. */
1390         if (dsp->busy_cadence.length == 4) {
1391                 int x;
1392                 int errors = 0;
1393                 int errors_max = ((4 * dsp->busycount) / 100.0) * BUSY_PAT_PERCENT;
1394
1395                 for (x = DSP_HISTORY - (dsp->busycount); x < DSP_HISTORY; x += 2) {
1396                         int temp_error;
1397                         temp_error = abs(dsp->historicnoise[x] - dsp->busy_cadence.pattern[0]);
1398                         if ((temp_error * 100) / dsp->busy_cadence.pattern[0] > BUSY_PERCENT) {
1399                                 errors++;
1400                         }
1401
1402                         temp_error = abs(dsp->historicnoise[x + 1] - dsp->busy_cadence.pattern[2]);
1403                         if ((temp_error * 100) / dsp->busy_cadence.pattern[2] > BUSY_PERCENT) {
1404                                 errors++;
1405                         }
1406
1407                         temp_error = abs(dsp->historicsilence[x] - dsp->busy_cadence.pattern[1]);
1408                         if ((temp_error * 100) / dsp->busy_cadence.pattern[1] > BUSY_PERCENT) {
1409                                 errors++;
1410                         }
1411
1412                         temp_error = abs(dsp->historicsilence[x + 1] - dsp->busy_cadence.pattern[3]);
1413                         if ((temp_error * 100) / dsp->busy_cadence.pattern[3] > BUSY_PERCENT) {
1414                                 errors++;
1415                         }
1416                 }
1417
1418                 ast_debug(5, "errors = %d  max = %d\n", errors, errors_max);
1419
1420                 if (errors <= errors_max) {
1421                         return 1;
1422                 }
1423         }
1424
1425         /* If we know the expected busy tone length, check we are in the range */
1426         if (res && (dsp->busy_cadence.pattern[0] > 0)) {
1427                 if (abs(avgtone - dsp->busy_cadence.pattern[0]) > MAX(dsp->busy_cadence.pattern[0]*BUSY_PAT_PERCENT/100, 20)) {
1428 #ifdef BUSYDETECT_DEBUG
1429                         ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
1430                                 avgtone, dsp->busy_cadence.pattern[0]);
1431 #endif
1432                         res = 0;
1433                 }
1434         }
1435 #ifndef BUSYDETECT_TONEONLY
1436         /* If we know the expected busy tone silent-period length, check we are in the range */
1437         if (res && (dsp->busy_cadence.pattern[1] > 0)) {
1438                 if (abs(avgsilence - dsp->busy_cadence.pattern[1]) > MAX(dsp->busy_cadence.pattern[1]*BUSY_PAT_PERCENT/100, 20)) {
1439 #ifdef BUSYDETECT_DEBUG
1440                 ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
1441                         avgsilence, dsp->busy_cadence.pattern[1]);
1442 #endif
1443                         res = 0;
1444                 }
1445         }
1446 #endif
1447 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
1448         if (res) {
1449                 ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1450         } else {
1451                 ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1452         }
1453 #endif
1454         return res;
1455 }
1456
1457 static int ast_dsp_silence_noise_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *total, int *frames_energy, int noise)
1458 {
1459         short *s;
1460         int len;
1461         int x;
1462         unsigned char *odata;
1463
1464         if (!f) {
1465                 return 0;
1466         }
1467
1468         if (f->frametype != AST_FRAME_VOICE) {
1469                 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1470                 return 0;
1471         }
1472         if (!ast_format_is_slinear(&f->subclass.format)) {
1473                 odata = f->data.ptr;
1474                 len = f->datalen;
1475                 switch (f->subclass.format.id) {
1476                         case AST_FORMAT_ULAW:
1477                                 s = alloca(len * 2);
1478                                 for (x = 0;x < len; x++) {
1479                                         s[x] = AST_MULAW(odata[x]);
1480                                 }
1481                                 break;
1482                         case AST_FORMAT_ALAW:
1483                                 s = alloca(len * 2);
1484                                 for (x = 0;x < len; x++) {
1485                                         s[x] = AST_ALAW(odata[x]);
1486                                 }
1487                                 break;
1488                         default:
1489                                 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear, alaw or ulaw frames :(\n");
1490                         return 0;
1491                 }
1492         } else {
1493                 s = f->data.ptr;
1494                 len = f->datalen/2;
1495         }
1496         if (noise) {
1497                 return __ast_dsp_silence_noise(dsp, s, len, NULL, total, frames_energy);
1498         } else {
1499                 return __ast_dsp_silence_noise(dsp, s, len, total, NULL, frames_energy);
1500         }
1501 }
1502
1503 int ast_dsp_silence_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence, int *frames_energy)
1504 {
1505         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, frames_energy, 0);
1506 }
1507
1508 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1509 {
1510         return ast_dsp_silence_noise_with_energy(dsp, f, totalsilence, NULL, 0);
1511 }
1512
1513 int ast_dsp_noise(struct ast_dsp *dsp, struct ast_frame *f, int *totalnoise)
1514 {
1515         return ast_dsp_silence_noise_with_energy(dsp, f, totalnoise, NULL, 1);
1516 }
1517
1518
1519 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1520 {
1521         int silence;
1522         int res;
1523         int digit = 0, fax_digit = 0;
1524         int x;
1525         short *shortdata;
1526         unsigned char *odata;
1527         int len;
1528         struct ast_frame *outf = NULL;
1529
1530         if (!af) {
1531                 return NULL;
1532         }
1533         if (af->frametype != AST_FRAME_VOICE) {
1534                 return af;
1535         }
1536
1537         odata = af->data.ptr;
1538         len = af->datalen;
1539         /* Make sure we have short data */
1540         if (ast_format_is_slinear(&af->subclass.format)) {
1541                 shortdata = af->data.ptr;
1542                 len = af->datalen / 2;
1543         } else {
1544                 switch (af->subclass.format.id) {
1545                 case AST_FORMAT_ULAW:
1546                 case AST_FORMAT_TESTLAW:
1547                         shortdata = alloca(af->datalen * 2);
1548                         for (x = 0;x < len; x++) {
1549                                 shortdata[x] = AST_MULAW(odata[x]);
1550                         }
1551                         break;
1552                 case AST_FORMAT_ALAW:
1553                         shortdata = alloca(af->datalen * 2);
1554                         for (x = 0; x < len; x++) {
1555                                 shortdata[x] = AST_ALAW(odata[x]);
1556                         }
1557                         break;
1558                 default:
1559                         /*Display warning only once. Otherwise you would get hundreds of warnings every second */
1560                         if (dsp->display_inband_dtmf_warning)
1561                                 ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(&af->subclass.format));
1562                         dsp->display_inband_dtmf_warning = 0;
1563                         return af;
1564                 }
1565         }
1566
1567         /* Initially we do not want to mute anything */
1568         dsp->mute_fragments = 0;
1569
1570         /* Need to run the silence detection stuff for silence suppression and busy detection */
1571         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) || (dsp->features & DSP_FEATURE_BUSY_DETECT)) {
1572                 res = __ast_dsp_silence_noise(dsp, shortdata, len, &silence, NULL, NULL);
1573         }
1574
1575         if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1576                 memset(&dsp->f, 0, sizeof(dsp->f));
1577                 dsp->f.frametype = AST_FRAME_NULL;
1578                 ast_frfree(af);
1579                 return ast_frisolate(&dsp->f);
1580         }
1581         if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1582                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1583                 memset(&dsp->f, 0, sizeof(dsp->f));
1584                 dsp->f.frametype = AST_FRAME_CONTROL;
1585                 dsp->f.subclass.integer = AST_CONTROL_BUSY;
1586                 ast_frfree(af);
1587                 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", chan->name);
1588                 return ast_frisolate(&dsp->f);
1589         }
1590
1591         if ((dsp->features & DSP_FEATURE_FAX_DETECT)) {
1592                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CNG) && tone_detect(dsp, &dsp->cng_tone_state, shortdata, len)) {
1593                         fax_digit = 'f';
1594                 }
1595
1596                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CED) && tone_detect(dsp, &dsp->ced_tone_state, shortdata, len)) {
1597                         fax_digit = 'e';
1598                 }
1599
1600                 if ((dsp->faxmode & DSP_FAXMODE_DETECT_V21) && v21_detect(dsp, &dsp->v21_state, shortdata, len)) {
1601                         fax_digit = 'g';
1602                 }
1603         }
1604
1605         if (dsp->features & (DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_BUSY_DETECT)) {
1606                 if (dsp->digitmode & DSP_DIGITMODE_MF)
1607                         digit = mf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1608                 else
1609                         digit = dtmf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1610
1611                 if (dsp->digit_state.current_digits) {
1612                         int event = 0, event_len = 0;
1613                         char event_digit = 0;
1614
1615                         if (!dsp->dtmf_began) {
1616                                 /* We have not reported DTMF_BEGIN for anything yet */
1617
1618                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1619                                         event = AST_FRAME_DTMF_BEGIN;
1620                                         event_digit = dsp->digit_state.digits[0];
1621                                 }
1622                                 dsp->dtmf_began = 1;
1623
1624                         } else if (dsp->digit_state.current_digits > 1 || digit != dsp->digit_state.digits[0]) {
1625                                 /* Digit changed. This means digit we have reported with DTMF_BEGIN ended */
1626                                 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1627                                         event = AST_FRAME_DTMF_END;
1628                                         event_digit = dsp->digit_state.digits[0];
1629                                         event_len = dsp->digit_state.digitlen[0] * 1000 / dsp->sample_rate;
1630                                 }
1631                                 memmove(&dsp->digit_state.digits[0], &dsp->digit_state.digits[1], dsp->digit_state.current_digits);
1632                                 memmove(&dsp->digit_state.digitlen[0], &dsp->digit_state.digitlen[1], dsp->digit_state.current_digits * sizeof(dsp->digit_state.digitlen[0]));
1633                                 dsp->digit_state.current_digits--;
1634                                 dsp->dtmf_began = 0;
1635
1636                                 if (dsp->features & DSP_FEATURE_BUSY_DETECT) {
1637                                         /* Reset Busy Detector as we have some confirmed activity */ 
1638                                         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1639                                         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1640                                         ast_debug(1, "DTMF Detected - Reset busydetector\n");
1641                                 }
1642                         }
1643
1644                         if (event) {
1645                                 memset(&dsp->f, 0, sizeof(dsp->f));
1646                                 dsp->f.frametype = event;
1647                                 dsp->f.subclass.integer = event_digit;
1648                                 dsp->f.len = event_len;
1649                                 outf = &dsp->f;
1650                                 goto done;
1651                         }
1652                 }
1653         }
1654
1655         if (fax_digit) {
1656                 /* Fax was detected - digit is either 'f' or 'e' */
1657
1658                 memset(&dsp->f, 0, sizeof(dsp->f));
1659                 dsp->f.frametype = AST_FRAME_DTMF;
1660                 dsp->f.subclass.integer = fax_digit;
1661                 outf = &dsp->f;
1662                 goto done;
1663         }
1664
1665         if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1666                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1667                 if (res) {
1668                         switch (res) {
1669                         case AST_CONTROL_ANSWER:
1670                         case AST_CONTROL_BUSY:
1671                         case AST_CONTROL_RINGING:
1672                         case AST_CONTROL_CONGESTION:
1673                         case AST_CONTROL_HANGUP:
1674                                 memset(&dsp->f, 0, sizeof(dsp->f));
1675                                 dsp->f.frametype = AST_FRAME_CONTROL;
1676                                 dsp->f.subclass.integer = res;
1677                                 dsp->f.src = "dsp_progress";
1678                                 if (chan) 
1679                                         ast_queue_frame(chan, &dsp->f);
1680                                 break;
1681                         default:
1682                                 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1683                         }
1684                 }
1685         } else if ((dsp->features & DSP_FEATURE_WAITDIALTONE)) {
1686                 res = __ast_dsp_call_progress(dsp, shortdata, len);
1687         }
1688
1689 done:
1690         /* Mute fragment of the frame */
1691         for (x = 0; x < dsp->mute_fragments; x++) {
1692                 memset(shortdata + dsp->mute_data[x].start, 0, sizeof(int16_t) * (dsp->mute_data[x].end - dsp->mute_data[x].start));
1693         }
1694
1695         switch (af->subclass.format.id) {
1696         case AST_FORMAT_ULAW:
1697                 for (x = 0; x < len; x++) {
1698                         odata[x] = AST_LIN2MU((unsigned short) shortdata[x]);
1699                 }
1700                 break;
1701         case AST_FORMAT_ALAW:
1702                 for (x = 0; x < len; x++) {
1703                         odata[x] = AST_LIN2A((unsigned short) shortdata[x]);
1704                 }
1705                 /* fall through */
1706         default:
1707                 break;
1708         }
1709
1710         if (outf) {
1711                 if (chan) {
1712                         ast_queue_frame(chan, af);
1713                 }
1714                 ast_frfree(af);
1715                 return ast_frisolate(outf);
1716         } else {
1717                 return af;
1718         }
1719 }
1720
1721 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1722 {
1723         int max = 0;
1724         int x;
1725         
1726         dsp->gsamp_size = modes[dsp->progmode].size;
1727         dsp->gsamps = 0;
1728         for (x = 0; x < ARRAY_LEN(modes[dsp->progmode].freqs); x++) {
1729                 if (modes[dsp->progmode].freqs[x]) {
1730                         goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->gsamp_size, dsp->sample_rate);
1731                         max = x + 1;
1732                 }
1733         }
1734         dsp->freqcount = max;
1735         dsp->ringtimeout= 0;
1736 }
1737
1738 unsigned int ast_dsp_get_sample_rate(const struct ast_dsp *dsp)
1739 {
1740         return dsp->sample_rate;
1741 }
1742
1743 static struct ast_dsp *__ast_dsp_new(unsigned int sample_rate)
1744 {
1745         struct ast_dsp *dsp;
1746         
1747         if ((dsp = ast_calloc(1, sizeof(*dsp)))) {              
1748                 dsp->threshold = DEFAULT_THRESHOLD;
1749                 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1750                 dsp->busycount = DSP_HISTORY;
1751                 dsp->digitmode = DSP_DIGITMODE_DTMF;
1752                 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1753                 dsp->sample_rate = sample_rate;
1754                 /* Initialize digit detector */
1755                 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF, dsp->sample_rate);
1756                 dsp->display_inband_dtmf_warning = 1;
1757                 /* Initialize initial DSP progress detect parameters */
1758                 ast_dsp_prog_reset(dsp);
1759                 /* Initialize fax detector */
1760                 ast_fax_detect_init(dsp);
1761         }
1762         return dsp;
1763 }
1764
1765 struct ast_dsp *ast_dsp_new(void)
1766 {
1767         return __ast_dsp_new(DEFAULT_SAMPLE_RATE);
1768 }
1769
1770 struct ast_dsp *ast_dsp_new_with_rate(unsigned int sample_rate)
1771 {
1772         return __ast_dsp_new(sample_rate);
1773 }
1774
1775 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1776 {
1777         dsp->features = features;
1778         if (!(features & DSP_FEATURE_DIGIT_DETECT)) {
1779                 dsp->display_inband_dtmf_warning = 0;
1780         }
1781 }
1782
1783 void ast_dsp_free(struct ast_dsp *dsp)
1784 {
1785         ast_free(dsp);
1786 }
1787
1788 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1789 {
1790         dsp->threshold = threshold;
1791 }
1792
1793 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1794 {
1795         if (cadences < 4) {
1796                 cadences = 4;
1797         }
1798         if (cadences > DSP_HISTORY) {
1799                 cadences = DSP_HISTORY;
1800         }
1801         dsp->busycount = cadences;
1802 }
1803
1804 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, const struct ast_dsp_busy_pattern *cadence)
1805 {
1806         dsp->busy_cadence = *cadence;
1807         ast_debug(1, "dsp busy pattern set to %d,%d,%d,%d\n", cadence->pattern[0], cadence->pattern[1], (cadence->length == 4) ? cadence->pattern[2] : 0, (cadence->length == 4) ? cadence->pattern[3] : 0);
1808 }
1809
1810 void ast_dsp_digitreset(struct ast_dsp *dsp)
1811 {
1812         int i;
1813         
1814         dsp->dtmf_began = 0;
1815         if (dsp->digitmode & DSP_DIGITMODE_MF) {
1816                 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1817                 /* Reinitialise the detector for the next block */
1818                 for (i = 0;  i < 6;  i++) {
1819                         goertzel_reset(&s->tone_out[i]);
1820                 }
1821                 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = s->current_hit = 0;
1822                 s->current_sample = 0;
1823         } else {
1824                 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1825                 /* Reinitialise the detector for the next block */
1826                 for (i = 0;  i < 4;  i++) {
1827                         goertzel_reset(&s->row_out[i]);
1828                         goertzel_reset(&s->col_out[i]);
1829                 }
1830                 s->lasthit = s->current_hit = 0;
1831                 s->energy = 0.0;
1832                 s->current_sample = 0;
1833                 s->hits = 0;
1834                 s->misses = 0;
1835         }
1836
1837         dsp->digit_state.digits[0] = '\0';
1838         dsp->digit_state.current_digits = 0;
1839 }
1840
1841 void ast_dsp_reset(struct ast_dsp *dsp)
1842 {
1843         int x;
1844         
1845         dsp->totalsilence = 0;
1846         dsp->gsamps = 0;
1847         for (x = 0; x < 4; x++) {
1848                 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1849         }
1850         memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1851         memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));      
1852         dsp->ringtimeout= 0;
1853 }
1854
1855 int ast_dsp_set_digitmode(struct ast_dsp *dsp, int digitmode)
1856 {
1857         int new;
1858         int old;
1859         
1860         old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1861         new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1862         if (old != new) {
1863                 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1864                 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF, dsp->sample_rate);
1865         }
1866         dsp->digitmode = digitmode;
1867         return 0;
1868 }
1869
1870 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1871 {
1872         if (dsp->faxmode != faxmode) {
1873                 dsp->faxmode = faxmode;
1874                 ast_fax_detect_init(dsp);
1875         }
1876         return 0;
1877 }
1878
1879 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1880 {
1881         int x;
1882         
1883         for (x = 0; x < ARRAY_LEN(aliases); x++) {
1884                 if (!strcasecmp(aliases[x].name, zone)) {
1885                         dsp->progmode = aliases[x].mode;
1886                         ast_dsp_prog_reset(dsp);
1887                         return 0;
1888                 }
1889         }
1890         return -1;
1891 }
1892
1893 int ast_dsp_was_muted(struct ast_dsp *dsp)
1894 {
1895         return (dsp->mute_fragments > 0);
1896 }
1897
1898 int ast_dsp_get_tstate(struct ast_dsp *dsp) 
1899 {
1900         return dsp->tstate;
1901 }
1902
1903 int ast_dsp_get_tcount(struct ast_dsp *dsp) 
1904 {
1905         return dsp->tcount;
1906 }
1907
1908 static int _dsp_init(int reload)
1909 {
1910         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1911         struct ast_config *cfg;
1912
1913         cfg = ast_config_load2(CONFIG_FILE_NAME, "dsp", config_flags);
1914         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
1915                 ast_verb(5, "Can't find dsp config file %s. Assuming default silencethreshold of %d.\n", CONFIG_FILE_NAME, DEFAULT_SILENCE_THRESHOLD);
1916                 thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1917                 return 0;
1918         }
1919
1920         if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
1921                 return 0;
1922         }
1923
1924         if (cfg) {
1925                 const char *value;
1926
1927                 value = ast_variable_retrieve(cfg, "default", "silencethreshold");
1928                 if (value && sscanf(value, "%30d", &thresholds[THRESHOLD_SILENCE]) != 1) {
1929                         ast_verb(5, "%s: '%s' is not a valid silencethreshold value\n", CONFIG_FILE_NAME, value);
1930                         thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1931                 } else if (!value) {
1932                         thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1933                 }
1934
1935                 ast_config_destroy(cfg);
1936         }
1937         return 0;
1938 }
1939
1940 int ast_dsp_get_threshold_from_settings(enum threshold which)
1941 {
1942         return thresholds[which];
1943 }
1944
1945 int ast_dsp_init(void)
1946 {
1947         return _dsp_init(0);
1948 }
1949
1950 int ast_dsp_reload(void)
1951 {
1952         return _dsp_init(1);
1953 }
1954