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