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"
57 /*! Number of goertzels for progress detect */
59 GSAMP_SIZE_NA = 183, /*!< North America - 350, 440, 480, 620, 950, 1400, 1800 Hz */
60 GSAMP_SIZE_CR = 188, /*!< Costa Rica, Brazil - Only care about 425 Hz */
61 GSAMP_SIZE_UK = 160 /*!< UK disconnect goertzel feed - should trigger 400hz */
80 /*! For CR/BR modes */
87 static struct progalias {
91 { "us", PROG_MODE_NA },
92 { "ca", PROG_MODE_NA },
93 { "cr", PROG_MODE_CR },
94 { "br", PROG_MODE_CR },
95 { "uk", PROG_MODE_UK },
98 static struct progress {
102 { GSAMP_SIZE_NA, { 350, 440, 480, 620, 950, 1400, 1800 } }, /*!< North America */
103 { GSAMP_SIZE_CR, { 425 } }, /*!< Costa Rica, Brazil */
104 { GSAMP_SIZE_UK, { 400 } }, /*!< UK */
107 #define DEFAULT_THRESHOLD 512
110 BUSY_PERCENT = 10, /*!< The percentage difference between the two last silence periods */
111 BUSY_PAT_PERCENT = 7, /*!< The percentage difference between measured and actual pattern */
112 BUSY_THRESHOLD = 100, /*!< Max number of ms difference between max and min times in busy */
113 BUSY_MIN = 75, /*!< Busy must be at least 80 ms in half-cadence */
114 BUSY_MAX =3100 /*!< Busy can't be longer than 3100 ms in half-cadence */
117 /*! Remember last 15 units */
118 #define DSP_HISTORY 15
120 #define TONE_THRESH 10.0 /*!< How much louder the tone should be than channel energy */
121 #define TONE_MIN_THRESH 1e8 /*!< How much tone there should be at least to attempt */
123 /*! All THRESH_XXX values are in GSAMP_SIZE chunks (us = 22ms) */
125 THRESH_RING = 8, /*!< Need at least 150ms ring to accept */
126 THRESH_TALK = 2, /*!< Talk detection does not work continuously */
127 THRESH_BUSY = 4, /*!< Need at least 80ms to accept */
128 THRESH_CONGESTION = 4, /*!< Need at least 80ms to accept */
129 THRESH_HANGUP = 60, /*!< Need at least 1300ms to accept hangup */
130 THRESH_RING2ANSWER = 300 /*!< Timeout from start of ring to answer (about 6600 ms) */
133 #define MAX_DTMF_DIGITS 128
137 * Minimum tone on = 40ms
138 * Minimum tone off = 50ms
139 * Maximum digit rate = 10 per second
140 * Normal twist <= 8dB accepted
141 * Reverse twist <= 4dB accepted
142 * S/N >= 15dB will detect OK
143 * Attenuation <= 26dB will detect OK
144 * Frequency tolerance +- 1.5% will detect, +-3.5% will reject
147 #define DTMF_THRESHOLD 8.0e7
148 #define FAX_THRESHOLD 8.0e7
149 #define FAX_2ND_HARMONIC 2.0 /* 4dB */
150 #define DTMF_NORMAL_TWIST 6.3 /* 8dB */
152 #define DTMF_REVERSE_TWIST ((digitmode & DSP_DIGITMODE_RELAXDTMF) ? 6.5 : 2.5) /* 4dB normal */
154 #define DTMF_REVERSE_TWIST ((digitmode & DSP_DIGITMODE_RELAXDTMF) ? 4.0 : 2.5) /* 4dB normal */
156 #define DTMF_RELATIVE_PEAK_ROW 6.3 /* 8dB */
157 #define DTMF_RELATIVE_PEAK_COL 6.3 /* 8dB */
158 #define DTMF_2ND_HARMONIC_ROW ((digitmode & DSP_DIGITMODE_RELAXDTMF) ? 1.7 : 2.5) /* 4dB normal */
159 #define DTMF_2ND_HARMONIC_COL 63.1 /* 18dB */
160 #define DTMF_TO_TOTAL_ENERGY 42.0
162 #define BELL_MF_THRESHOLD 1.6e9
163 #define BELL_MF_TWIST 4.0 /* 6dB */
164 #define BELL_MF_RELATIVE_PEAK 12.6 /* 11dB */
166 #if defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
167 #error You cant use BUSYDETECT_TONEONLY together with BUSYDETECT_COMPARE_TONE_AND_SILENCE
170 /* The CNG signal consists of the transmission of 1100 Hz for 1/2 second,
171 * followed by a 3 second silent (2100 Hz OFF) period.
173 #define FAX_TONE_CNG_FREQ 1100
174 #define FAX_TONE_CNG_DURATION 500
175 #define FAX_TONE_CNG_DB 16
177 /* This signal may be sent by the Terminating FAX machine anywhere between
178 * 1.8 to 2.5 seconds AFTER answering the call. The CED signal consists
179 * of a 2100 Hz tone that is from 2.6 to 4 seconds in duration.
181 #define FAX_TONE_CED_FREQ 2100
182 #define FAX_TONE_CED_DURATION 2600
183 #define FAX_TONE_CED_DB 16
185 #define SAMPLE_RATE 8000
187 /* How many samples a frame has. This constant is used when calculating
188 * Goertzel block size for tone_detect. It is only important if we want to
189 * remove (squelch) the tone. In this case it is important to have block
190 * size not to exceed size of voice frame. Otherwise by the moment the tone
191 * is detected it is too late to squelch it from previous frames.
193 #define SAMPLES_IN_FRAME 160
213 int squelch; /* Remove (squelch) tone */
214 goertzel_state_t tone;
215 float energy; /* Accumulated energy of the current block */
216 int samples_pending; /* Samples remain to complete the current block */
218 int hits_required; /* How many successive blocks with tone we are looking for */
219 float threshold; /* Energy of the tone relative to energy from all other signals to consider a hit */
221 int hit_count; /* How many successive blocks we consider tone present */
222 int last_hit; /* Indicates if the last processed block was a hit */
224 } tone_detect_state_t;
228 goertzel_state_t row_out[4];
229 goertzel_state_t col_out[4];
234 } dtmf_detect_state_t;
238 goertzel_state_t tone_out[6];
246 char digits[MAX_DTMF_DIGITS + 1];
252 dtmf_detect_state_t dtmf;
253 mf_detect_state_t mf;
255 } digit_detect_state_t;
257 static float dtmf_row[] =
259 697.0, 770.0, 852.0, 941.0
261 static float dtmf_col[] =
263 1209.0, 1336.0, 1477.0, 1633.0
266 static float mf_tones[] =
268 700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
271 static char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
273 static char bell_mf_positions[] = "1247C-358A--69*---0B----#";
275 static inline void goertzel_sample(goertzel_state_t *s, short sample)
282 s->v3 = (s->fac * s->v2) >> 15;
283 s->v3 = s->v3 - v1 + (sample >> s->chunky);
284 if (abs(s->v3) > 32768) {
292 static inline void goertzel_update(goertzel_state_t *s, short *samps, int count)
296 for (i=0;i<count;i++)
297 goertzel_sample(s, samps[i]);
301 static inline float goertzel_result(goertzel_state_t *s)
304 r.value = (s->v3 * s->v3) + (s->v2 * s->v2);
305 r.value -= ((s->v2 * s->v3) >> 15) * s->fac;
306 r.power = s->chunky * 2;
307 return (float)r.value * (float)(1 << r.power);
310 static inline void goertzel_init(goertzel_state_t *s, float freq, int samples)
312 s->v2 = s->v3 = s->chunky = 0.0;
313 s->fac = (int)(32768.0 * 2.0 * cos(2.0 * M_PI * freq / SAMPLE_RATE));
314 s->samples = samples;
317 static inline void goertzel_reset(goertzel_state_t *s)
319 s->v2 = s->v3 = s->chunky = 0.0;
332 int busy_quietlength;
333 int historicnoise[DSP_HISTORY];
334 int historicsilence[DSP_HISTORY];
335 goertzel_state_t freqs[7];
338 enum gsamp_size gsamp_size;
339 enum prog_mode progmode;
346 digit_detect_state_t digit_state;
347 tone_detect_state_t cng_tone_state;
348 tone_detect_state_t ced_tone_state;
351 static void ast_tone_detect_init(tone_detect_state_t *s, int freq, int duration, int amp)
353 int duration_samples;
355 int periods_in_block;
359 /* Desired tone duration in samples */
360 duration_samples = duration * SAMPLE_RATE / 1000;
361 /* We want to allow 10% deviation of tone duration */
362 duration_samples = duration_samples * 9 / 10;
364 /* If we want to remove tone, it is important to have block size not
365 to exceed frame size. Otherwise by the moment tone is detected it is too late
366 to squelch it from previous frames */
367 s->block_size = SAMPLES_IN_FRAME;
369 periods_in_block = s->block_size * freq / SAMPLE_RATE;
371 /* Make sure we will have at least 5 periods at target frequency for analisys.
372 This may make block larger than expected packet and will make squelching impossible
373 but at least we will be detecting the tone */
374 if (periods_in_block < 5)
375 periods_in_block = 5;
377 /* Now calculate final block size. It will contain integer number of periods */
378 s->block_size = periods_in_block * SAMPLE_RATE / freq;
380 /* tone_detect is currently only used to detect fax tones and we
381 do not need suqlching the fax tones */
384 /* Account for the first and the last block to be incomplete
385 and thus no tone will be detected in them */
386 s->hits_required = (duration_samples - (s->block_size - 1)) / s->block_size;
388 goertzel_init(&s->tone, freq, s->block_size);
390 s->samples_pending = s->block_size;
395 /* We want tone energy to be amp decibels above the rest of the signal (the noise).
396 According to Parseval's theorem the energy computed in time domain equals to energy
397 computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
398 from the energy in the time domain we will get energy of the remaining signal (without the tone
399 we are detecting). We will be checking that
400 10*log(Ew / (Et - Ew)) > amp
401 Calculate threshold so that we will be actually checking
405 x = pow(10.0, amp / 10.0);
406 s->threshold = x / (x + 1);
408 ast_debug(1, "Setup tone %d Hz, %d ms, block_size=%d, hits_required=%d\n", freq, duration, s->block_size, s->hits_required);
411 static void ast_fax_detect_init(struct ast_dsp *s)
413 ast_tone_detect_init(&s->cng_tone_state, FAX_TONE_CNG_FREQ, FAX_TONE_CNG_DURATION, FAX_TONE_CNG_DB);
414 ast_tone_detect_init(&s->ced_tone_state, FAX_TONE_CED_FREQ, FAX_TONE_CED_DURATION, FAX_TONE_CED_DB);
417 static void ast_dtmf_detect_init (dtmf_detect_state_t *s)
423 for (i = 0; i < 4; i++) {
424 goertzel_init (&s->row_out[i], dtmf_row[i], 102);
425 goertzel_init (&s->col_out[i], dtmf_col[i], 102);
428 s->current_sample = 0;
431 static void ast_mf_detect_init (mf_detect_state_t *s)
434 s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
435 for (i = 0; i < 6; i++) {
436 goertzel_init (&s->tone_out[i], mf_tones[i], 160);
438 s->current_sample = 0;
442 static void ast_digit_detect_init(digit_detect_state_t *s, int mf)
444 s->current_digits = 0;
445 s->detected_digits = 0;
450 ast_mf_detect_init(&s->td.mf);
452 ast_dtmf_detect_init(&s->td.dtmf);
455 static int tone_detect(tone_detect_state_t *s, int16_t *amp, int samples,
466 /* Process in blocks. */
467 limit = (samples < s->samples_pending) ? samples : s->samples_pending;
469 for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
470 /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
471 s->energy += (int32_t) *ptr * (int32_t) *ptr;
473 goertzel_sample(&s->tone, *ptr);
476 s->samples_pending -= limit;
478 if (s->samples_pending) {
479 /* Finished incomplete (last) block */
480 if (s->last_hit && s->squelch) {
481 /* If we had a hit last time, go ahead and clear this out since likely it
482 will be another hit */
483 memset(amp, 0, sizeof(*amp) * limit);
491 tone_energy = goertzel_result(&s->tone);
493 /* Scale to make comparable */
495 s->energy *= s->block_size;
497 ast_debug(10, "tone %d, Ew=%f, Et=%f, s/n=%10.2f\n", s->freq, tone_energy, s->energy, tone_energy / (s->energy - tone_energy));
499 if (tone_energy > s->energy * s->threshold) {
501 ast_debug(10, "Hit! count=%d\n", s->hit_count);
505 /* Zero out frame data */
506 memset(amp, 0, sizeof(*amp) * limit);
515 if (hit == s->last_hit) {
517 /* Two successive misses. Tone ended */
519 } else if (!s->hit_count) {
525 if (s->hit_count == s->hits_required) {
526 ast_debug(1, "%d Hz done detected\n", s->freq);
532 /* Reset for the next block */
533 goertzel_reset(&s->tone);
535 /* Advance to the next block */
537 s->samples_pending = s->block_size;
546 static void store_digit(digit_detect_state_t *s, char digit)
548 s->detected_digits++;
549 if (s->current_digits < MAX_DTMF_DIGITS) {
550 s->digits[s->current_digits++] = digit;
551 s->digits[s->current_digits] = '\0';
553 ast_log(LOG_WARNING, "Digit lost due to full buffer\n");
558 static int dtmf_detect(digit_detect_state_t *s, int16_t amp[], int samples,
559 int digitmode, int *writeback)
573 for (sample = 0; sample < samples; sample = limit) {
574 /* 102 is optimised to meet the DTMF specs. */
575 if ((samples - sample) >= (102 - s->td.dtmf.current_sample))
576 limit = sample + (102 - s->td.dtmf.current_sample);
579 /* The following unrolled loop takes only 35% (rough estimate) of the
580 time of a rolled loop on the machine on which it was developed */
581 for (j = sample; j < limit; j++) {
583 s->td.dtmf.energy += famp*famp;
584 /* With GCC 2.95, the following unrolled code seems to take about 35%
585 (rough estimate) as long as a neat little 0-3 loop */
586 goertzel_sample(s->td.dtmf.row_out, amp[j]);
587 goertzel_sample(s->td.dtmf.col_out, amp[j]);
588 goertzel_sample(s->td.dtmf.row_out + 1, amp[j]);
589 goertzel_sample(s->td.dtmf.col_out + 1, amp[j]);
590 goertzel_sample(s->td.dtmf.row_out + 2, amp[j]);
591 goertzel_sample(s->td.dtmf.col_out + 2, amp[j]);
592 goertzel_sample(s->td.dtmf.row_out + 3, amp[j]);
593 goertzel_sample(s->td.dtmf.col_out + 3, amp[j]);
595 s->td.dtmf.current_sample += (limit - sample);
596 if (s->td.dtmf.current_sample < 102) {
597 if (hit && !((digitmode & DSP_DIGITMODE_NOQUELCH))) {
598 /* If we had a hit last time, go ahead and clear this out since likely it
599 will be another hit */
600 for (i=sample;i<limit;i++)
606 /* We are at the end of a DTMF detection block */
607 /* Find the peak row and the peak column */
608 row_energy[0] = goertzel_result (&s->td.dtmf.row_out[0]);
609 col_energy[0] = goertzel_result (&s->td.dtmf.col_out[0]);
611 for (best_row = best_col = 0, i = 1; i < 4; i++) {
612 row_energy[i] = goertzel_result (&s->td.dtmf.row_out[i]);
613 if (row_energy[i] > row_energy[best_row])
615 col_energy[i] = goertzel_result (&s->td.dtmf.col_out[i]);
616 if (col_energy[i] > col_energy[best_col])
620 /* Basic signal level test and the twist test */
621 if (row_energy[best_row] >= DTMF_THRESHOLD &&
622 col_energy[best_col] >= DTMF_THRESHOLD &&
623 col_energy[best_col] < row_energy[best_row]*DTMF_REVERSE_TWIST &&
624 col_energy[best_col]*DTMF_NORMAL_TWIST > row_energy[best_row]) {
625 /* Relative peak test */
626 for (i = 0; i < 4; i++) {
627 if ((i != best_col &&
628 col_energy[i]*DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
630 && row_energy[i]*DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
634 /* ... and fraction of total energy test */
636 (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY*s->td.dtmf.energy) {
638 hit = dtmf_positions[(best_row << 2) + best_col];
639 if (!(digitmode & DSP_DIGITMODE_NOQUELCH)) {
640 /* Zero out frame data if this is part DTMF */
641 for (i=sample;i<limit;i++)
648 /* The logic in the next test is:
649 For digits we need two successive identical clean detects, with
650 something different preceeding it. This can work with
651 back to back differing digits. More importantly, it
652 can work with nasty phones that give a very wobbly start
654 if (hit != s->td.dtmf.current_hit) {
655 if (hit && s->td.dtmf.lasthit == hit) {
656 s->td.dtmf.current_hit = hit;
658 } else if (s->td.dtmf.lasthit != s->td.dtmf.current_hit) {
659 s->td.dtmf.current_hit = 0;
662 s->td.dtmf.lasthit = hit;
664 /* Reinitialise the detector for the next block */
665 for (i = 0; i < 4; i++) {
666 goertzel_reset(&s->td.dtmf.row_out[i]);
667 goertzel_reset(&s->td.dtmf.col_out[i]);
669 s->td.dtmf.energy = 0.0;
670 s->td.dtmf.current_sample = 0;
672 return (s->td.dtmf.current_hit); /* return the debounced hit */
675 /* MF goertzel size */
678 static int mf_detect(digit_detect_state_t *s, int16_t amp[],
679 int samples, int digitmode, int *writeback)
692 for (sample = 0; sample < samples; sample = limit) {
693 /* 80 is optimised to meet the MF specs. */
694 if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample))
695 limit = sample + (MF_GSIZE - s->td.mf.current_sample);
698 /* The following unrolled loop takes only 35% (rough estimate) of the
699 time of a rolled loop on the machine on which it was developed */
700 for (j = sample; j < limit; j++) {
702 /* With GCC 2.95, the following unrolled code seems to take about 35%
703 (rough estimate) as long as a neat little 0-3 loop */
704 goertzel_sample(s->td.mf.tone_out, amp[j]);
705 goertzel_sample(s->td.mf.tone_out + 1, amp[j]);
706 goertzel_sample(s->td.mf.tone_out + 2, amp[j]);
707 goertzel_sample(s->td.mf.tone_out + 3, amp[j]);
708 goertzel_sample(s->td.mf.tone_out + 4, amp[j]);
709 goertzel_sample(s->td.mf.tone_out + 5, amp[j]);
711 s->td.mf.current_sample += (limit - sample);
712 if (s->td.mf.current_sample < MF_GSIZE) {
713 if (hit && !((digitmode & DSP_DIGITMODE_NOQUELCH))) {
714 /* If we had a hit last time, go ahead and clear this out since likely it
715 will be another hit */
716 for (i=sample;i<limit;i++)
722 /* We're at the end of an MF detection block. */
723 /* Find the two highest energies. The spec says to look for
724 two tones and two tones only. Taking this literally -ie
725 only two tones pass the minimum threshold - doesn't work
726 well. The sinc function mess, due to rectangular windowing
727 ensure that! Find the two highest energies and ensure they
728 are considerably stronger than any of the others. */
729 energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
730 energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
731 if (energy[0] > energy[1]) {
740 energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
741 if (energy[i] >= energy[best]) {
744 } else if (energy[i] >= energy[second_best]) {
748 /* Basic signal level and twist tests */
750 if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
751 && energy[best] < energy[second_best]*BELL_MF_TWIST
752 && energy[best]*BELL_MF_TWIST > energy[second_best]) {
753 /* Relative peak test */
756 if (i != best && i != second_best) {
757 if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
758 /* The best two are not clearly the best */
766 /* Get the values into ascending order */
767 if (second_best < best) {
772 best = best*5 + second_best - 1;
773 hit = bell_mf_positions[best];
774 /* Look for two successive similar results */
775 /* The logic in the next test is:
776 For KP we need 4 successive identical clean detects, with
777 two blocks of something different preceeding it. For anything
778 else we need two successive identical clean detects, with
779 two blocks of something different preceeding it. */
780 if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
781 ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
782 (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] &&
783 hit != s->td.mf.hits[0]))) {
789 if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
790 /* Two successive block without a hit terminate current digit */
791 s->td.mf.current_hit = 0;
794 s->td.mf.hits[0] = s->td.mf.hits[1];
795 s->td.mf.hits[1] = s->td.mf.hits[2];
796 s->td.mf.hits[2] = s->td.mf.hits[3];
797 s->td.mf.hits[3] = s->td.mf.hits[4];
798 s->td.mf.hits[4] = hit;
799 /* Reinitialise the detector for the next block */
800 for (i = 0; i < 6; i++)
801 goertzel_reset(&s->td.mf.tone_out[i]);
802 s->td.mf.current_sample = 0;
805 return (s->td.mf.current_hit); /* return the debounced hit */
808 static int __ast_dsp_digitdetect(struct ast_dsp *dsp, short *s, int len, int *writeback)
812 if ((dsp->features & DSP_FEATURE_DTMF_DETECT) && (dsp->digitmode & DSP_DIGITMODE_MF))
813 res = mf_detect(&dsp->digit_state, s, len, dsp->digitmode & DSP_DIGITMODE_RELAXDTMF, writeback);
814 else if (dsp->features & DSP_FEATURE_DTMF_DETECT)
815 res = dtmf_detect(&dsp->digit_state, s, len, dsp->digitmode & DSP_DIGITMODE_RELAXDTMF, writeback);
817 if ((dsp->features & DSP_FEATURE_FAX_DETECT) && (dsp->faxmode & DSP_FAXMODE_DETECT_CNG)) {
818 if (tone_detect(&dsp->cng_tone_state, s, len, NULL)) {
819 store_digit(&dsp->digit_state, 'f');
824 if ((dsp->features & DSP_FEATURE_FAX_DETECT) && (dsp->faxmode & DSP_FAXMODE_DETECT_CED)) {
825 if (tone_detect(&dsp->ced_tone_state, s, len, NULL)) {
826 store_digit(&dsp->digit_state, 'e');
834 int ast_dsp_digitdetect(struct ast_dsp *dsp, struct ast_frame *inf)
840 if (inf->frametype != AST_FRAME_VOICE) {
841 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
844 if (inf->subclass != AST_FORMAT_SLINEAR) {
845 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
849 len = inf->datalen / 2;
850 return __ast_dsp_digitdetect(dsp, s, len, &ign);
853 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
855 /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
856 /* Make sure absolute levels are high enough */
857 if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH))
859 /* Amplify ignored stuff */
863 /* Check first tone */
864 if ((p1 < i1) || (p1 < i2) || (p1 < e))
867 if ((p2 < i1) || (p2 < i2) || (p2 < e))
869 /* Guess it's there... */
873 int ast_dsp_getdigits(struct ast_dsp *dsp, char *buf, int max)
875 if (max > dsp->digit_state.current_digits)
876 max = dsp->digit_state.current_digits;
878 memcpy(buf, dsp->digit_state.digits, max);
879 memmove(dsp->digit_state.digits, dsp->digit_state.digits + max, dsp->digit_state.current_digits - max);
880 dsp->digit_state.current_digits -= max;
886 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
891 int newstate = DSP_TONE_STATE_SILENCE;
894 /* Take the lesser of the number of samples we need and what we have */
896 if (pass > dsp->gsamp_size - dsp->gsamps)
897 pass = dsp->gsamp_size - dsp->gsamps;
898 for (x=0;x<pass;x++) {
899 for (y=0;y<dsp->freqcount;y++)
900 goertzel_sample(&dsp->freqs[y], s[x]);
901 dsp->genergy += s[x] * s[x];
906 if (dsp->gsamps == dsp->gsamp_size) {
909 hz[y] = goertzel_result(&dsp->freqs[y]);
910 switch (dsp->progmode) {
912 if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
913 newstate = DSP_TONE_STATE_BUSY;
914 } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
915 newstate = DSP_TONE_STATE_RINGING;
916 } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
917 newstate = DSP_TONE_STATE_DIALTONE;
918 } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
919 newstate = DSP_TONE_STATE_SPECIAL1;
920 } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
921 if (dsp->tstate == DSP_TONE_STATE_SPECIAL1)
922 newstate = DSP_TONE_STATE_SPECIAL2;
923 } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
924 if (dsp->tstate == DSP_TONE_STATE_SPECIAL2)
925 newstate = DSP_TONE_STATE_SPECIAL3;
926 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
927 newstate = DSP_TONE_STATE_TALKING;
929 newstate = DSP_TONE_STATE_SILENCE;
932 if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
933 newstate = DSP_TONE_STATE_RINGING;
934 } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
935 newstate = DSP_TONE_STATE_TALKING;
937 newstate = DSP_TONE_STATE_SILENCE;
940 if (hz[HZ_400] > TONE_MIN_THRESH * TONE_THRESH) {
941 newstate = DSP_TONE_STATE_HUNGUP;
945 ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
947 if (newstate == dsp->tstate) {
949 if (dsp->ringtimeout)
951 switch (dsp->tstate) {
952 case DSP_TONE_STATE_RINGING:
953 if ((dsp->features & DSP_PROGRESS_RINGING) &&
954 (dsp->tcount==THRESH_RING)) {
955 res = AST_CONTROL_RINGING;
959 case DSP_TONE_STATE_BUSY:
960 if ((dsp->features & DSP_PROGRESS_BUSY) &&
961 (dsp->tcount==THRESH_BUSY)) {
962 res = AST_CONTROL_BUSY;
963 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
966 case DSP_TONE_STATE_TALKING:
967 if ((dsp->features & DSP_PROGRESS_TALK) &&
968 (dsp->tcount==THRESH_TALK)) {
969 res = AST_CONTROL_ANSWER;
970 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
973 case DSP_TONE_STATE_SPECIAL3:
974 if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
975 (dsp->tcount==THRESH_CONGESTION)) {
976 res = AST_CONTROL_CONGESTION;
977 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
980 case DSP_TONE_STATE_HUNGUP:
981 if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
982 (dsp->tcount==THRESH_HANGUP)) {
983 res = AST_CONTROL_HANGUP;
984 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
988 if (dsp->ringtimeout==THRESH_RING2ANSWER) {
989 ast_debug(1, "Consider call as answered because of timeout after last ring\n");
990 res = AST_CONTROL_ANSWER;
991 dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
994 ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
995 ast_debug(5, "Start state %d\n", newstate);
996 dsp->tstate = newstate;
1000 /* Reset goertzel */
1002 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1011 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
1013 if (inf->frametype != AST_FRAME_VOICE) {
1014 ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
1017 if (inf->subclass != AST_FORMAT_SLINEAR) {
1018 ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
1021 return __ast_dsp_call_progress(dsp, inf->data, inf->datalen / 2);
1024 static int __ast_dsp_silence(struct ast_dsp *dsp, short *s, int len, int *totalsilence)
1033 for (x=0;x<len; x++)
1036 if (accum < dsp->threshold) {
1038 dsp->totalsilence += len/8;
1039 if (dsp->totalnoise) {
1040 /* Move and save history */
1041 memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount +1, dsp->busycount*sizeof(dsp->historicnoise[0]));
1042 dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
1043 /* we don't want to check for busydetect that frequently */
1048 dsp->totalnoise = 0;
1052 dsp->totalnoise += len/8;
1053 if (dsp->totalsilence) {
1054 int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
1055 int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
1056 /* Move and save history */
1057 memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount*sizeof(dsp->historicsilence[0]));
1058 dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
1059 /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
1060 if (silence1 < silence2) {
1061 if (silence1 + silence1*BUSY_PERCENT/100 >= silence2)
1066 if (silence1 - silence1*BUSY_PERCENT/100 <= silence2)
1072 dsp->totalsilence = 0;
1075 *totalsilence = dsp->totalsilence;
1079 int ast_dsp_busydetect(struct ast_dsp *dsp)
1082 #ifndef BUSYDETECT_TONEONLY
1083 int avgsilence = 0, hitsilence = 0;
1085 int avgtone = 0, hittone = 0;
1086 if (!dsp->busymaybe)
1088 for (x=DSP_HISTORY - dsp->busycount;x<DSP_HISTORY;x++) {
1089 #ifndef BUSYDETECT_TONEONLY
1090 avgsilence += dsp->historicsilence[x];
1092 avgtone += dsp->historicnoise[x];
1094 #ifndef BUSYDETECT_TONEONLY
1095 avgsilence /= dsp->busycount;
1097 avgtone /= dsp->busycount;
1098 for (x=DSP_HISTORY - dsp->busycount;x<DSP_HISTORY;x++) {
1099 #ifndef BUSYDETECT_TONEONLY
1100 if (avgsilence > dsp->historicsilence[x]) {
1101 if (avgsilence - (avgsilence*BUSY_PERCENT/100) <= dsp->historicsilence[x])
1104 if (avgsilence + (avgsilence*BUSY_PERCENT/100) >= dsp->historicsilence[x])
1108 if (avgtone > dsp->historicnoise[x]) {
1109 if (avgtone - (avgtone*BUSY_PERCENT/100) <= dsp->historicnoise[x])
1112 if (avgtone + (avgtone*BUSY_PERCENT/100) >= dsp->historicnoise[x])
1116 #ifndef BUSYDETECT_TONEONLY
1117 if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) &&
1118 (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) &&
1119 (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
1121 if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
1123 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
1124 if (avgtone > avgsilence) {
1125 if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence)
1128 if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence)
1135 /* If we know the expected busy tone length, check we are in the range */
1136 if (res && (dsp->busy_tonelength > 0)) {
1137 if (abs(avgtone - dsp->busy_tonelength) > (dsp->busy_tonelength*BUSY_PAT_PERCENT/100)) {
1138 #ifdef BUSYDETECT_DEBUG
1139 ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
1140 avgtone, dsp->busy_tonelength);
1145 #ifndef BUSYDETECT_TONEONLY
1146 /* If we know the expected busy tone silent-period length, check we are in the range */
1147 if (res && (dsp->busy_quietlength > 0)) {
1148 if (abs(avgsilence - dsp->busy_quietlength) > (dsp->busy_quietlength*BUSY_PAT_PERCENT/100)) {
1149 #ifdef BUSYDETECT_DEBUG
1150 ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
1151 avgsilence, dsp->busy_quietlength);
1157 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
1159 ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1161 ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
1167 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
1172 if (f->frametype != AST_FRAME_VOICE) {
1173 ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
1176 if (f->subclass != AST_FORMAT_SLINEAR) {
1177 ast_log(LOG_WARNING, "Can only calculate silence on signed-linear frames :(\n");
1182 return __ast_dsp_silence(dsp, s, len, totalsilence);
1185 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
1192 unsigned char *odata;
1196 #define FIX_INF(inf) do { \
1198 switch (inf->subclass) { \
1199 case AST_FORMAT_SLINEAR: \
1201 case AST_FORMAT_ULAW: \
1202 for (x=0;x<len;x++) \
1203 odata[x] = AST_LIN2MU((unsigned short)shortdata[x]); \
1205 case AST_FORMAT_ALAW: \
1206 for (x=0;x<len;x++) \
1207 odata[x] = AST_LIN2A((unsigned short)shortdata[x]); \
1215 if (af->frametype != AST_FRAME_VOICE)
1219 /* Make sure we have short data */
1220 switch (af->subclass) {
1221 case AST_FORMAT_SLINEAR:
1222 shortdata = af->data;
1223 len = af->datalen / 2;
1225 case AST_FORMAT_ULAW:
1226 shortdata = alloca(af->datalen * 2);
1227 for (x = 0;x < len; x++)
1228 shortdata[x] = AST_MULAW(odata[x]);
1230 case AST_FORMAT_ALAW:
1231 shortdata = alloca(af->datalen * 2);
1232 for (x = 0; x < len; x++)
1233 shortdata[x] = AST_ALAW(odata[x]);
1236 ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(af->subclass));
1239 silence = __ast_dsp_silence(dsp, shortdata, len, NULL);
1240 if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
1241 memset(&dsp->f, 0, sizeof(dsp->f));
1242 dsp->f.frametype = AST_FRAME_NULL;
1246 if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
1247 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1248 memset(&dsp->f, 0, sizeof(dsp->f));
1249 dsp->f.frametype = AST_FRAME_CONTROL;
1250 dsp->f.subclass = AST_CONTROL_BUSY;
1252 ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", chan->name);
1255 if (((dsp->features & DSP_FEATURE_DTMF_DETECT) || (dsp->features & DSP_FEATURE_FAX_DETECT))) {
1256 digit = __ast_dsp_digitdetect(dsp, shortdata, len, &writeback);
1259 printf("Performing digit detection returned %d, digitmode is %d\n", digit, dsp->digitmode);
1261 if (dsp->digitmode & (DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX)) {
1262 if (!dsp->thinkdigit) {
1264 /* Looks like we might have something.
1265 * Request a conference mute for the moment */
1266 memset(&dsp->f, 0, sizeof(dsp->f));
1267 dsp->f.frametype = AST_FRAME_DTMF;
1268 dsp->f.subclass = 'm';
1269 dsp->thinkdigit = 'x';
1272 ast_queue_frame(chan, af);
1278 /* Thought we saw one last time. Pretty sure we really have now */
1279 if ((dsp->thinkdigit != 'x') && (dsp->thinkdigit != digit)) {
1280 /* If we found a digit, and we're changing digits, go
1281 ahead and send this one, but DON'T stop confmute because
1282 we're detecting something else, too... */
1283 memset(&dsp->f, 0, sizeof(dsp->f));
1284 dsp->f.frametype = AST_FRAME_DTMF_END;
1285 dsp->f.subclass = dsp->thinkdigit;
1288 ast_queue_frame(chan, af);
1291 dsp->thinkdigit = digit;
1292 memset(&dsp->f, 0, sizeof(dsp->f));
1293 dsp->f.frametype = AST_FRAME_DTMF_BEGIN;
1294 dsp->f.subclass = dsp->thinkdigit;
1297 ast_queue_frame(chan, af);
1302 memset(&dsp->f, 0, sizeof(dsp->f));
1303 if (dsp->thinkdigit != 'x') {
1304 /* If we found a digit, send it now */
1305 dsp->f.frametype = AST_FRAME_DTMF_END;
1306 dsp->f.subclass = dsp->thinkdigit;
1307 dsp->thinkdigit = 0;
1309 dsp->f.frametype = AST_FRAME_DTMF;
1310 dsp->f.subclass = 'u';
1311 dsp->thinkdigit = 0;
1315 ast_queue_frame(chan, af);
1320 } else if (dsp->digit_state.current_digits > 1 ||
1321 (dsp->digit_state.current_digits == 1 && digit != dsp->digit_state.digits[0])) {
1322 /* Since we basically generate DTMF_END frames we do it only when a digit
1325 memset(&dsp->f, 0, sizeof(dsp->f));
1326 dsp->f.frametype = AST_FRAME_DTMF;
1327 dsp->f.subclass = dsp->digit_state.digits[0];
1328 memmove(dsp->digit_state.digits, dsp->digit_state.digits + 1, dsp->digit_state.current_digits);
1329 dsp->digit_state.current_digits--;
1332 ast_queue_frame(chan, af);
1337 if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
1338 res = __ast_dsp_call_progress(dsp, shortdata, len);
1341 case AST_CONTROL_ANSWER:
1342 case AST_CONTROL_BUSY:
1343 case AST_CONTROL_RINGING:
1344 case AST_CONTROL_CONGESTION:
1345 case AST_CONTROL_HANGUP:
1346 memset(&dsp->f, 0, sizeof(dsp->f));
1347 dsp->f.frametype = AST_FRAME_CONTROL;
1348 dsp->f.subclass = res;
1349 dsp->f.src = "dsp_progress";
1351 ast_queue_frame(chan, &dsp->f);
1354 ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
1362 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
1367 dsp->gsamp_size = modes[dsp->progmode].size;
1369 for (x = 0; x < sizeof(modes[dsp->progmode].freqs) / sizeof(modes[dsp->progmode].freqs[0]); x++) {
1370 if (modes[dsp->progmode].freqs[x]) {
1371 goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->gsamp_size);
1375 dsp->freqcount = max;
1376 dsp->ringtimeout= 0;
1379 struct ast_dsp *ast_dsp_new(void)
1381 struct ast_dsp *dsp;
1383 if ((dsp = ast_calloc(1, sizeof(*dsp)))) {
1384 dsp->threshold = DEFAULT_THRESHOLD;
1385 dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
1386 dsp->busycount = DSP_HISTORY;
1387 dsp->digitmode = DSP_DIGITMODE_DTMF;
1388 dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
1389 /* Initialize digit detector */
1390 ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF);
1391 /* Initialize initial DSP progress detect parameters */
1392 ast_dsp_prog_reset(dsp);
1393 /* Initialize fax detector */
1394 ast_fax_detect_init(dsp);
1399 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
1401 dsp->features = features;
1404 void ast_dsp_free(struct ast_dsp *dsp)
1409 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
1411 dsp->threshold = threshold;
1414 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
1418 if (cadences > DSP_HISTORY)
1419 cadences = DSP_HISTORY;
1420 dsp->busycount = cadences;
1423 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, int tonelength, int quietlength)
1425 dsp->busy_tonelength = tonelength;
1426 dsp->busy_quietlength = quietlength;
1427 ast_debug(1, "dsp busy pattern set to %d,%d\n", tonelength, quietlength);
1430 void ast_dsp_digitreset(struct ast_dsp *dsp)
1434 dsp->thinkdigit = 0;
1435 if (dsp->digitmode & DSP_DIGITMODE_MF) {
1436 mf_detect_state_t *s = &dsp->digit_state.td.mf;
1437 /* Reinitialise the detector for the next block */
1438 for (i = 0; i < 6; i++) {
1439 goertzel_reset(&s->tone_out[i]);
1441 s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = s->current_hit = 0;
1442 s->current_sample = 0;
1444 dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
1445 /* Reinitialise the detector for the next block */
1446 for (i = 0; i < 4; i++) {
1447 goertzel_reset(&s->row_out[i]);
1448 goertzel_reset(&s->col_out[i]);
1450 s->lasthit = s->current_hit = 0;
1452 s->current_sample = 0;
1455 dsp->digit_state.digits[0] = '\0';
1456 dsp->digit_state.current_digits = 0;
1459 void ast_dsp_reset(struct ast_dsp *dsp)
1463 dsp->totalsilence = 0;
1466 dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
1467 memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
1468 memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
1469 dsp->ringtimeout= 0;
1472 int ast_dsp_digitmode(struct ast_dsp *dsp, int digitmode)
1477 old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1478 new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
1480 /* Must initialize structures if switching from MF to DTMF or vice-versa */
1481 ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF);
1483 dsp->digitmode = digitmode;
1487 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
1489 if (dsp->faxmode != faxmode) {
1490 ast_fax_detect_init(dsp);
1492 dsp->faxmode = faxmode;
1496 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
1500 for (x = 0; x < ARRAY_LEN(aliases); x++) {
1501 if (!strcasecmp(aliases[x].name, zone)) {
1502 dsp->progmode = aliases[x].mode;
1503 ast_dsp_prog_reset(dsp);
1510 int ast_dsp_get_tstate(struct ast_dsp *dsp)
1515 int ast_dsp_get_tcount(struct ast_dsp *dsp)