2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * Goertzel routines are borrowed from Steve Underwood's tremendous work on the
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.
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.
24 * \brief Convenience Signal Processing routines
26 * \author Mark Spencer <markster@digium.com>
27 * \author Steve Underwood <steveu@coppice.org>
30 /* Some routines from tone_detect.c by Steven Underwood as published under the zapata library */
32 tone_detect.c - General telephony tone detection, and specific
35 Copyright (C) 2001 Steve Underwood <steveu@coppice.org>
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
45 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
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"
58 /*! Number of goertzels for progress detect */
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 */
81 /*! For CR/BR modes */
90 static struct progalias {
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 },
101 static struct progress {
102 enum gsamp_size size;
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 */
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
117 #define DEFAULT_THRESHOLD 512
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 */
127 /*! Remember last 15 units */
128 #define DSP_HISTORY 15
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 */
133 /*! All THRESH_XXX values are in GSAMP_SIZE chunks (us = 22ms) */
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) */
143 #define MAX_DTMF_DIGITS 128
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
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 */
162 #define DTMF_REVERSE_TWIST (relax ? 6.5 : 2.5) /* 4dB normal */
164 #define DTMF_REVERSE_TWIST (relax ? 4.0 : 2.5) /* 4dB normal */
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
172 #define BELL_MF_THRESHOLD 1.6e9
173 #define BELL_MF_TWIST 4.0 /* 6dB */
174 #define BELL_MF_RELATIVE_PEAK 12.6 /* 11dB */
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
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.
183 #define FAX_TONE_CNG_FREQ 1100
184 #define FAX_TONE_CNG_DURATION 500
185 #define FAX_TONE_CNG_DB 16
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.
191 #define FAX_TONE_CED_FREQ 2100
192 #define FAX_TONE_CED_DURATION 2600
193 #define FAX_TONE_CED_DB 16
195 #define DEFAULT_SAMPLE_RATE 8000
197 /* MF goertzel size */
200 /* DTMF goertzel size */
201 #define DTMF_GSIZE 102
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
209 * \brief The default silence threshold we will use if an alternate
210 * configured value is not present or is invalid.
212 static const int DEFAULT_SILENCE_THRESHOLD = 256;
214 #define CONFIG_FILE_NAME "dsp.conf"
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 */
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 */
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 */
245 } tone_detect_state_t;
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 */
254 float threshold; /* Energy of the tone relative to energy from all other signals to consider a hit */
259 } v21_detect_state_t;
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 */
274 } dtmf_detect_state_t;
278 goertzel_state_t tone_out[6];
287 char digits[MAX_DTMF_DIGITS + 1];
288 int digitlen[MAX_DTMF_DIGITS + 1];
294 dtmf_detect_state_t dtmf;
295 mf_detect_state_t mf;
297 } digit_detect_state_t;
299 static const float dtmf_row[] = {
300 697.0, 770.0, 852.0, 941.0
302 static const float dtmf_col[] = {
303 1209.0, 1336.0, 1477.0, 1633.0
305 static const float mf_tones[] = {
306 700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
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];
312 static inline void goertzel_sample(goertzel_state_t *s, short sample)
319 s->v3 = (s->fac * s->v2) >> 15;
320 s->v3 = s->v3 - v1 + (sample >> s->chunky);
321 if (abs(s->v3) > 32768) {
329 static inline void goertzel_update(goertzel_state_t *s, short *samps, int count)
333 for (i = 0; i < count; i++) {
334 goertzel_sample(s, samps[i]);
339 static inline float goertzel_result(goertzel_state_t *s)
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);
348 static inline void goertzel_init(goertzel_state_t *s, float freq, int samples, unsigned int sample_rate)
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;
355 static inline void goertzel_reset(goertzel_state_t *s)
357 s->v2 = s->v3 = s->chunky = 0.0;
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.
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.
387 struct ast_dsp_busy_pattern busy_cadence;
388 int historicnoise[DSP_HISTORY];
389 int historicsilence[DSP_HISTORY];
390 goertzel_state_t freqs[7];
393 enum gsamp_size gsamp_size;
394 enum prog_mode progmode;
400 int display_inband_dtmf_warning;
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;
411 static void mute_fragment(struct ast_dsp *dsp, fragment_t *fragment)
413 if (dsp->mute_fragments >= ARRAY_LEN(dsp->mute_data)) {
414 ast_log(LOG_ERROR, "Too many fragments to mute. Ignoring\n");
418 dsp->mute_data[dsp->mute_fragments++] = *fragment;
421 static void ast_tone_detect_init(tone_detect_state_t *s, int freq, int duration, int amp, unsigned int sample_rate)
423 int duration_samples;
425 int periods_in_block;
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;
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;
439 periods_in_block = s->block_size * freq / sample_rate;
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;
447 /* Now calculate final block size. It will contain integer number of periods */
448 s->block_size = periods_in_block * sample_rate / freq;
450 /* tone_detect is currently only used to detect fax tones and we
451 do not need suqlching the fax tones */
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;
458 goertzel_init(&s->tone, freq, s->block_size, sample_rate);
460 s->samples_pending = s->block_size;
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
475 x = pow(10.0, amp / 10.0);
476 s->threshold = x / (x + 1);
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);
481 static void ast_v21_detect_init(v21_detect_state_t *s, unsigned int sample_rate)
484 int periods_in_block;
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;
491 periods_in_block = s->block_size * 1850 / sample_rate;
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;
499 /* Now calculate final block size. It will contain integer number of periods */
500 s->block_size = periods_in_block * sample_rate / 1850;
502 goertzel_init(&s->tone, 1850.0, s->block_size, sample_rate);
504 s->samples_pending = s->block_size;
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
519 x = pow(10.0, 16 / 10.0);
520 s->threshold = x / (x + 1);
522 ast_debug(1, "Setup v21 detector, block_size=%d\n", s->block_size);
525 static void ast_fax_detect_init(struct ast_dsp *s)
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);
532 static void ast_dtmf_detect_init (dtmf_detect_state_t *s, unsigned int sample_rate)
538 for (i = 0; i < 4; i++) {
539 goertzel_init(&s->row_out[i], dtmf_row[i], DTMF_GSIZE, sample_rate);
540 goertzel_init(&s->col_out[i], dtmf_col[i], DTMF_GSIZE, sample_rate);
543 s->current_sample = 0;
547 s->hits_to_begin = DTMF_HITS_TO_BEGIN;
548 s->misses_to_end = DTMF_MISSES_TO_END;
551 static void ast_mf_detect_init (mf_detect_state_t *s, unsigned int sample_rate)
554 s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
555 for (i = 0; i < 6; i++) {
556 goertzel_init (&s->tone_out[i], mf_tones[i], 160, sample_rate);
558 s->current_sample = 0;
562 static void ast_digit_detect_init(digit_detect_state_t *s, int mf, unsigned int sample_rate)
564 s->current_digits = 0;
565 s->detected_digits = 0;
570 ast_mf_detect_init(&s->td.mf, sample_rate);
572 ast_dtmf_detect_init(&s->td.dtmf, sample_rate);
576 /*! \brief Detect a v21 preamble.
577 * This code is derived from the tone_detect code and detects a pattern of 1850
578 * Hz tone found in a v21 preamble.
580 static int v21_detect(struct ast_dsp *dsp, v21_detect_state_t *s, int16_t *amp, int samples)
590 for (start = 0; start < samples; start = end) {
591 /* Process in blocks. */
592 limit = samples - start;
593 if (limit > s->samples_pending) {
594 limit = s->samples_pending;
598 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
599 /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
600 s->energy += (int32_t) *ptr * (int32_t) *ptr;
602 goertzel_sample(&s->tone, *ptr);
605 s->samples_pending -= limit;
607 if (s->samples_pending) {
608 /* Finished incomplete (last) block */
612 tone_energy = goertzel_result(&s->tone);
614 /* Scale to make comparable */
616 s->energy *= s->block_size;
618 ast_debug(10, "v21 1850 Ew=%.2E, Et=%.2E, s/n=%10.2f\n", tone_energy, s->energy, tone_energy / (s->energy - tone_energy));
621 if (tone_energy > s->energy * s->threshold) {
622 ast_debug(10, "Hit! count=%d; miss_count=%d\n", s->hit_count, s->miss_count);
627 if (s->miss_count == 3) {
636 if (s->miss_count > 3) {
641 if (s->hit_count == 4) {
642 ast_debug(1, "v21 preamble detected\n");
646 /* Reinitialise the detector for the next block */
647 goertzel_reset(&s->tone);
649 /* Advance to the next block */
651 s->samples_pending = s->block_size;
659 static int tone_detect(struct ast_dsp *dsp, tone_detect_state_t *s, int16_t *amp, int samples)
668 fragment_t mute = {0, 0};
670 if (s->squelch && s->mute_samples > 0) {
671 mute.end = (s->mute_samples < samples) ? s->mute_samples : samples;
672 s->mute_samples -= mute.end;
675 for (start = 0; start < samples; start = end) {
676 /* Process in blocks. */
677 limit = samples - start;
678 if (limit > s->samples_pending) {
679 limit = s->samples_pending;
683 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
684 /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
685 s->energy += (int32_t) *ptr * (int32_t) *ptr;
687 goertzel_sample(&s->tone, *ptr);
690 s->samples_pending -= limit;
692 if (s->samples_pending) {
693 /* Finished incomplete (last) block */
697 tone_energy = goertzel_result(&s->tone);
699 /* Scale to make comparable */
701 s->energy *= s->block_size;
703 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));
705 if (tone_energy > s->energy * s->threshold) {
706 ast_debug(10, "Hit! count=%d\n", s->hit_count);
714 if (hit == s->last_hit) {
716 /* Two successive misses. Tone ended */
718 } else if (!s->hit_count) {
724 if (s->hit_count == s->hits_required) {
725 ast_debug(1, "%d Hz done detected\n", s->freq);
731 /* If we had a hit in this block, include it into mute fragment */
732 if (s->squelch && hit) {
733 if (mute.end < start - s->block_size) {
734 /* There is a gap between fragments */
735 mute_fragment(dsp, &mute);
736 mute.start = (start > s->block_size) ? (start - s->block_size) : 0;
738 mute.end = end + s->block_size;
741 /* Reinitialise the detector for the next block */
742 /* Reset for the next block */
743 goertzel_reset(&s->tone);
745 /* Advance to the next block */
747 s->samples_pending = s->block_size;
752 if (s->squelch && mute.end) {
753 if (mute.end > samples) {
754 s->mute_samples = mute.end - samples;
757 mute_fragment(dsp, &mute);
763 static void store_digit(digit_detect_state_t *s, char digit)
765 s->detected_digits++;
766 if (s->current_digits < MAX_DTMF_DIGITS) {
767 s->digitlen[s->current_digits] = 0;
768 s->digits[s->current_digits++] = digit;
769 s->digits[s->current_digits] = '\0';
771 ast_log(LOG_WARNING, "Digit lost due to full buffer\n");
776 static int dtmf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[], int samples, int squelch, int relax)
788 fragment_t mute = {0, 0};
790 if (squelch && s->td.dtmf.mute_samples > 0) {
791 mute.end = (s->td.dtmf.mute_samples < samples) ? s->td.dtmf.mute_samples : samples;
792 s->td.dtmf.mute_samples -= mute.end;
796 for (sample = 0; sample < samples; sample = limit) {
797 /* DTMF_GSIZE is optimised to meet the DTMF specs. */
798 if ((samples - sample) >= (DTMF_GSIZE - s->td.dtmf.current_sample)) {
799 limit = sample + (DTMF_GSIZE - s->td.dtmf.current_sample);
803 /* The following unrolled loop takes only 35% (rough estimate) of the
804 time of a rolled loop on the machine on which it was developed */
805 for (j = sample; j < limit; j++) {
807 s->td.dtmf.energy += famp*famp;
808 /* With GCC 2.95, the following unrolled code seems to take about 35%
809 (rough estimate) as long as a neat little 0-3 loop */
810 goertzel_sample(s->td.dtmf.row_out, amp[j]);
811 goertzel_sample(s->td.dtmf.col_out, amp[j]);
812 goertzel_sample(s->td.dtmf.row_out + 1, amp[j]);
813 goertzel_sample(s->td.dtmf.col_out + 1, amp[j]);
814 goertzel_sample(s->td.dtmf.row_out + 2, amp[j]);
815 goertzel_sample(s->td.dtmf.col_out + 2, amp[j]);
816 goertzel_sample(s->td.dtmf.row_out + 3, amp[j]);
817 goertzel_sample(s->td.dtmf.col_out + 3, amp[j]);
819 s->td.dtmf.current_sample += (limit - sample);
820 if (s->td.dtmf.current_sample < DTMF_GSIZE) {
823 /* We are at the end of a DTMF detection block */
824 /* Find the peak row and the peak column */
825 row_energy[0] = goertzel_result (&s->td.dtmf.row_out[0]);
826 col_energy[0] = goertzel_result (&s->td.dtmf.col_out[0]);
828 for (best_row = best_col = 0, i = 1; i < 4; i++) {
829 row_energy[i] = goertzel_result (&s->td.dtmf.row_out[i]);
830 if (row_energy[i] > row_energy[best_row]) {
833 col_energy[i] = goertzel_result (&s->td.dtmf.col_out[i]);
834 if (col_energy[i] > col_energy[best_col]) {
839 /* Basic signal level test and the twist test */
840 if (row_energy[best_row] >= DTMF_THRESHOLD &&
841 col_energy[best_col] >= DTMF_THRESHOLD &&
842 col_energy[best_col] < row_energy[best_row] * DTMF_REVERSE_TWIST &&
843 col_energy[best_col] * DTMF_NORMAL_TWIST > row_energy[best_row]) {
844 /* Relative peak test */
845 for (i = 0; i < 4; i++) {
846 if ((i != best_col &&
847 col_energy[i] * DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
849 && row_energy[i] * DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
853 /* ... and fraction of total energy test */
855 (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY * s->td.dtmf.energy) {
857 hit = dtmf_positions[(best_row << 2) + best_col];
861 if (s->td.dtmf.current_hit) {
862 /* We are in the middle of a digit already */
863 if (hit != s->td.dtmf.current_hit) {
865 if (s->td.dtmf.misses == s->td.dtmf.misses_to_end) {
866 /* There were enough misses to consider digit ended */
867 s->td.dtmf.current_hit = 0;
870 s->td.dtmf.misses = 0;
871 /* Current hit was same as last, so increment digit duration (of last digit) */
872 s->digitlen[s->current_digits - 1] += DTMF_GSIZE;
876 /* Look for a start of a new digit no matter if we are already in the middle of some
877 digit or not. This is because hits_to_begin may be smaller than misses_to_end
878 and we may find begin of new digit before we consider last one ended. */
880 if (hit == s->td.dtmf.lasthit) {
886 if (s->td.dtmf.hits == s->td.dtmf.hits_to_begin && hit != s->td.dtmf.current_hit) {
888 s->td.dtmf.current_hit = hit;
889 s->td.dtmf.misses = 0;
895 s->td.dtmf.lasthit = hit;
897 /* If we had a hit in this block, include it into mute fragment */
898 if (squelch && hit) {
899 if (mute.end < sample - DTMF_GSIZE) {
900 /* There is a gap between fragments */
901 mute_fragment(dsp, &mute);
902 mute.start = (sample > DTMF_GSIZE) ? (sample - DTMF_GSIZE) : 0;
904 mute.end = limit + DTMF_GSIZE;
907 /* Reinitialise the detector for the next block */
908 for (i = 0; i < 4; i++) {
909 goertzel_reset(&s->td.dtmf.row_out[i]);
910 goertzel_reset(&s->td.dtmf.col_out[i]);
912 s->td.dtmf.energy = 0.0;
913 s->td.dtmf.current_sample = 0;
916 if (squelch && mute.end) {
917 if (mute.end > samples) {
918 s->td.dtmf.mute_samples = mute.end - samples;
921 mute_fragment(dsp, &mute);
924 return (s->td.dtmf.current_hit); /* return the debounced hit */
927 static int mf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[],
928 int samples, int squelch, int relax)
938 fragment_t mute = {0, 0};
940 if (squelch && s->td.mf.mute_samples > 0) {
941 mute.end = (s->td.mf.mute_samples < samples) ? s->td.mf.mute_samples : samples;
942 s->td.mf.mute_samples -= mute.end;
946 for (sample = 0; sample < samples; sample = limit) {
947 /* 80 is optimised to meet the MF specs. */
948 /* XXX So then why is MF_GSIZE defined as 120? */
949 if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample)) {
950 limit = sample + (MF_GSIZE - s->td.mf.current_sample);
954 /* The following unrolled loop takes only 35% (rough estimate) of the
955 time of a rolled loop on the machine on which it was developed */
956 for (j = sample; j < limit; j++) {
957 /* With GCC 2.95, the following unrolled code seems to take about 35%
958 (rough estimate) as long as a neat little 0-3 loop */
959 goertzel_sample(s->td.mf.tone_out, amp[j]);
960 goertzel_sample(s->td.mf.tone_out + 1, amp[j]);
961 goertzel_sample(s->td.mf.tone_out + 2, amp[j]);
962 goertzel_sample(s->td.mf.tone_out + 3, amp[j]);
963 goertzel_sample(s->td.mf.tone_out + 4, amp[j]);
964 goertzel_sample(s->td.mf.tone_out + 5, amp[j]);
966 s->td.mf.current_sample += (limit - sample);
967 if (s->td.mf.current_sample < MF_GSIZE) {
970 /* We're at the end of an MF detection block. */
971 /* Find the two highest energies. The spec says to look for
972 two tones and two tones only. Taking this literally -ie
973 only two tones pass the minimum threshold - doesn't work
974 well. The sinc function mess, due to rectangular windowing
975 ensure that! Find the two highest energies and ensure they
976 are considerably stronger than any of the others. */
977 energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
978 energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
979 if (energy[0] > energy[1]) {
987 for (i = 2; i < 6; i++) {
988 energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
989 if (energy[i] >= energy[best]) {
992 } else if (energy[i] >= energy[second_best]) {
996 /* Basic signal level and twist tests */
998 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
999 && energy[best] < energy[second_best]*BELL_MF_TWIST
1000 && energy[best] * BELL_MF_TWIST > energy[second_best]) {
1001 /* Relative peak test */
1003 for (i = 0; i < 6; i++) {
1004 if (i != best && i != second_best) {
1005 if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
1006 /* The best two are not clearly the best */
1014 /* Get the values into ascending order */
1015 if (second_best < best) {
1020 best = best * 5 + second_best - 1;
1021 hit = bell_mf_positions[best];
1022 /* Look for two successive similar results */
1023 /* The logic in the next test is:
1024 For KP we need 4 successive identical clean detects, with
1025 two blocks of something different preceeding it. For anything
1026 else we need two successive identical clean detects, with
1027 two blocks of something different preceeding it. */
1028 if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
1029 ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
1030 (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] &&
1031 hit != s->td.mf.hits[0]))) {
1032 store_digit(s, hit);
1037 if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
1038 /* Two successive block without a hit terminate current digit */
1039 s->td.mf.current_hit = 0;
1042 s->td.mf.hits[0] = s->td.mf.hits[1];
1043 s->td.mf.hits[1] = s->td.mf.hits[2];
1044 s->td.mf.hits[2] = s->td.mf.hits[3];
1045 s->td.mf.hits[3] = s->td.mf.hits[4];
1046 s->td.mf.hits[4] = hit;
1048 /* If we had a hit in this block, include it into mute fragment */
1049 if (squelch && hit) {
1050 if (mute.end < sample - MF_GSIZE) {
1051 /* There is a gap between fragments */
1052 mute_fragment(dsp, &mute);
1053 mute.start = (sample > MF_GSIZE) ? (sample - MF_GSIZE) : 0;
1055 mute.end = limit + DTMF_GSIZE;
1058 /* Reinitialise the detector for the next block */
1059 for (i = 0; i < 6; i++)
1060 goertzel_reset(&s->td.mf.tone_out[i]);
1061 s->td.mf.current_sample = 0;
1064 if (squelch && mute.end) {
1065 if (mute.end > samples) {
1066 s->td.mf.mute_samples = mute.end - samples;
1069 mute_fragment(dsp, &mute);
1072 return (s->td.mf.current_hit); /* return the debounced hit */
1075 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
1077 /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
1078 /* Make sure absolute levels are high enough */
1079 if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH)) {
1082 /* Amplify ignored stuff */
1086 /* Check first tone */
1087 if ((p1 < i1) || (p1 < i2) || (p1 < e)) {
1091 if ((p2 < i1) || (p2 < i2) || (p2 < e)) {
1094 /* Guess it's there... */
1098 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
1103 int newstate = DSP_TONE_STATE_SILENCE;
1106 /* Take the lesser of the number of samples we need and what we have */
1108 if (pass > dsp->gsamp_size - dsp->gsamps) {
1109 pass = dsp->gsamp_size - dsp->gsamps;
1111 for (x = 0; x < pass; x++) {
1112 for (y = 0; y < dsp->freqcount; y++) {
1113 goertzel_sample(&dsp->freqs[y], s[x]);
1115 dsp->genergy += s[x] * s[x];
1118 dsp->gsamps += pass;
1120 if (dsp->gsamps == dsp->gsamp_size) {
1122 for (y = 0; y < 7; y++) {
1123 hz[y] = goertzel_result(&dsp->freqs[y]);
1125 switch (dsp->progmode) {
1127 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
1128 newstate = DSP_TONE_STATE_BUSY;
1129 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
1130 newstate = DSP_TONE_STATE_RINGING;
1131 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
1132 newstate = DSP_TONE_STATE_DIALTONE;
1133 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
1134 newstate = DSP_TONE_STATE_SPECIAL1;
1135 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
1136 /* End of SPECIAL1 or middle of SPECIAL2 */
1137 if (dsp->tstate == DSP_TONE_STATE_SPECIAL1 || dsp->tstate == DSP_TONE_STATE_SPECIAL2) {
1138 newstate = DSP_TONE_STATE_SPECIAL2;
1140 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
1141 /* End of SPECIAL2 or middle of SPECIAL3 */
1142 if (dsp->tstate == DSP_TONE_STATE_SPECIAL2 || dsp->tstate == DSP_TONE_STATE_SPECIAL3) {
1143 newstate = DSP_TONE_STATE_SPECIAL3;
1145 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1146 newstate = DSP_TONE_STATE_TALKING;
1148 newstate = DSP_TONE_STATE_SILENCE;
1152 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
1153 newstate = DSP_TONE_STATE_RINGING;
1154 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
1155 newstate = DSP_TONE_STATE_TALKING;
1157 newstate = DSP_TONE_STATE_SILENCE;
1161 if (hz[HZ_400UK] > TONE_MIN_THRESH * TONE_THRESH) {
1162 newstate = DSP_TONE_STATE_HUNGUP;
1163 } else if (pair_there(hz[HZ_350UK], hz[HZ_440UK], hz[HZ_400UK], hz[HZ_400UK], dsp->genergy)) {
1164 newstate = DSP_TONE_STATE_DIALTONE;
1168 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
1170 if (newstate == dsp->tstate) {
1172 if (dsp->ringtimeout) {
1175 switch (dsp->tstate) {
1176 case DSP_TONE_STATE_RINGING:
1177 if ((dsp->features & DSP_PROGRESS_RINGING) &&
1178 (dsp->tcount == THRESH_RING)) {
1179 res = AST_CONTROL_RINGING;
1180 dsp->ringtimeout = 1;
1183 case DSP_TONE_STATE_BUSY:
1184 if ((dsp->features & DSP_PROGRESS_BUSY) &&
1185 (dsp->tcount == THRESH_BUSY)) {
1186 res = AST_CONTROL_BUSY;
1187 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1190 case DSP_TONE_STATE_TALKING:
1191 if ((dsp->features & DSP_PROGRESS_TALK) &&
1192 (dsp->tcount == THRESH_TALK)) {
1193 res = AST_CONTROL_ANSWER;
1194 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1197 case DSP_TONE_STATE_SPECIAL3:
1198 if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
1199 (dsp->tcount == THRESH_CONGESTION)) {
1200 res = AST_CONTROL_CONGESTION;
1201 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1204 case DSP_TONE_STATE_HUNGUP:
1205 if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
1206 (dsp->tcount == THRESH_HANGUP)) {
1207 res = AST_CONTROL_HANGUP;
1208 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1212 if (dsp->ringtimeout == THRESH_RING2ANSWER) {
1213 ast_debug(1, "Consider call as answered because of timeout after last ring\n");
1214 res = AST_CONTROL_ANSWER;
1215 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
1218 ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
1219 ast_debug(5, "Start state %d\n", newstate);
1220 dsp->tstate = newstate;
1224 /* Reset goertzel */
1225 for (x = 0; x < 7; x++) {
1226 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1236 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1238 if (inf->frametype != AST_FRAME_VOICE) {
1239 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1242 if (!ast_format_is_slinear(&inf->subclass.format)) {
1243 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1246 return __ast_dsp_call_progress(dsp, inf->data.ptr, inf->datalen / 2);
1249 static int __ast_dsp_silence_noise(struct ast_dsp *dsp, short *s, int len, int *totalsilence, int *totalnoise, int *frames_energy)
1259 for (x = 0; x < len; x++) {
1263 if (accum < dsp->threshold) {
1265 dsp->totalsilence += len / (dsp->sample_rate / 1000);
1266 if (dsp->totalnoise) {
1267 /* Move and save history */
1268 memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicnoise[0]));
1269 dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1270 /* we don't want to check for busydetect that frequently */
1275 dsp->totalnoise = 0;
1279 dsp->totalnoise += len / (dsp->sample_rate / 1000);
1280 if (dsp->totalsilence) {
1281 int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1282 int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1283 /* Move and save history */
1284 memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicsilence[0]));
1285 dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1286 /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1287 if (silence1 < silence2) {
1288 if (silence1 + silence1 * BUSY_PERCENT / 100 >= silence2) {
1294 if (silence1 - silence1 * BUSY_PERCENT / 100 <= silence2) {
1301 dsp->totalsilence = 0;
1304 *totalsilence = dsp->totalsilence;
1307 *totalnoise = dsp->totalnoise;
1309 if (frames_energy) {
1310 *frames_energy = accum;
1315 int ast_dsp_busydetect(struct ast_dsp *dsp)
1318 #ifndef BUSYDETECT_TONEONLY
1319 int avgsilence = 0, hitsilence = 0;
1321 int avgtone = 0, hittone = 0;
1323 /* if we have a 4 length pattern, the way busymaybe is set doesn't help us. */
1324 if (dsp->busy_cadence.length != 4) {
1325 if (!dsp->busymaybe) {
1330 for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1331 #ifndef BUSYDETECT_TONEONLY
1332 avgsilence += dsp->historicsilence[x];
1334 avgtone += dsp->historicnoise[x];
1336 #ifndef BUSYDETECT_TONEONLY
1337 avgsilence /= dsp->busycount;
1339 avgtone /= dsp->busycount;
1340 for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
1341 #ifndef BUSYDETECT_TONEONLY
1342 if (avgsilence > dsp->historicsilence[x]) {
1343 if (avgsilence - (avgsilence * BUSY_PERCENT / 100) <= dsp->historicsilence[x]) {
1347 if (avgsilence + (avgsilence * BUSY_PERCENT / 100) >= dsp->historicsilence[x]) {
1352 if (avgtone > dsp->historicnoise[x]) {
1353 if (avgtone - (avgtone * BUSY_PERCENT / 100) <= dsp->historicnoise[x]) {
1357 if (avgtone + (avgtone * BUSY_PERCENT / 100) >= dsp->historicnoise[x]) {
1362 #ifndef BUSYDETECT_TONEONLY
1363 if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) &&
1364 (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) &&
1365 (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1367 if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1369 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1370 if (avgtone > avgsilence) {
1371 if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence) {
1375 if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence) {
1384 /* If we have a 4-length pattern, we can go ahead and just check it in a different way. */
1385 if (dsp->busy_cadence.length == 4) {
1388 int errors_max = ((4 * dsp->busycount) / 100.0) * BUSY_PAT_PERCENT;
1390 for (x = DSP_HISTORY - (dsp->busycount); x < DSP_HISTORY; x += 2) {
1392 temp_error = abs(dsp->historicnoise[x] - dsp->busy_cadence.pattern[0]);
1393 if ((temp_error * 100) / dsp->busy_cadence.pattern[0] > BUSY_PERCENT) {
1397 temp_error = abs(dsp->historicnoise[x + 1] - dsp->busy_cadence.pattern[2]);
1398 if ((temp_error * 100) / dsp->busy_cadence.pattern[2] > BUSY_PERCENT) {
1402 temp_error = abs(dsp->historicsilence[x] - dsp->busy_cadence.pattern[1]);
1403 if ((temp_error * 100) / dsp->busy_cadence.pattern[1] > BUSY_PERCENT) {
1407 temp_error = abs(dsp->historicsilence[x + 1] - dsp->busy_cadence.pattern[3]);
1408 if ((temp_error * 100) / dsp->busy_cadence.pattern[3] > BUSY_PERCENT) {
1413 ast_debug(5, "errors = %d max = %d\n", errors, errors_max);
1415 if (errors <= errors_max) {
1420 /* If we know the expected busy tone length, check we are in the range */
1421 if (res && (dsp->busy_cadence.pattern[0] > 0)) {
1422 if (abs(avgtone - dsp->busy_cadence.pattern[0]) > MAX(dsp->busy_cadence.pattern[0]*BUSY_PAT_PERCENT/100, 20)) {
1423 #ifdef BUSYDETECT_DEBUG
1424 ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
1425 avgtone, dsp->busy_cadence.pattern[0]);
1430 #ifndef BUSYDETECT_TONEONLY
1431 /* If we know the expected busy tone silent-period length, check we are in the range */
1432 if (res && (dsp->busy_cadence.pattern[1] > 0)) {
1433 if (abs(avgsilence - dsp->busy_cadence.pattern[1]) > MAX(dsp->busy_cadence.pattern[1]*BUSY_PAT_PERCENT/100, 20)) {
1434 #ifdef BUSYDETECT_DEBUG
1435 ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
1436 avgsilence, dsp->busy_cadence.pattern[1]);
1442 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
1444 ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1446 ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1452 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1457 if (f->frametype != AST_FRAME_VOICE) {
1458 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1461 if (!ast_format_is_slinear(&f->subclass.format)) {
1462 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear frames :(\n");
1467 return __ast_dsp_silence_noise(dsp, s, len, totalsilence, NULL, NULL);
1470 int ast_dsp_silence_with_energy(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence, int *frames_energy)
1475 if (f->frametype != AST_FRAME_VOICE) {
1476 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1479 if (!ast_format_is_slinear(&f->subclass.format)) {
1480 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear frames :(\n");
1485 return __ast_dsp_silence_noise(dsp, s, len, totalsilence, NULL, frames_energy);
1488 int ast_dsp_noise(struct ast_dsp *dsp, struct ast_frame *f, int *totalnoise)
1493 if (f->frametype != AST_FRAME_VOICE) {
1494 ast_log(LOG_WARNING, "Can't calculate noise on a non-voice frame\n");
1497 if (!ast_format_is_slinear(&f->subclass.format)) {
1498 ast_log(LOG_WARNING, "Can only calculate noise on signed-linear frames :(\n");
1503 return __ast_dsp_silence_noise(dsp, s, len, NULL, totalnoise, NULL);
1507 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1511 int digit = 0, fax_digit = 0;
1514 unsigned char *odata;
1516 struct ast_frame *outf = NULL;
1521 if (af->frametype != AST_FRAME_VOICE) {
1525 odata = af->data.ptr;
1527 /* Make sure we have short data */
1528 if (ast_format_is_slinear(&af->subclass.format)) {
1529 shortdata = af->data.ptr;
1530 len = af->datalen / 2;
1532 switch (af->subclass.format.id) {
1533 case AST_FORMAT_ULAW:
1534 case AST_FORMAT_TESTLAW:
1535 shortdata = alloca(af->datalen * 2);
1536 for (x = 0;x < len; x++) {
1537 shortdata[x] = AST_MULAW(odata[x]);
1540 case AST_FORMAT_ALAW:
1541 shortdata = alloca(af->datalen * 2);
1542 for (x = 0; x < len; x++) {
1543 shortdata[x] = AST_ALAW(odata[x]);
1547 /*Display warning only once. Otherwise you would get hundreds of warnings every second */
1548 if (dsp->display_inband_dtmf_warning)
1549 ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(&af->subclass.format));
1550 dsp->display_inband_dtmf_warning = 0;
1555 /* Initially we do not want to mute anything */
1556 dsp->mute_fragments = 0;
1558 /* Need to run the silence detection stuff for silence suppression and busy detection */
1559 if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) || (dsp->features & DSP_FEATURE_BUSY_DETECT)) {
1560 res = __ast_dsp_silence_noise(dsp, shortdata, len, &silence, NULL, NULL);
1563 if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1564 memset(&dsp->f, 0, sizeof(dsp->f));
1565 dsp->f.frametype = AST_FRAME_NULL;
1567 return ast_frisolate(&dsp->f);
1569 if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1570 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1571 memset(&dsp->f, 0, sizeof(dsp->f));
1572 dsp->f.frametype = AST_FRAME_CONTROL;
1573 dsp->f.subclass.integer = AST_CONTROL_BUSY;
1575 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", chan->name);
1576 return ast_frisolate(&dsp->f);
1579 if ((dsp->features & DSP_FEATURE_FAX_DETECT)) {
1580 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CNG) && tone_detect(dsp, &dsp->cng_tone_state, shortdata, len)) {
1584 if ((dsp->faxmode & DSP_FAXMODE_DETECT_CED) && tone_detect(dsp, &dsp->ced_tone_state, shortdata, len)) {
1588 if ((dsp->faxmode & DSP_FAXMODE_DETECT_V21) && v21_detect(dsp, &dsp->v21_state, shortdata, len)) {
1593 if (dsp->features & (DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_BUSY_DETECT)) {
1594 if (dsp->digitmode & DSP_DIGITMODE_MF)
1595 digit = mf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1597 digit = dtmf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
1599 if (dsp->digit_state.current_digits) {
1600 int event = 0, event_len = 0;
1601 char event_digit = 0;
1603 if (!dsp->dtmf_began) {
1604 /* We have not reported DTMF_BEGIN for anything yet */
1606 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1607 event = AST_FRAME_DTMF_BEGIN;
1608 event_digit = dsp->digit_state.digits[0];
1610 dsp->dtmf_began = 1;
1612 } else if (dsp->digit_state.current_digits > 1 || digit != dsp->digit_state.digits[0]) {
1613 /* Digit changed. This means digit we have reported with DTMF_BEGIN ended */
1614 if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
1615 event = AST_FRAME_DTMF_END;
1616 event_digit = dsp->digit_state.digits[0];
1617 event_len = dsp->digit_state.digitlen[0] * 1000 / dsp->sample_rate;
1619 memmove(&dsp->digit_state.digits[0], &dsp->digit_state.digits[1], dsp->digit_state.current_digits);
1620 memmove(&dsp->digit_state.digitlen[0], &dsp->digit_state.digitlen[1], dsp->digit_state.current_digits * sizeof(dsp->digit_state.digitlen[0]));
1621 dsp->digit_state.current_digits--;
1622 dsp->dtmf_began = 0;
1624 if (dsp->features & DSP_FEATURE_BUSY_DETECT) {
1625 /* Reset Busy Detector as we have some confirmed activity */
1626 memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1627 memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1628 ast_debug(1, "DTMF Detected - Reset busydetector\n");
1633 memset(&dsp->f, 0, sizeof(dsp->f));
1634 dsp->f.frametype = event;
1635 dsp->f.subclass.integer = event_digit;
1636 dsp->f.len = event_len;
1644 /* Fax was detected - digit is either 'f' or 'e' */
1646 memset(&dsp->f, 0, sizeof(dsp->f));
1647 dsp->f.frametype = AST_FRAME_DTMF;
1648 dsp->f.subclass.integer = fax_digit;
1653 if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1654 res = __ast_dsp_call_progress(dsp, shortdata, len);
1657 case AST_CONTROL_ANSWER:
1658 case AST_CONTROL_BUSY:
1659 case AST_CONTROL_RINGING:
1660 case AST_CONTROL_CONGESTION:
1661 case AST_CONTROL_HANGUP:
1662 memset(&dsp->f, 0, sizeof(dsp->f));
1663 dsp->f.frametype = AST_FRAME_CONTROL;
1664 dsp->f.subclass.integer = res;
1665 dsp->f.src = "dsp_progress";
1667 ast_queue_frame(chan, &dsp->f);
1670 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1673 } else if ((dsp->features & DSP_FEATURE_WAITDIALTONE)) {
1674 res = __ast_dsp_call_progress(dsp, shortdata, len);
1678 /* Mute fragment of the frame */
1679 for (x = 0; x < dsp->mute_fragments; x++) {
1680 memset(shortdata + dsp->mute_data[x].start, 0, sizeof(int16_t) * (dsp->mute_data[x].end - dsp->mute_data[x].start));
1683 switch (af->subclass.format.id) {
1684 case AST_FORMAT_ULAW:
1685 for (x = 0; x < len; x++) {
1686 odata[x] = AST_LIN2MU((unsigned short) shortdata[x]);
1689 case AST_FORMAT_ALAW:
1690 for (x = 0; x < len; x++) {
1691 odata[x] = AST_LIN2A((unsigned short) shortdata[x]);
1700 ast_queue_frame(chan, af);
1703 return ast_frisolate(outf);
1709 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1714 dsp->gsamp_size = modes[dsp->progmode].size;
1716 for (x = 0; x < ARRAY_LEN(modes[dsp->progmode].freqs); x++) {
1717 if (modes[dsp->progmode].freqs[x]) {
1718 goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->gsamp_size, dsp->sample_rate);
1722 dsp->freqcount = max;
1723 dsp->ringtimeout= 0;
1726 unsigned int ast_dsp_get_sample_rate(const struct ast_dsp *dsp)
1728 return dsp->sample_rate;
1731 static struct ast_dsp *__ast_dsp_new(unsigned int sample_rate)
1733 struct ast_dsp *dsp;
1735 if ((dsp = ast_calloc(1, sizeof(*dsp)))) {
1736 dsp->threshold = DEFAULT_THRESHOLD;
1737 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1738 dsp->busycount = DSP_HISTORY;
1739 dsp->digitmode = DSP_DIGITMODE_DTMF;
1740 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1741 dsp->sample_rate = sample_rate;
1742 /* Initialize digit detector */
1743 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF, dsp->sample_rate);
1744 dsp->display_inband_dtmf_warning = 1;
1745 /* Initialize initial DSP progress detect parameters */
1746 ast_dsp_prog_reset(dsp);
1747 /* Initialize fax detector */
1748 ast_fax_detect_init(dsp);
1753 struct ast_dsp *ast_dsp_new(void)
1755 return __ast_dsp_new(DEFAULT_SAMPLE_RATE);
1758 struct ast_dsp *ast_dsp_new_with_rate(unsigned int sample_rate)
1760 return __ast_dsp_new(sample_rate);
1763 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1765 dsp->features = features;
1766 if (!(features & DSP_FEATURE_DIGIT_DETECT)) {
1767 dsp->display_inband_dtmf_warning = 0;
1771 void ast_dsp_free(struct ast_dsp *dsp)
1776 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1778 dsp->threshold = threshold;
1781 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1786 if (cadences > DSP_HISTORY) {
1787 cadences = DSP_HISTORY;
1789 dsp->busycount = cadences;
1792 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, const struct ast_dsp_busy_pattern *cadence)
1794 dsp->busy_cadence = *cadence;
1795 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);
1798 void ast_dsp_digitreset(struct ast_dsp *dsp)
1802 dsp->dtmf_began = 0;
1803 if (dsp->digitmode & DSP_DIGITMODE_MF) {
1804 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1805 /* Reinitialise the detector for the next block */
1806 for (i = 0; i < 6; i++) {
1807 goertzel_reset(&s->tone_out[i]);
1809 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = s->current_hit = 0;
1810 s->current_sample = 0;
1812 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1813 /* Reinitialise the detector for the next block */
1814 for (i = 0; i < 4; i++) {
1815 goertzel_reset(&s->row_out[i]);
1816 goertzel_reset(&s->col_out[i]);
1818 s->lasthit = s->current_hit = 0;
1820 s->current_sample = 0;
1825 dsp->digit_state.digits[0] = '\0';
1826 dsp->digit_state.current_digits = 0;
1829 void ast_dsp_reset(struct ast_dsp *dsp)
1833 dsp->totalsilence = 0;
1835 for (x = 0; x < 4; x++) {
1836 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1838 memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1839 memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1840 dsp->ringtimeout= 0;
1843 int ast_dsp_set_digitmode(struct ast_dsp *dsp, int digitmode)
1848 old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1849 new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1851 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1852 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF, dsp->sample_rate);
1854 dsp->digitmode = digitmode;
1858 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1860 if (dsp->faxmode != faxmode) {
1861 ast_fax_detect_init(dsp);
1863 dsp->faxmode = faxmode;
1867 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1871 for (x = 0; x < ARRAY_LEN(aliases); x++) {
1872 if (!strcasecmp(aliases[x].name, zone)) {
1873 dsp->progmode = aliases[x].mode;
1874 ast_dsp_prog_reset(dsp);
1881 int ast_dsp_was_muted(struct ast_dsp *dsp)
1883 return (dsp->mute_fragments > 0);
1886 int ast_dsp_get_tstate(struct ast_dsp *dsp)
1891 int ast_dsp_get_tcount(struct ast_dsp *dsp)
1896 static int _dsp_init(int reload)
1898 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
1899 struct ast_config *cfg;
1901 cfg = ast_config_load2(CONFIG_FILE_NAME, "dsp", config_flags);
1902 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
1903 ast_verb(5, "Can't find dsp config file %s. Assuming default silencethreshold of %d.\n", CONFIG_FILE_NAME, DEFAULT_SILENCE_THRESHOLD);
1904 thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1908 if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
1915 value = ast_variable_retrieve(cfg, "default", "silencethreshold");
1916 if (value && sscanf(value, "%30d", &thresholds[THRESHOLD_SILENCE]) != 1) {
1917 ast_verb(5, "%s: '%s' is not a valid silencethreshold value\n", CONFIG_FILE_NAME, value);
1918 thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1919 } else if (!value) {
1920 thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
1923 ast_config_destroy(cfg);
1928 int ast_dsp_get_threshold_from_settings(enum threshold which)
1930 return thresholds[which];
1933 int ast_dsp_init(void)
1935 return _dsp_init(0);
1938 int ast_dsp_reload(void)
1940 return _dsp_init(1);