Thu Aug 30 20:43:05 2012

Asterisk developer's documentation


dsp.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * Goertzel routines are borrowed from Steve Underwood's tremendous work on the
00009  * DTMF detector.
00010  *
00011  * See http://www.asterisk.org for more information about
00012  * the Asterisk project. Please do not directly contact
00013  * any of the maintainers of this project for assistance;
00014  * the project provides a web site, mailing lists and IRC
00015  * channels for your use.
00016  *
00017  * This program is free software, distributed under the terms of
00018  * the GNU General Public License Version 2. See the LICENSE file
00019  * at the top of the source tree.
00020  */
00021 
00022 /*! \file
00023  *
00024  * \brief Convenience Signal Processing routines
00025  *
00026  * \author Mark Spencer <markster@digium.com>
00027  * \author Steve Underwood <steveu@coppice.org>
00028  */
00029 
00030 /* Some routines from tone_detect.c by Steven Underwood as published under the zapata library */
00031 /*
00032    tone_detect.c - General telephony tone detection, and specific
00033                detection of DTMF.
00034 
00035    Copyright (C) 2001  Steve Underwood <steveu@coppice.org>
00036 
00037    Despite my general liking of the GPL, I place this code in the
00038    public domain for the benefit of all mankind - even the slimy
00039    ones who might try to proprietize my work and use it to my
00040    detriment.
00041 */
00042 
00043 /*** MODULEINFO
00044    <support_level>core</support_level>
00045  ***/
00046 
00047 #include "asterisk.h"
00048 
00049 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 369001 $")
00050 
00051 #include <math.h>
00052 
00053 #include "asterisk/frame.h"
00054 #include "asterisk/channel.h"
00055 #include "asterisk/dsp.h"
00056 #include "asterisk/ulaw.h"
00057 #include "asterisk/alaw.h"
00058 #include "asterisk/utils.h"
00059 #include "asterisk/options.h"
00060 #include "asterisk/config.h"
00061 
00062 /*! Number of goertzels for progress detect */
00063 enum gsamp_size {
00064    GSAMP_SIZE_NA = 183,       /*!< North America - 350, 440, 480, 620, 950, 1400, 1800 Hz */
00065    GSAMP_SIZE_CR = 188,       /*!< Costa Rica, Brazil - Only care about 425 Hz */
00066    GSAMP_SIZE_UK = 160        /*!< UK disconnect goertzel feed - should trigger 400hz */
00067 };
00068 
00069 enum prog_mode {
00070    PROG_MODE_NA = 0,
00071    PROG_MODE_CR,
00072    PROG_MODE_UK
00073 };
00074 
00075 enum freq_index { 
00076    /*! For US modes { */
00077    HZ_350 = 0,
00078    HZ_440,
00079    HZ_480,
00080    HZ_620,
00081    HZ_950,
00082    HZ_1400,
00083    HZ_1800, /*!< } */
00084 
00085    /*! For CR/BR modes */
00086    HZ_425 = 0,
00087 
00088    /*! For UK mode */
00089    HZ_350UK = 0,
00090    HZ_400UK,
00091    HZ_440UK
00092 };
00093 
00094 static struct progalias {
00095    char *name;
00096    enum prog_mode mode;
00097 } aliases[] = {
00098    { "us", PROG_MODE_NA },
00099    { "ca", PROG_MODE_NA },
00100    { "cr", PROG_MODE_CR },
00101    { "br", PROG_MODE_CR },
00102    { "uk", PROG_MODE_UK },
00103 };
00104 
00105 static struct progress {
00106    enum gsamp_size size;
00107    int freqs[7];
00108 } modes[] = {
00109    { GSAMP_SIZE_NA, { 350, 440, 480, 620, 950, 1400, 1800 } }, /*!< North America */
00110    { GSAMP_SIZE_CR, { 425 } },                                 /*!< Costa Rica, Brazil */
00111    { GSAMP_SIZE_UK, { 350, 400, 440 } },                                   /*!< UK */
00112 };
00113 
00114 /*!\brief This value is the minimum threshold, calculated by averaging all
00115  * of the samples within a frame, for which a frame is determined to either
00116  * be silence (below the threshold) or noise (above the threshold).  Please
00117  * note that while the default threshold is an even exponent of 2, there is
00118  * no requirement that it be so.  The threshold will accept any value between
00119  * 0 and 32767.
00120  */
00121 #define DEFAULT_THRESHOLD  512
00122 
00123 enum busy_detect {
00124    BUSY_PERCENT = 10,      /*!< The percentage difference between the two last silence periods */
00125    BUSY_PAT_PERCENT = 7,   /*!< The percentage difference between measured and actual pattern */
00126    BUSY_THRESHOLD = 100,   /*!< Max number of ms difference between max and min times in busy */
00127    BUSY_MIN = 75,          /*!< Busy must be at least 80 ms in half-cadence */
00128    BUSY_MAX =3100          /*!< Busy can't be longer than 3100 ms in half-cadence */
00129 };
00130 
00131 /*! Remember last 15 units */
00132 #define DSP_HISTORY     15
00133 
00134 #define TONE_THRESH     10.0  /*!< How much louder the tone should be than channel energy */
00135 #define TONE_MIN_THRESH    1e8   /*!< How much tone there should be at least to attempt */
00136 
00137 /*! All THRESH_XXX values are in GSAMP_SIZE chunks (us = 22ms) */
00138 enum gsamp_thresh {
00139    THRESH_RING = 8,           /*!< Need at least 150ms ring to accept */
00140    THRESH_TALK = 2,           /*!< Talk detection does not work continuously */
00141    THRESH_BUSY = 4,           /*!< Need at least 80ms to accept */
00142    THRESH_CONGESTION = 4,     /*!< Need at least 80ms to accept */
00143    THRESH_HANGUP = 60,        /*!< Need at least 1300ms to accept hangup */
00144    THRESH_RING2ANSWER = 300   /*!< Timeout from start of ring to answer (about 6600 ms) */
00145 };
00146 
00147 #define  MAX_DTMF_DIGITS      128
00148 
00149 /* Basic DTMF specs:
00150  *
00151  * Minimum tone on = 40ms
00152  * Minimum tone off = 50ms
00153  * Maximum digit rate = 10 per second
00154  * Normal twist <= 8dB accepted
00155  * Reverse twist <= 4dB accepted
00156  * S/N >= 15dB will detect OK
00157  * Attenuation <= 26dB will detect OK
00158  * Frequency tolerance +- 1.5% will detect, +-3.5% will reject
00159  */
00160 
00161 #define DTMF_THRESHOLD     8.0e7
00162 #define FAX_THRESHOLD      8.0e7
00163 #define FAX_2ND_HARMONIC   2.0     /* 4dB */
00164 #define DTMF_NORMAL_TWIST  6.3     /* 8dB */
00165 #ifdef   RADIO_RELAX
00166 #define DTMF_REVERSE_TWIST          (relax ? 6.5 : 2.5)     /* 4dB normal */
00167 #else
00168 #define DTMF_REVERSE_TWIST          (relax ? 4.0 : 2.5)     /* 4dB normal */
00169 #endif
00170 #define DTMF_RELATIVE_PEAK_ROW   6.3     /* 8dB */
00171 #define DTMF_RELATIVE_PEAK_COL   6.3     /* 8dB */
00172 #define DTMF_2ND_HARMONIC_ROW       (relax ? 1.7 : 2.5)     /* 4dB normal */
00173 #define DTMF_2ND_HARMONIC_COL 63.1    /* 18dB */
00174 #define DTMF_TO_TOTAL_ENERGY  42.0
00175 
00176 #define BELL_MF_THRESHOLD  1.6e9
00177 #define BELL_MF_TWIST      4.0     /* 6dB */
00178 #define BELL_MF_RELATIVE_PEAK 12.6    /* 11dB */
00179 
00180 #if defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
00181 #error You cant use BUSYDETECT_TONEONLY together with BUSYDETECT_COMPARE_TONE_AND_SILENCE
00182 #endif
00183 
00184 /* The CNG signal consists of the transmission of 1100 Hz for 1/2 second,
00185  * followed by a 3 second silent (2100 Hz OFF) period.
00186  */
00187 #define FAX_TONE_CNG_FREQ  1100
00188 #define FAX_TONE_CNG_DURATION 500
00189 #define FAX_TONE_CNG_DB    16
00190 
00191 /* This signal may be sent by the Terminating FAX machine anywhere between
00192  * 1.8 to 2.5 seconds AFTER answering the call.  The CED signal consists
00193  * of a 2100 Hz tone that is from 2.6 to 4 seconds in duration.
00194 */
00195 #define FAX_TONE_CED_FREQ  2100
00196 #define FAX_TONE_CED_DURATION 2600
00197 #define FAX_TONE_CED_DB    16
00198 
00199 #define SAMPLE_RATE     8000
00200 
00201 /* How many samples a frame has.  This constant is used when calculating
00202  * Goertzel block size for tone_detect.  It is only important if we want to
00203  * remove (squelch) the tone. In this case it is important to have block
00204  * size not to exceed size of voice frame.  Otherwise by the moment the tone
00205  * is detected it is too late to squelch it from previous frames.
00206  */
00207 #define SAMPLES_IN_FRAME   160
00208 
00209 /* MF goertzel size */
00210 #define MF_GSIZE     120
00211 
00212 /* DTMF goertzel size */
00213 #define DTMF_GSIZE      102
00214 
00215 /* How many successive hits needed to consider begin of a digit */
00216 #define DTMF_HITS_TO_BEGIN 4
00217 /* How many successive misses needed to consider end of a digit */
00218 #define DTMF_MISSES_TO_END 4
00219 
00220 /*!
00221  * \brief The default silence threshold we will use if an alternate
00222  * configured value is not present or is invalid.
00223  */
00224 static const int DEFAULT_SILENCE_THRESHOLD = 256;
00225 
00226 #define CONFIG_FILE_NAME "dsp.conf"
00227 
00228 typedef struct {
00229    int v2;
00230    int v3;
00231    int chunky;
00232    int fac;
00233    int samples;
00234 } goertzel_state_t;
00235 
00236 typedef struct {
00237    int value;
00238    int power;
00239 } goertzel_result_t;
00240 
00241 typedef struct
00242 {
00243    int freq;
00244    int block_size;
00245    int squelch;      /* Remove (squelch) tone */
00246    goertzel_state_t tone;
00247    float energy;     /* Accumulated energy of the current block */
00248    int samples_pending; /* Samples remain to complete the current block */
00249    int mute_samples; /* How many additional samples needs to be muted to suppress already detected tone */
00250 
00251    int hits_required;   /* How many successive blocks with tone we are looking for */
00252    float threshold;  /* Energy of the tone relative to energy from all other signals to consider a hit */
00253 
00254    int hit_count;    /* How many successive blocks we consider tone present */
00255    int last_hit;     /* Indicates if the last processed block was a hit */
00256 
00257 } tone_detect_state_t;
00258 
00259 typedef struct
00260 {
00261    goertzel_state_t row_out[4];
00262    goertzel_state_t col_out[4];
00263    int hits_to_begin;      /* How many successive hits needed to consider begin of a digit */
00264    int misses_to_end;      /* How many successive misses needed to consider end of a digit */
00265    int hits;         /* How many successive hits we have seen already */
00266    int misses;       /* How many successive misses we have seen already */
00267    int lasthit;
00268    int current_hit;
00269    float energy;
00270    int current_sample;
00271    int mute_samples;
00272 } dtmf_detect_state_t;
00273 
00274 typedef struct
00275 {
00276    goertzel_state_t tone_out[6];
00277    int current_hit;
00278    int hits[5];
00279    int current_sample;
00280    int mute_samples;
00281 } mf_detect_state_t;
00282 
00283 typedef struct
00284 {
00285    char digits[MAX_DTMF_DIGITS + 1];
00286    int digitlen[MAX_DTMF_DIGITS + 1];
00287    int current_digits;
00288    int detected_digits;
00289    int lost_digits;
00290 
00291    union {
00292       dtmf_detect_state_t dtmf;
00293       mf_detect_state_t mf;
00294    } td;
00295 } digit_detect_state_t;
00296 
00297 static const float dtmf_row[] = {
00298    697.0,  770.0,  852.0,  941.0
00299 };
00300 static const float dtmf_col[] = {
00301    1209.0, 1336.0, 1477.0, 1633.0
00302 };
00303 static const float mf_tones[] = {
00304    700.0, 900.0, 1100.0, 1300.0, 1500.0, 1700.0
00305 };
00306 static const char dtmf_positions[] = "123A" "456B" "789C" "*0#D";
00307 static const char bell_mf_positions[] = "1247C-358A--69*---0B----#";
00308 static int thresholds[THRESHOLD_MAX];
00309 
00310 static inline void goertzel_sample(goertzel_state_t *s, short sample)
00311 {
00312    int v1;
00313    
00314    v1 = s->v2;
00315    s->v2 = s->v3;
00316    
00317    s->v3 = (s->fac * s->v2) >> 15;
00318    s->v3 = s->v3 - v1 + (sample >> s->chunky);
00319    if (abs(s->v3) > 32768) {
00320       s->chunky++;
00321       s->v3 = s->v3 >> 1;
00322       s->v2 = s->v2 >> 1;
00323       v1 = v1 >> 1;
00324    }
00325 }
00326 
00327 static inline void goertzel_update(goertzel_state_t *s, short *samps, int count)
00328 {
00329    int i;
00330    
00331    for (i = 0; i < count; i++) {
00332       goertzel_sample(s, samps[i]);
00333    }
00334 }
00335 
00336 
00337 static inline float goertzel_result(goertzel_state_t *s)
00338 {
00339    goertzel_result_t r;
00340    r.value = (s->v3 * s->v3) + (s->v2 * s->v2);
00341    r.value -= ((s->v2 * s->v3) >> 15) * s->fac;
00342    r.power = s->chunky * 2;
00343    return (float)r.value * (float)(1 << r.power);
00344 }
00345 
00346 static inline void goertzel_init(goertzel_state_t *s, float freq, int samples)
00347 {
00348    s->v2 = s->v3 = s->chunky = 0.0;
00349    s->fac = (int)(32768.0 * 2.0 * cos(2.0 * M_PI * freq / SAMPLE_RATE));
00350    s->samples = samples;
00351 }
00352 
00353 static inline void goertzel_reset(goertzel_state_t *s)
00354 {
00355    s->v2 = s->v3 = s->chunky = 0.0;
00356 }
00357 
00358 typedef struct {
00359    int start;
00360    int end;
00361 } fragment_t;
00362 
00363 /* Note on tone suppression (squelching). Individual detectors (DTMF/MF/generic tone)
00364  * report fragmens of the frame in which detected tone resides and which needs
00365  * to be "muted" in order to suppress the tone. To mark fragment for muting,
00366  * detectors call mute_fragment passing fragment_t there. Multiple fragments
00367  * can be marked and ast_dsp_process later will mute all of them.
00368  *
00369  * Note: When tone starts in the middle of a Goertzel block, it won't be properly
00370  * detected in that block, only in the next. If we only mute the next block
00371  * where tone is actually detected, the user will still hear beginning
00372  * of the tone in preceeding block. This is why we usually want to mute some amount
00373  * of samples preceeding and following the block where tone was detected.
00374 */
00375 
00376 struct ast_dsp {
00377    struct ast_frame f;
00378    int threshold;
00379    int totalsilence;
00380    int totalnoise;
00381    int features;
00382    int ringtimeout;
00383    int busymaybe;
00384    int busycount;
00385    int busy_tonelength;
00386    int busy_quietlength;
00387    int historicnoise[DSP_HISTORY];
00388    int historicsilence[DSP_HISTORY];
00389    goertzel_state_t freqs[7];
00390    int freqcount;
00391    int gsamps;
00392    enum gsamp_size gsamp_size;
00393    enum prog_mode progmode;
00394    int tstate;
00395    int tcount;
00396    int digitmode;
00397    int faxmode;
00398    int dtmf_began;
00399    int display_inband_dtmf_warning;
00400    float genergy;
00401    int mute_fragments;
00402    fragment_t mute_data[5];
00403    digit_detect_state_t digit_state;
00404    tone_detect_state_t cng_tone_state;
00405    tone_detect_state_t ced_tone_state;
00406 };
00407 
00408 static void mute_fragment(struct ast_dsp *dsp, fragment_t *fragment)
00409 {
00410    if (dsp->mute_fragments >= ARRAY_LEN(dsp->mute_data)) {
00411       ast_log(LOG_ERROR, "Too many fragments to mute. Ignoring\n");
00412       return;
00413    }
00414 
00415    dsp->mute_data[dsp->mute_fragments++] = *fragment;
00416 }
00417 
00418 static void ast_tone_detect_init(tone_detect_state_t *s, int freq, int duration, int amp)
00419 {
00420    int duration_samples;
00421    float x;
00422    int periods_in_block;
00423 
00424    s->freq = freq;
00425 
00426    /* Desired tone duration in samples */
00427    duration_samples = duration * SAMPLE_RATE / 1000;
00428    /* We want to allow 10% deviation of tone duration */
00429    duration_samples = duration_samples * 9 / 10;
00430 
00431    /* If we want to remove tone, it is important to have block size not
00432       to exceed frame size. Otherwise by the moment tone is detected it is too late
00433       to squelch it from previous frames */
00434    s->block_size = SAMPLES_IN_FRAME;
00435 
00436    periods_in_block = s->block_size * freq / SAMPLE_RATE;
00437 
00438    /* Make sure we will have at least 5 periods at target frequency for analisys.
00439       This may make block larger than expected packet and will make squelching impossible
00440       but at least we will be detecting the tone */
00441    if (periods_in_block < 5)
00442       periods_in_block = 5;
00443 
00444    /* Now calculate final block size. It will contain integer number of periods */
00445    s->block_size = periods_in_block * SAMPLE_RATE / freq;
00446 
00447    /* tone_detect is currently only used to detect fax tones and we
00448       do not need suqlching the fax tones */
00449    s->squelch = 0;
00450 
00451    /* Account for the first and the last block to be incomplete
00452       and thus no tone will be detected in them */
00453    s->hits_required = (duration_samples - (s->block_size - 1)) / s->block_size;
00454 
00455    goertzel_init(&s->tone, freq, s->block_size);
00456 
00457    s->samples_pending = s->block_size;
00458    s->hit_count = 0;
00459    s->last_hit = 0;
00460    s->energy = 0.0;
00461 
00462    /* We want tone energy to be amp decibels above the rest of the signal (the noise).
00463       According to Parseval's theorem the energy computed in time domain equals to energy
00464       computed in frequency domain. So subtracting energy in the frequency domain (Goertzel result)
00465       from the energy in the time domain we will get energy of the remaining signal (without the tone
00466       we are detecting). We will be checking that
00467       10*log(Ew / (Et - Ew)) > amp
00468       Calculate threshold so that we will be actually checking
00469       Ew > Et * threshold
00470    */
00471 
00472    x = pow(10.0, amp / 10.0);
00473    s->threshold = x / (x + 1);
00474 
00475    ast_debug(1, "Setup tone %d Hz, %d ms, block_size=%d, hits_required=%d\n", freq, duration, s->block_size, s->hits_required);
00476 }
00477 
00478 static void ast_fax_detect_init(struct ast_dsp *s)
00479 {
00480    ast_tone_detect_init(&s->cng_tone_state, FAX_TONE_CNG_FREQ, FAX_TONE_CNG_DURATION, FAX_TONE_CNG_DB);
00481    ast_tone_detect_init(&s->ced_tone_state, FAX_TONE_CED_FREQ, FAX_TONE_CED_DURATION, FAX_TONE_CED_DB);
00482 }
00483 
00484 static void ast_dtmf_detect_init (dtmf_detect_state_t *s)
00485 {
00486    int i;
00487 
00488    s->lasthit = 0;
00489    s->current_hit = 0;
00490    for (i = 0;  i < 4;  i++) {
00491       goertzel_init(&s->row_out[i], dtmf_row[i], DTMF_GSIZE);
00492       goertzel_init(&s->col_out[i], dtmf_col[i], DTMF_GSIZE);
00493       s->energy = 0.0;
00494    }
00495    s->current_sample = 0;
00496    s->hits = 0;
00497    s->misses = 0;
00498 
00499    s->hits_to_begin = DTMF_HITS_TO_BEGIN;
00500    s->misses_to_end = DTMF_MISSES_TO_END;
00501 }
00502 
00503 static void ast_mf_detect_init (mf_detect_state_t *s)
00504 {
00505    int i;
00506    s->hits[0] = s->hits[1] = s->hits[2] = s->hits[3] = s->hits[4] = 0;
00507    for (i = 0;  i < 6;  i++) {
00508       goertzel_init (&s->tone_out[i], mf_tones[i], 160);
00509    }
00510    s->current_sample = 0;
00511    s->current_hit = 0;
00512 }
00513 
00514 static void ast_digit_detect_init(digit_detect_state_t *s, int mf)
00515 {
00516    s->current_digits = 0;
00517    s->detected_digits = 0;
00518    s->lost_digits = 0;
00519    s->digits[0] = '\0';
00520 
00521    if (mf) {
00522       ast_mf_detect_init(&s->td.mf);
00523    } else {
00524       ast_dtmf_detect_init(&s->td.dtmf);
00525    }
00526 }
00527 
00528 static int tone_detect(struct ast_dsp *dsp, tone_detect_state_t *s, int16_t *amp, int samples)
00529 {
00530    float tone_energy;
00531    int i;
00532    int hit = 0;
00533    int limit;
00534    int res = 0;
00535    int16_t *ptr;
00536    int start, end;
00537    fragment_t mute = {0, 0};
00538 
00539    if (s->squelch && s->mute_samples > 0) {
00540       mute.end = (s->mute_samples < samples) ? s->mute_samples : samples;
00541       s->mute_samples -= mute.end;
00542    }
00543 
00544    for (start = 0;  start < samples;  start = end) {
00545       /* Process in blocks. */
00546       limit = samples - start;
00547       if (limit > s->samples_pending) {
00548          limit = s->samples_pending;
00549       }
00550       end = start + limit;
00551 
00552       for (i = limit, ptr = amp ; i > 0; i--, ptr++) {
00553          /* signed 32 bit int should be enough to suqare any possible signed 16 bit value */
00554          s->energy += (int32_t) *ptr * (int32_t) *ptr;
00555 
00556          goertzel_sample(&s->tone, *ptr);
00557       }
00558 
00559       s->samples_pending -= limit;
00560 
00561       if (s->samples_pending) {
00562          /* Finished incomplete (last) block */
00563          break;
00564       }
00565 
00566       tone_energy = goertzel_result(&s->tone);
00567 
00568       /* Scale to make comparable */
00569       tone_energy *= 2.0;
00570       s->energy *= s->block_size;
00571 
00572       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));
00573       hit = 0;
00574       if (tone_energy > s->energy * s->threshold) {
00575          ast_debug(10, "Hit! count=%d\n", s->hit_count);
00576          hit = 1;
00577       }
00578 
00579       if (s->hit_count) {
00580          s->hit_count++;
00581       }
00582 
00583       if (hit == s->last_hit) {
00584          if (!hit) {
00585             /* Two successive misses. Tone ended */
00586             s->hit_count = 0;
00587          } else if (!s->hit_count) {
00588             s->hit_count++;
00589          }
00590 
00591       }
00592 
00593       if (s->hit_count == s->hits_required) {
00594          ast_debug(1, "%d Hz done detected\n", s->freq);
00595          res = 1;
00596       }
00597 
00598       s->last_hit = hit;
00599 
00600       /* If we had a hit in this block, include it into mute fragment */
00601       if (s->squelch && hit) {
00602          if (mute.end < start - s->block_size) {
00603             /* There is a gap between fragments */
00604             mute_fragment(dsp, &mute);
00605             mute.start = (start > s->block_size) ? (start - s->block_size) : 0;
00606          }
00607          mute.end = end + s->block_size;
00608       }
00609 
00610       /* Reinitialise the detector for the next block */
00611       /* Reset for the next block */
00612       goertzel_reset(&s->tone);
00613 
00614       /* Advance to the next block */
00615       s->energy = 0.0;
00616       s->samples_pending = s->block_size;
00617 
00618       amp += limit;
00619    }
00620 
00621    if (s->squelch && mute.end) {
00622       if (mute.end > samples) {
00623          s->mute_samples = mute.end - samples;
00624          mute.end = samples;
00625       }
00626       mute_fragment(dsp, &mute);
00627    }
00628 
00629    return res;
00630 }
00631 
00632 static void store_digit(digit_detect_state_t *s, char digit)
00633 {
00634    s->detected_digits++;
00635    if (s->current_digits < MAX_DTMF_DIGITS) {
00636       s->digitlen[s->current_digits] = 0;
00637       s->digits[s->current_digits++] = digit;
00638       s->digits[s->current_digits] = '\0';
00639    } else {
00640       ast_log(LOG_WARNING, "Digit lost due to full buffer\n");
00641       s->lost_digits++;
00642    }
00643 }
00644 
00645 static int dtmf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[], int samples, int squelch, int relax)
00646 {
00647    float row_energy[4];
00648    float col_energy[4];
00649    float famp;
00650    int i;
00651    int j;
00652    int sample;
00653    int best_row;
00654    int best_col;
00655    int hit;
00656    int limit;
00657    fragment_t mute = {0, 0};
00658 
00659    if (squelch && s->td.dtmf.mute_samples > 0) {
00660       mute.end = (s->td.dtmf.mute_samples < samples) ? s->td.dtmf.mute_samples : samples;
00661       s->td.dtmf.mute_samples -= mute.end;
00662    }
00663 
00664    hit = 0;
00665    for (sample = 0; sample < samples; sample = limit) {
00666       /* DTMF_GSIZE is optimised to meet the DTMF specs. */
00667       if ((samples - sample) >= (DTMF_GSIZE - s->td.dtmf.current_sample)) {
00668          limit = sample + (DTMF_GSIZE - s->td.dtmf.current_sample);
00669       } else {
00670          limit = samples;
00671       }
00672       /* The following unrolled loop takes only 35% (rough estimate) of the 
00673          time of a rolled loop on the machine on which it was developed */
00674       for (j = sample; j < limit; j++) {
00675          famp = amp[j];
00676          s->td.dtmf.energy += famp*famp;
00677          /* With GCC 2.95, the following unrolled code seems to take about 35%
00678             (rough estimate) as long as a neat little 0-3 loop */
00679          goertzel_sample(s->td.dtmf.row_out, amp[j]);
00680          goertzel_sample(s->td.dtmf.col_out, amp[j]);
00681          goertzel_sample(s->td.dtmf.row_out + 1, amp[j]);
00682          goertzel_sample(s->td.dtmf.col_out + 1, amp[j]);
00683          goertzel_sample(s->td.dtmf.row_out + 2, amp[j]);
00684          goertzel_sample(s->td.dtmf.col_out + 2, amp[j]);
00685          goertzel_sample(s->td.dtmf.row_out + 3, amp[j]);
00686          goertzel_sample(s->td.dtmf.col_out + 3, amp[j]);
00687       }
00688       s->td.dtmf.current_sample += (limit - sample);
00689       if (s->td.dtmf.current_sample < DTMF_GSIZE) {
00690          continue;
00691       }
00692       /* We are at the end of a DTMF detection block */
00693       /* Find the peak row and the peak column */
00694       row_energy[0] = goertzel_result (&s->td.dtmf.row_out[0]);
00695       col_energy[0] = goertzel_result (&s->td.dtmf.col_out[0]);
00696 
00697       for (best_row = best_col = 0, i = 1;  i < 4;  i++) {
00698          row_energy[i] = goertzel_result (&s->td.dtmf.row_out[i]);
00699          if (row_energy[i] > row_energy[best_row]) {
00700             best_row = i;
00701          }
00702          col_energy[i] = goertzel_result (&s->td.dtmf.col_out[i]);
00703          if (col_energy[i] > col_energy[best_col]) {
00704             best_col = i;
00705          }
00706       }
00707       hit = 0;
00708       /* Basic signal level test and the twist test */
00709       if (row_energy[best_row] >= DTMF_THRESHOLD && 
00710           col_energy[best_col] >= DTMF_THRESHOLD &&
00711           col_energy[best_col] < row_energy[best_row] * DTMF_REVERSE_TWIST &&
00712           col_energy[best_col] * DTMF_NORMAL_TWIST > row_energy[best_row]) {
00713          /* Relative peak test */
00714          for (i = 0;  i < 4;  i++) {
00715             if ((i != best_col &&
00716                 col_energy[i] * DTMF_RELATIVE_PEAK_COL > col_energy[best_col]) ||
00717                 (i != best_row 
00718                  && row_energy[i] * DTMF_RELATIVE_PEAK_ROW > row_energy[best_row])) {
00719                break;
00720             }
00721          }
00722          /* ... and fraction of total energy test */
00723          if (i >= 4 &&
00724              (row_energy[best_row] + col_energy[best_col]) > DTMF_TO_TOTAL_ENERGY * s->td.dtmf.energy) {
00725             /* Got a hit */
00726             hit = dtmf_positions[(best_row << 2) + best_col];
00727          }
00728       } 
00729 
00730       if (hit == s->td.dtmf.lasthit) {
00731          if (s->td.dtmf.current_hit) {
00732             /* We are in the middle of a digit already */
00733             if (hit) {
00734                if (hit != s->td.dtmf.current_hit) {
00735                   /* Look for a start of a new digit.
00736                      This is because hits_to_begin may be smaller than misses_to_end
00737                      and we may find the beginning of new digit before we consider last one ended. */
00738                   s->td.dtmf.current_hit = 0;
00739                } else {
00740                   /* Current hit was same as last, so increment digit duration (of last digit) */
00741                   s->digitlen[s->current_digits - 1] += DTMF_GSIZE;
00742                }
00743             } else {
00744                /* No Digit */
00745                s->td.dtmf.misses++;
00746                if (s->td.dtmf.misses == s->td.dtmf.misses_to_end) {
00747                   /* There were enough misses to consider digit ended */
00748                   s->td.dtmf.current_hit = 0;
00749                }
00750             }
00751          } else if (hit) {
00752             /* Detecting new digit */
00753             s->td.dtmf.hits++;
00754             if (s->td.dtmf.hits == s->td.dtmf.hits_to_begin) {
00755                store_digit(s, hit);
00756                s->td.dtmf.current_hit = hit;
00757             }
00758          }
00759       } else {
00760          s->td.dtmf.hits = 1;
00761          s->td.dtmf.misses = 1;
00762          s->td.dtmf.lasthit = hit;
00763       }
00764 
00765       /* If we had a hit in this block, include it into mute fragment */
00766       if (squelch && hit) {
00767          if (mute.end < sample - DTMF_GSIZE) {
00768             /* There is a gap between fragments */
00769             mute_fragment(dsp, &mute);
00770             mute.start = (sample > DTMF_GSIZE) ? (sample - DTMF_GSIZE) : 0;
00771          }
00772          mute.end = limit + DTMF_GSIZE;
00773       }
00774 
00775       /* Reinitialise the detector for the next block */
00776       for (i = 0; i < 4; i++) {
00777          goertzel_reset(&s->td.dtmf.row_out[i]);
00778          goertzel_reset(&s->td.dtmf.col_out[i]);
00779       }
00780       s->td.dtmf.energy = 0.0;
00781       s->td.dtmf.current_sample = 0;
00782    }
00783 
00784    if (squelch && mute.end) {
00785       if (mute.end > samples) {
00786          s->td.dtmf.mute_samples = mute.end - samples;
00787          mute.end = samples;
00788       }
00789       mute_fragment(dsp, &mute);
00790    }
00791 
00792    return (s->td.dtmf.current_hit); /* return the debounced hit */
00793 }
00794 
00795 static int mf_detect(struct ast_dsp *dsp, digit_detect_state_t *s, int16_t amp[],
00796                  int samples, int squelch, int relax)
00797 {
00798    float energy[6];
00799    int best;
00800    int second_best;
00801    int i;
00802    int j;
00803    int sample;
00804    int hit;
00805    int limit;
00806    fragment_t mute = {0, 0};
00807 
00808    if (squelch && s->td.mf.mute_samples > 0) {
00809       mute.end = (s->td.mf.mute_samples < samples) ? s->td.mf.mute_samples : samples;
00810       s->td.mf.mute_samples -= mute.end;
00811    }
00812 
00813    hit = 0;
00814    for (sample = 0;  sample < samples;  sample = limit) {
00815       /* 80 is optimised to meet the MF specs. */
00816       /* XXX So then why is MF_GSIZE defined as 120? */
00817       if ((samples - sample) >= (MF_GSIZE - s->td.mf.current_sample)) {
00818          limit = sample + (MF_GSIZE - s->td.mf.current_sample);
00819       } else {
00820          limit = samples;
00821       }
00822       /* The following unrolled loop takes only 35% (rough estimate) of the 
00823          time of a rolled loop on the machine on which it was developed */
00824       for (j = sample;  j < limit;  j++) {
00825          /* With GCC 2.95, the following unrolled code seems to take about 35%
00826             (rough estimate) as long as a neat little 0-3 loop */
00827          goertzel_sample(s->td.mf.tone_out, amp[j]);
00828          goertzel_sample(s->td.mf.tone_out + 1, amp[j]);
00829          goertzel_sample(s->td.mf.tone_out + 2, amp[j]);
00830          goertzel_sample(s->td.mf.tone_out + 3, amp[j]);
00831          goertzel_sample(s->td.mf.tone_out + 4, amp[j]);
00832          goertzel_sample(s->td.mf.tone_out + 5, amp[j]);
00833       }
00834       s->td.mf.current_sample += (limit - sample);
00835       if (s->td.mf.current_sample < MF_GSIZE) {
00836          continue;
00837       }
00838       /* We're at the end of an MF detection block.  */
00839       /* Find the two highest energies. The spec says to look for
00840          two tones and two tones only. Taking this literally -ie
00841          only two tones pass the minimum threshold - doesn't work
00842          well. The sinc function mess, due to rectangular windowing
00843          ensure that! Find the two highest energies and ensure they
00844          are considerably stronger than any of the others. */
00845       energy[0] = goertzel_result(&s->td.mf.tone_out[0]);
00846       energy[1] = goertzel_result(&s->td.mf.tone_out[1]);
00847       if (energy[0] > energy[1]) {
00848          best = 0;
00849          second_best = 1;
00850       } else {
00851          best = 1;
00852          second_best = 0;
00853       }
00854       /*endif*/
00855       for (i = 2; i < 6; i++) {
00856          energy[i] = goertzel_result(&s->td.mf.tone_out[i]);
00857          if (energy[i] >= energy[best]) {
00858             second_best = best;
00859             best = i;
00860          } else if (energy[i] >= energy[second_best]) {
00861             second_best = i;
00862          }
00863       }
00864       /* Basic signal level and twist tests */
00865       hit = 0;
00866       if (energy[best] >= BELL_MF_THRESHOLD && energy[second_best] >= BELL_MF_THRESHOLD
00867                && energy[best] < energy[second_best]*BELL_MF_TWIST
00868                && energy[best] * BELL_MF_TWIST > energy[second_best]) {
00869          /* Relative peak test */
00870          hit = -1;
00871          for (i = 0; i < 6; i++) {
00872             if (i != best && i != second_best) {
00873                if (energy[i]*BELL_MF_RELATIVE_PEAK >= energy[second_best]) {
00874                   /* The best two are not clearly the best */
00875                   hit = 0;
00876                   break;
00877                }
00878             }
00879          }
00880       }
00881       if (hit) {
00882          /* Get the values into ascending order */
00883          if (second_best < best) {
00884             i = best;
00885             best = second_best;
00886             second_best = i;
00887          }
00888          best = best * 5 + second_best - 1;
00889          hit = bell_mf_positions[best];
00890          /* Look for two successive similar results */
00891          /* The logic in the next test is:
00892             For KP we need 4 successive identical clean detects, with
00893             two blocks of something different preceeding it. For anything
00894             else we need two successive identical clean detects, with
00895             two blocks of something different preceeding it. */
00896          if (hit == s->td.mf.hits[4] && hit == s->td.mf.hits[3] &&
00897             ((hit != '*' && hit != s->td.mf.hits[2] && hit != s->td.mf.hits[1])||
00898              (hit == '*' && hit == s->td.mf.hits[2] && hit != s->td.mf.hits[1] && 
00899              hit != s->td.mf.hits[0]))) {
00900             store_digit(s, hit);
00901          }
00902       }
00903 
00904 
00905       if (hit != s->td.mf.hits[4] && hit != s->td.mf.hits[3]) {
00906          /* Two successive block without a hit terminate current digit */
00907          s->td.mf.current_hit = 0;
00908       }
00909 
00910       s->td.mf.hits[0] = s->td.mf.hits[1];
00911       s->td.mf.hits[1] = s->td.mf.hits[2];
00912       s->td.mf.hits[2] = s->td.mf.hits[3];
00913       s->td.mf.hits[3] = s->td.mf.hits[4];
00914       s->td.mf.hits[4] = hit;
00915 
00916       /* If we had a hit in this block, include it into mute fragment */
00917       if (squelch && hit) {
00918          if (mute.end < sample - MF_GSIZE) {
00919             /* There is a gap between fragments */
00920             mute_fragment(dsp, &mute);
00921             mute.start = (sample > MF_GSIZE) ? (sample - MF_GSIZE) : 0;
00922          }
00923          mute.end = limit + DTMF_GSIZE;
00924       }
00925 
00926       /* Reinitialise the detector for the next block */
00927       for (i = 0;  i < 6;  i++)
00928          goertzel_reset(&s->td.mf.tone_out[i]);
00929       s->td.mf.current_sample = 0;
00930    }
00931 
00932    if (squelch && mute.end) {
00933       if (mute.end > samples) {
00934          s->td.mf.mute_samples = mute.end - samples;
00935          mute.end = samples;
00936       }
00937       mute_fragment(dsp, &mute);
00938    }
00939 
00940    return (s->td.mf.current_hit); /* return the debounced hit */
00941 }
00942 
00943 static inline int pair_there(float p1, float p2, float i1, float i2, float e)
00944 {
00945    /* See if p1 and p2 are there, relative to i1 and i2 and total energy */
00946    /* Make sure absolute levels are high enough */
00947    if ((p1 < TONE_MIN_THRESH) || (p2 < TONE_MIN_THRESH)) {
00948       return 0;
00949    }
00950    /* Amplify ignored stuff */
00951    i2 *= TONE_THRESH;
00952    i1 *= TONE_THRESH;
00953    e *= TONE_THRESH;
00954    /* Check first tone */
00955    if ((p1 < i1) || (p1 < i2) || (p1 < e)) {
00956       return 0;
00957    }
00958    /* And second */
00959    if ((p2 < i1) || (p2 < i2) || (p2 < e)) {
00960       return 0;
00961    }
00962    /* Guess it's there... */
00963    return 1;
00964 }
00965 
00966 static int __ast_dsp_call_progress(struct ast_dsp *dsp, short *s, int len)
00967 {
00968    int x;
00969    int y;
00970    int pass;
00971    int newstate = DSP_TONE_STATE_SILENCE;
00972    int res = 0;
00973    while (len) {
00974       /* Take the lesser of the number of samples we need and what we have */
00975       pass = len;
00976       if (pass > dsp->gsamp_size - dsp->gsamps) {
00977          pass = dsp->gsamp_size - dsp->gsamps;
00978       }
00979       for (x = 0; x < pass; x++) {
00980          for (y = 0; y < dsp->freqcount; y++) {
00981             goertzel_sample(&dsp->freqs[y], s[x]);
00982          }
00983          dsp->genergy += s[x] * s[x];
00984       }
00985       s += pass;
00986       dsp->gsamps += pass;
00987       len -= pass;
00988       if (dsp->gsamps == dsp->gsamp_size) {
00989          float hz[7];
00990          for (y = 0; y < 7; y++) {
00991             hz[y] = goertzel_result(&dsp->freqs[y]);
00992          }
00993          switch (dsp->progmode) {
00994          case PROG_MODE_NA:
00995             if (pair_there(hz[HZ_480], hz[HZ_620], hz[HZ_350], hz[HZ_440], dsp->genergy)) {
00996                newstate = DSP_TONE_STATE_BUSY;
00997             } else if (pair_there(hz[HZ_440], hz[HZ_480], hz[HZ_350], hz[HZ_620], dsp->genergy)) {
00998                newstate = DSP_TONE_STATE_RINGING;
00999             } else if (pair_there(hz[HZ_350], hz[HZ_440], hz[HZ_480], hz[HZ_620], dsp->genergy)) {
01000                newstate = DSP_TONE_STATE_DIALTONE;
01001             } else if (hz[HZ_950] > TONE_MIN_THRESH * TONE_THRESH) {
01002                newstate = DSP_TONE_STATE_SPECIAL1;
01003             } else if (hz[HZ_1400] > TONE_MIN_THRESH * TONE_THRESH) {
01004                /* End of SPECIAL1 or middle of SPECIAL2 */
01005                if (dsp->tstate == DSP_TONE_STATE_SPECIAL1 || dsp->tstate == DSP_TONE_STATE_SPECIAL2) {
01006                   newstate = DSP_TONE_STATE_SPECIAL2;
01007                }
01008             } else if (hz[HZ_1800] > TONE_MIN_THRESH * TONE_THRESH) {
01009                /* End of SPECIAL2 or middle of SPECIAL3 */
01010                if (dsp->tstate == DSP_TONE_STATE_SPECIAL2 || dsp->tstate == DSP_TONE_STATE_SPECIAL3) {
01011                   newstate = DSP_TONE_STATE_SPECIAL3;
01012                }
01013             } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
01014                newstate = DSP_TONE_STATE_TALKING;
01015             } else {
01016                newstate = DSP_TONE_STATE_SILENCE;
01017             }
01018             break;
01019          case PROG_MODE_CR:
01020             if (hz[HZ_425] > TONE_MIN_THRESH * TONE_THRESH) {
01021                newstate = DSP_TONE_STATE_RINGING;
01022             } else if (dsp->genergy > TONE_MIN_THRESH * TONE_THRESH) {
01023                newstate = DSP_TONE_STATE_TALKING;
01024             } else {
01025                newstate = DSP_TONE_STATE_SILENCE;
01026             }
01027             break;
01028          case PROG_MODE_UK:
01029             if (hz[HZ_400UK] > TONE_MIN_THRESH * TONE_THRESH) {
01030                newstate = DSP_TONE_STATE_HUNGUP;
01031             } else if (pair_there(hz[HZ_350UK], hz[HZ_440UK], hz[HZ_400UK], hz[HZ_400UK], dsp->genergy)) {
01032                newstate = DSP_TONE_STATE_DIALTONE;
01033             }
01034             break;
01035          default:
01036             ast_log(LOG_WARNING, "Can't process in unknown prog mode '%d'\n", dsp->progmode);
01037          }
01038          if (newstate == dsp->tstate) {
01039             dsp->tcount++;
01040             if (dsp->ringtimeout) {
01041                dsp->ringtimeout++;
01042             }
01043             switch (dsp->tstate) {
01044             case DSP_TONE_STATE_RINGING:
01045                if ((dsp->features & DSP_PROGRESS_RINGING) &&
01046                    (dsp->tcount == THRESH_RING)) {
01047                   res = AST_CONTROL_RINGING;
01048                   dsp->ringtimeout = 1;
01049                }
01050                break;
01051             case DSP_TONE_STATE_BUSY:
01052                if ((dsp->features & DSP_PROGRESS_BUSY) &&
01053                    (dsp->tcount == THRESH_BUSY)) {
01054                   res = AST_CONTROL_BUSY;
01055                   dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
01056                }
01057                break;
01058             case DSP_TONE_STATE_TALKING:
01059                if ((dsp->features & DSP_PROGRESS_TALK) &&
01060                    (dsp->tcount == THRESH_TALK)) {
01061                   res = AST_CONTROL_ANSWER;
01062                   dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
01063                }
01064                break;
01065             case DSP_TONE_STATE_SPECIAL3:
01066                if ((dsp->features & DSP_PROGRESS_CONGESTION) &&
01067                    (dsp->tcount == THRESH_CONGESTION)) {
01068                   res = AST_CONTROL_CONGESTION;
01069                   dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
01070                }
01071                break;
01072             case DSP_TONE_STATE_HUNGUP:
01073                if ((dsp->features & DSP_FEATURE_CALL_PROGRESS) &&
01074                    (dsp->tcount == THRESH_HANGUP)) {
01075                   res = AST_CONTROL_HANGUP;
01076                   dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
01077                }
01078                break;
01079             }
01080             if (dsp->ringtimeout == THRESH_RING2ANSWER) {
01081                ast_debug(1, "Consider call as answered because of timeout after last ring\n");
01082                res = AST_CONTROL_ANSWER;
01083                dsp->features &= ~DSP_FEATURE_CALL_PROGRESS;
01084             }
01085          } else {
01086             ast_debug(5, "Stop state %d with duration %d\n", dsp->tstate, dsp->tcount);
01087             ast_debug(5, "Start state %d\n", newstate);
01088             dsp->tstate = newstate;
01089             dsp->tcount = 1;
01090          }
01091 
01092          /* Reset goertzel */
01093          for (x = 0; x < 7; x++) {
01094             dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
01095          }
01096          dsp->gsamps = 0;
01097          dsp->genergy = 0.0;
01098       }
01099    }
01100 
01101    return res;
01102 }
01103 
01104 int ast_dsp_call_progress(struct ast_dsp *dsp, struct ast_frame *inf)
01105 {
01106    if (inf->frametype != AST_FRAME_VOICE) {
01107       ast_log(LOG_WARNING, "Can't check call progress of non-voice frames\n");
01108       return 0;
01109    }
01110    if (inf->subclass.codec != AST_FORMAT_SLINEAR) {
01111       ast_log(LOG_WARNING, "Can only check call progress in signed-linear frames\n");
01112       return 0;
01113    }
01114    return __ast_dsp_call_progress(dsp, inf->data.ptr, inf->datalen / 2);
01115 }
01116 
01117 static int __ast_dsp_silence_noise(struct ast_dsp *dsp, short *s, int len, int *totalsilence, int *totalnoise)
01118 {
01119    int accum;
01120    int x;
01121    int res = 0;
01122 
01123    if (!len) {
01124       return 0;
01125    }
01126    accum = 0;
01127    for (x = 0; x < len; x++) {
01128       accum += abs(s[x]);
01129    }
01130    accum /= len;
01131    if (accum < dsp->threshold) {
01132       /* Silent */
01133       dsp->totalsilence += len / 8;
01134       if (dsp->totalnoise) {
01135          /* Move and save history */
01136          memmove(dsp->historicnoise + DSP_HISTORY - dsp->busycount, dsp->historicnoise + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicnoise[0]));
01137          dsp->historicnoise[DSP_HISTORY - 1] = dsp->totalnoise;
01138 /* we don't want to check for busydetect that frequently */
01139 #if 0
01140          dsp->busymaybe = 1;
01141 #endif
01142       }
01143       dsp->totalnoise = 0;
01144       res = 1;
01145    } else {
01146       /* Not silent */
01147       dsp->totalnoise += len / 8;
01148       if (dsp->totalsilence) {
01149          int silence1 = dsp->historicsilence[DSP_HISTORY - 1];
01150          int silence2 = dsp->historicsilence[DSP_HISTORY - 2];
01151          /* Move and save history */
01152          memmove(dsp->historicsilence + DSP_HISTORY - dsp->busycount, dsp->historicsilence + DSP_HISTORY - dsp->busycount + 1, dsp->busycount * sizeof(dsp->historicsilence[0]));
01153          dsp->historicsilence[DSP_HISTORY - 1] = dsp->totalsilence;
01154          /* check if the previous sample differs only by BUSY_PERCENT from the one before it */
01155          if (silence1 < silence2) {
01156             if (silence1 + silence1 * BUSY_PERCENT / 100 >= silence2) {
01157                dsp->busymaybe = 1;
01158             } else {
01159                dsp->busymaybe = 0;
01160             }
01161          } else {
01162             if (silence1 - silence1 * BUSY_PERCENT / 100 <= silence2) {
01163                dsp->busymaybe = 1;
01164             } else {
01165                dsp->busymaybe = 0;
01166             }
01167          }
01168       }
01169       dsp->totalsilence = 0;
01170    }
01171    if (totalsilence) {
01172       *totalsilence = dsp->totalsilence;
01173    }
01174    if (totalnoise) {
01175       *totalnoise = dsp->totalnoise;
01176    }
01177    return res;
01178 }
01179 
01180 int ast_dsp_busydetect(struct ast_dsp *dsp)
01181 {
01182    int res = 0, x;
01183 #ifndef BUSYDETECT_TONEONLY
01184    int avgsilence = 0, hitsilence = 0;
01185 #endif
01186    int avgtone = 0, hittone = 0;
01187    if (!dsp->busymaybe) {
01188       return res;
01189    }
01190    for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
01191 #ifndef BUSYDETECT_TONEONLY
01192       avgsilence += dsp->historicsilence[x];
01193 #endif
01194       avgtone += dsp->historicnoise[x];
01195    }
01196 #ifndef BUSYDETECT_TONEONLY
01197    avgsilence /= dsp->busycount;
01198 #endif
01199    avgtone /= dsp->busycount;
01200    for (x = DSP_HISTORY - dsp->busycount; x < DSP_HISTORY; x++) {
01201 #ifndef BUSYDETECT_TONEONLY
01202       if (avgsilence > dsp->historicsilence[x]) {
01203          if (avgsilence - (avgsilence * BUSY_PERCENT / 100) <= dsp->historicsilence[x]) {
01204             hitsilence++;
01205          }
01206       } else {
01207          if (avgsilence + (avgsilence * BUSY_PERCENT / 100) >= dsp->historicsilence[x]) {
01208             hitsilence++;
01209          }
01210       }
01211 #endif
01212       if (avgtone > dsp->historicnoise[x]) {
01213          if (avgtone - (avgtone * BUSY_PERCENT / 100) <= dsp->historicnoise[x]) {
01214             hittone++;
01215          }
01216       } else {
01217          if (avgtone + (avgtone * BUSY_PERCENT / 100) >= dsp->historicnoise[x]) {
01218             hittone++;
01219          }
01220       }
01221    }
01222 #ifndef BUSYDETECT_TONEONLY
01223    if ((hittone >= dsp->busycount - 1) && (hitsilence >= dsp->busycount - 1) && 
01224        (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX) && 
01225        (avgsilence >= BUSY_MIN && avgsilence <= BUSY_MAX)) {
01226 #else
01227    if ((hittone >= dsp->busycount - 1) && (avgtone >= BUSY_MIN && avgtone <= BUSY_MAX)) {
01228 #endif
01229 #ifdef BUSYDETECT_COMPARE_TONE_AND_SILENCE
01230       if (avgtone > avgsilence) {
01231          if (avgtone - avgtone*BUSY_PERCENT/100 <= avgsilence) {
01232             res = 1;
01233          }
01234       } else {
01235          if (avgtone + avgtone*BUSY_PERCENT/100 >= avgsilence) {
01236             res = 1;
01237          }
01238       }
01239 #else
01240       res = 1;
01241 #endif
01242    }
01243    /* If we know the expected busy tone length, check we are in the range */
01244    if (res && (dsp->busy_tonelength > 0)) {
01245       if (abs(avgtone - dsp->busy_tonelength) > MAX(dsp->busy_tonelength*BUSY_PAT_PERCENT/100, 20)) {
01246 #ifdef BUSYDETECT_DEBUG
01247          ast_debug(5, "busy detector: avgtone of %d not close enough to desired %d\n",
01248             avgtone, dsp->busy_tonelength);
01249 #endif
01250          res = 0;
01251       }
01252    }
01253 #ifndef BUSYDETECT_TONEONLY
01254    /* If we know the expected busy tone silent-period length, check we are in the range */
01255    if (res && (dsp->busy_quietlength > 0)) {
01256       if (abs(avgsilence - dsp->busy_quietlength) > MAX(dsp->busy_quietlength*BUSY_PAT_PERCENT/100, 20)) {
01257 #ifdef BUSYDETECT_DEBUG
01258       ast_debug(5, "busy detector: avgsilence of %d not close enough to desired %d\n",
01259          avgsilence, dsp->busy_quietlength);
01260 #endif
01261          res = 0;
01262       }
01263    }
01264 #endif
01265 #if !defined(BUSYDETECT_TONEONLY) && defined(BUSYDETECT_DEBUG)
01266    if (res) {
01267       ast_debug(5, "ast_dsp_busydetect detected busy, avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
01268    } else {
01269       ast_debug(5, "busy detector: FAILED with avgtone: %d, avgsilence %d\n", avgtone, avgsilence);
01270    }
01271 #endif
01272    return res;
01273 }
01274 
01275 int ast_dsp_silence(struct ast_dsp *dsp, struct ast_frame *f, int *totalsilence)
01276 {
01277    short *s;
01278    int len;
01279    
01280    if (f->frametype != AST_FRAME_VOICE) {
01281       ast_log(LOG_WARNING, "Can't calculate silence on a non-voice frame\n");
01282       return 0;
01283    }
01284    if (f->subclass.codec != AST_FORMAT_SLINEAR) {
01285       ast_log(LOG_WARNING, "Can only calculate silence on signed-linear frames :(\n");
01286       return 0;
01287    }
01288    s = f->data.ptr;
01289    len = f->datalen/2;
01290    return __ast_dsp_silence_noise(dsp, s, len, totalsilence, NULL);
01291 }
01292 
01293 int ast_dsp_noise(struct ast_dsp *dsp, struct ast_frame *f, int *totalnoise)
01294 {
01295        short *s;
01296        int len;
01297 
01298        if (f->frametype != AST_FRAME_VOICE) {
01299                ast_log(LOG_WARNING, "Can't calculate noise on a non-voice frame\n");
01300                return 0;
01301        }
01302        if (f->subclass.codec != AST_FORMAT_SLINEAR) {
01303                ast_log(LOG_WARNING, "Can only calculate noise on signed-linear frames :(\n");
01304                return 0;
01305        }
01306        s = f->data.ptr;
01307        len = f->datalen/2;
01308        return __ast_dsp_silence_noise(dsp, s, len, NULL, totalnoise);
01309 }
01310 
01311 
01312 struct ast_frame *ast_dsp_process(struct ast_channel *chan, struct ast_dsp *dsp, struct ast_frame *af)
01313 {
01314    int silence;
01315    int res;
01316    int digit = 0, fax_digit = 0;
01317    int x;
01318    short *shortdata;
01319    unsigned char *odata;
01320    int len;
01321    struct ast_frame *outf = NULL;
01322 
01323    if (!af) {
01324       return NULL;
01325    }
01326    if (af->frametype != AST_FRAME_VOICE) {
01327       return af;
01328    }
01329 
01330    odata = af->data.ptr;
01331    len = af->datalen;
01332    /* Make sure we have short data */
01333    switch (af->subclass.codec) {
01334    case AST_FORMAT_SLINEAR:
01335       shortdata = af->data.ptr;
01336       len = af->datalen / 2;
01337       break;
01338    case AST_FORMAT_ULAW:
01339    case AST_FORMAT_TESTLAW:
01340       shortdata = alloca(af->datalen * 2);
01341       for (x = 0;x < len; x++) {
01342          shortdata[x] = AST_MULAW(odata[x]);
01343       }
01344       break;
01345    case AST_FORMAT_ALAW:
01346       shortdata = alloca(af->datalen * 2);
01347       for (x = 0; x < len; x++) {
01348          shortdata[x] = AST_ALAW(odata[x]);
01349       }
01350       break;
01351    default:
01352       /*Display warning only once. Otherwise you would get hundreds of warnings every second */
01353       if (dsp->display_inband_dtmf_warning)
01354          ast_log(LOG_WARNING, "Inband DTMF is not supported on codec %s. Use RFC2833\n", ast_getformatname(af->subclass.codec));
01355       dsp->display_inband_dtmf_warning = 0;
01356       return af;
01357    }
01358 
01359    /* Initially we do not want to mute anything */
01360    dsp->mute_fragments = 0;
01361 
01362    /* Need to run the silence detection stuff for silence suppression and busy detection */
01363    if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) || (dsp->features & DSP_FEATURE_BUSY_DETECT)) {
01364       res = __ast_dsp_silence_noise(dsp, shortdata, len, &silence, NULL);
01365    }
01366 
01367    if ((dsp->features & DSP_FEATURE_SILENCE_SUPPRESS) && silence) {
01368       memset(&dsp->f, 0, sizeof(dsp->f));
01369       dsp->f.frametype = AST_FRAME_NULL;
01370       ast_frfree(af);
01371       return ast_frisolate(&dsp->f);
01372    }
01373    if ((dsp->features & DSP_FEATURE_BUSY_DETECT) && ast_dsp_busydetect(dsp)) {
01374       chan->_softhangup |= AST_SOFTHANGUP_DEV;
01375       memset(&dsp->f, 0, sizeof(dsp->f));
01376       dsp->f.frametype = AST_FRAME_CONTROL;
01377       dsp->f.subclass.integer = AST_CONTROL_BUSY;
01378       ast_frfree(af);
01379       ast_debug(1, "Requesting Hangup because the busy tone was detected on channel %s\n", chan->name);
01380       return ast_frisolate(&dsp->f);
01381    }
01382 
01383    if ((dsp->features & DSP_FEATURE_FAX_DETECT)) {
01384       if ((dsp->faxmode & DSP_FAXMODE_DETECT_CNG) && tone_detect(dsp, &dsp->cng_tone_state, shortdata, len)) {
01385          fax_digit = 'f';
01386       }
01387 
01388       if ((dsp->faxmode & DSP_FAXMODE_DETECT_CED) && tone_detect(dsp, &dsp->ced_tone_state, shortdata, len)) {
01389          fax_digit = 'e';
01390       }
01391    }
01392 
01393    if (dsp->features & (DSP_FEATURE_DIGIT_DETECT | DSP_FEATURE_BUSY_DETECT)) {
01394       if (dsp->digitmode & DSP_DIGITMODE_MF)
01395          digit = mf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
01396       else
01397          digit = dtmf_detect(dsp, &dsp->digit_state, shortdata, len, (dsp->digitmode & DSP_DIGITMODE_NOQUELCH) == 0, (dsp->digitmode & DSP_DIGITMODE_RELAXDTMF));
01398 
01399       if (dsp->digit_state.current_digits) {
01400          int event = 0, event_len = 0;
01401          char event_digit = 0;
01402 
01403          if (!dsp->dtmf_began) {
01404             /* We have not reported DTMF_BEGIN for anything yet */
01405 
01406             if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
01407                event = AST_FRAME_DTMF_BEGIN;
01408                event_digit = dsp->digit_state.digits[0];
01409             }
01410             dsp->dtmf_began = 1;
01411 
01412          } else if (dsp->digit_state.current_digits > 1 || digit != dsp->digit_state.digits[0]) {
01413             /* Digit changed. This means digit we have reported with DTMF_BEGIN ended */
01414             if (dsp->features & DSP_FEATURE_DIGIT_DETECT) {
01415                event = AST_FRAME_DTMF_END;
01416                event_digit = dsp->digit_state.digits[0];
01417                event_len = dsp->digit_state.digitlen[0] * 1000 / SAMPLE_RATE;
01418             }
01419             memmove(&dsp->digit_state.digits[0], &dsp->digit_state.digits[1], dsp->digit_state.current_digits);
01420             memmove(&dsp->digit_state.digitlen[0], &dsp->digit_state.digitlen[1], dsp->digit_state.current_digits * sizeof(dsp->digit_state.digitlen[0]));
01421             dsp->digit_state.current_digits--;
01422             dsp->dtmf_began = 0;
01423 
01424             if (dsp->features & DSP_FEATURE_BUSY_DETECT) {
01425                /* Reset Busy Detector as we have some confirmed activity */ 
01426                memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
01427                memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));
01428                ast_debug(1, "DTMF Detected - Reset busydetector\n");
01429             }
01430          }
01431 
01432          if (event) {
01433             memset(&dsp->f, 0, sizeof(dsp->f));
01434             dsp->f.frametype = event;
01435             dsp->f.subclass.integer = event_digit;
01436             dsp->f.len = event_len;
01437             outf = &dsp->f;
01438             goto done;
01439          }
01440       }
01441    }
01442 
01443    if (fax_digit) {
01444       /* Fax was detected - digit is either 'f' or 'e' */
01445 
01446       memset(&dsp->f, 0, sizeof(dsp->f));
01447       dsp->f.frametype = AST_FRAME_DTMF;
01448       dsp->f.subclass.integer = fax_digit;
01449       outf = &dsp->f;
01450       goto done;
01451    }
01452 
01453    if ((dsp->features & DSP_FEATURE_CALL_PROGRESS)) {
01454       res = __ast_dsp_call_progress(dsp, shortdata, len);
01455       if (res) {
01456          switch (res) {
01457          case AST_CONTROL_ANSWER:
01458          case AST_CONTROL_BUSY:
01459          case AST_CONTROL_RINGING:
01460          case AST_CONTROL_CONGESTION:
01461          case AST_CONTROL_HANGUP:
01462             memset(&dsp->f, 0, sizeof(dsp->f));
01463             dsp->f.frametype = AST_FRAME_CONTROL;
01464             dsp->f.subclass.integer = res;
01465             dsp->f.src = "dsp_progress";
01466             if (chan) 
01467                ast_queue_frame(chan, &dsp->f);
01468             break;
01469          default:
01470             ast_log(LOG_WARNING, "Don't know how to represent call progress message %d\n", res);
01471          }
01472       }
01473    } else if ((dsp->features & DSP_FEATURE_WAITDIALTONE)) {
01474       res = __ast_dsp_call_progress(dsp, shortdata, len);
01475    }
01476 
01477 done:
01478    /* Mute fragment of the frame */
01479    for (x = 0; x < dsp->mute_fragments; x++) {
01480       memset(shortdata + dsp->mute_data[x].start, 0, sizeof(int16_t) * (dsp->mute_data[x].end - dsp->mute_data[x].start));
01481    }
01482 
01483    switch (af->subclass.codec) {
01484    case AST_FORMAT_SLINEAR:
01485       break;
01486    case AST_FORMAT_ULAW:
01487       for (x = 0; x < len; x++) {
01488          odata[x] = AST_LIN2MU((unsigned short) shortdata[x]);
01489       }
01490       break;
01491    case AST_FORMAT_ALAW:
01492       for (x = 0; x < len; x++) {
01493          odata[x] = AST_LIN2A((unsigned short) shortdata[x]);
01494       }
01495       break;
01496    }
01497 
01498    if (outf) {
01499       if (chan) {
01500          ast_queue_frame(chan, af);
01501       }
01502       ast_frfree(af);
01503       return ast_frisolate(outf);
01504    } else {
01505       return af;
01506    }
01507 }
01508 
01509 static void ast_dsp_prog_reset(struct ast_dsp *dsp)
01510 {
01511    int max = 0;
01512    int x;
01513    
01514    dsp->gsamp_size = modes[dsp->progmode].size;
01515    dsp->gsamps = 0;
01516    for (x = 0; x < ARRAY_LEN(modes[dsp->progmode].freqs); x++) {
01517       if (modes[dsp->progmode].freqs[x]) {
01518          goertzel_init(&dsp->freqs[x], (float)modes[dsp->progmode].freqs[x], dsp->gsamp_size);
01519          max = x + 1;
01520       }
01521    }
01522    dsp->freqcount = max;
01523    dsp->ringtimeout= 0;
01524 }
01525 
01526 struct ast_dsp *ast_dsp_new(void)
01527 {
01528    struct ast_dsp *dsp;
01529    
01530    if ((dsp = ast_calloc(1, sizeof(*dsp)))) {      
01531       dsp->threshold = DEFAULT_THRESHOLD;
01532       dsp->features = DSP_FEATURE_SILENCE_SUPPRESS;
01533       dsp->busycount = DSP_HISTORY;
01534       dsp->digitmode = DSP_DIGITMODE_DTMF;
01535       dsp->faxmode = DSP_FAXMODE_DETECT_CNG;
01536       /* Initialize digit detector */
01537       ast_digit_detect_init(&dsp->digit_state, dsp->digitmode & DSP_DIGITMODE_MF);
01538       dsp->display_inband_dtmf_warning = 1;
01539       /* Initialize initial DSP progress detect parameters */
01540       ast_dsp_prog_reset(dsp);
01541       /* Initialize fax detector */
01542       ast_fax_detect_init(dsp);
01543    }
01544    return dsp;
01545 }
01546 
01547 void ast_dsp_set_features(struct ast_dsp *dsp, int features)
01548 {
01549    dsp->features = features;
01550    if (!(features & DSP_FEATURE_DIGIT_DETECT)) {
01551       dsp->display_inband_dtmf_warning = 0;
01552    }
01553 }
01554 
01555 void ast_dsp_free(struct ast_dsp *dsp)
01556 {
01557    ast_free(dsp);
01558 }
01559 
01560 void ast_dsp_set_threshold(struct ast_dsp *dsp, int threshold)
01561 {
01562    dsp->threshold = threshold;
01563 }
01564 
01565 void ast_dsp_set_busy_count(struct ast_dsp *dsp, int cadences)
01566 {
01567    if (cadences < 4) {
01568       cadences = 4;
01569    }
01570    if (cadences > DSP_HISTORY) {
01571       cadences = DSP_HISTORY;
01572    }
01573    dsp->busycount = cadences;
01574 }
01575 
01576 void ast_dsp_set_busy_pattern(struct ast_dsp *dsp, int tonelength, int quietlength)
01577 {
01578    dsp->busy_tonelength = tonelength;
01579    dsp->busy_quietlength = quietlength;
01580    ast_debug(1, "dsp busy pattern set to %d,%d\n", tonelength, quietlength);
01581 }
01582 
01583 void ast_dsp_digitreset(struct ast_dsp *dsp)
01584 {
01585    int i;
01586    
01587    dsp->dtmf_began = 0;
01588    if (dsp->digitmode & DSP_DIGITMODE_MF) {
01589       mf_detect_state_t *s = &dsp->digit_state.td.mf;
01590       /* Reinitialise the detector for the next block */
01591       for (i = 0;  i < 6;  i++) {
01592          goertzel_reset(&s->tone_out[i]);
01593       }
01594       s->hits[4] = s->hits[3] = s->hits[2] = s->hits[1] = s->hits[0] = s->current_hit = 0;
01595       s->current_sample = 0;
01596    } else {
01597       dtmf_detect_state_t *s = &dsp->digit_state.td.dtmf;
01598       /* Reinitialise the detector for the next block */
01599       for (i = 0;  i < 4;  i++) {
01600          goertzel_reset(&s->row_out[i]);
01601          goertzel_reset(&s->col_out[i]);
01602       }
01603       s->lasthit = s->current_hit = 0;
01604       s->energy = 0.0;
01605       s->current_sample = 0;
01606       s->hits = 0;
01607       s->misses = 0;
01608    }
01609 
01610    dsp->digit_state.digits[0] = '\0';
01611    dsp->digit_state.current_digits = 0;
01612 }
01613 
01614 void ast_dsp_reset(struct ast_dsp *dsp)
01615 {
01616    int x;
01617    
01618    dsp->totalsilence = 0;
01619    dsp->gsamps = 0;
01620    for (x = 0; x < 4; x++) {
01621       dsp->freqs[x].v2 = dsp->freqs[x].v3 = 0.0;
01622    }
01623    memset(dsp->historicsilence, 0, sizeof(dsp->historicsilence));
01624    memset(dsp->historicnoise, 0, sizeof(dsp->historicnoise));  
01625    dsp->ringtimeout= 0;
01626 }
01627 
01628 int ast_dsp_set_digitmode(struct ast_dsp *dsp, int digitmode)
01629 {
01630    int new;
01631    int old;
01632    
01633    old = dsp->digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
01634    new = digitmode & (DSP_DIGITMODE_DTMF | DSP_DIGITMODE_MF | DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX);
01635    if (old != new) {
01636       /* Must initialize structures if switching from MF to DTMF or vice-versa */
01637       ast_digit_detect_init(&dsp->digit_state, new & DSP_DIGITMODE_MF);
01638    }
01639    dsp->digitmode = digitmode;
01640    return 0;
01641 }
01642 
01643 int ast_dsp_set_faxmode(struct ast_dsp *dsp, int faxmode)
01644 {
01645    if (dsp->faxmode != faxmode) {
01646       ast_fax_detect_init(dsp);
01647    }
01648    dsp->faxmode = faxmode;
01649    return 0;
01650 }
01651 
01652 int ast_dsp_set_call_progress_zone(struct ast_dsp *dsp, char *zone)
01653 {
01654    int x;
01655    
01656    for (x = 0; x < ARRAY_LEN(aliases); x++) {
01657       if (!strcasecmp(aliases[x].name, zone)) {
01658          dsp->progmode = aliases[x].mode;
01659          ast_dsp_prog_reset(dsp);
01660          return 0;
01661       }
01662    }
01663    return -1;
01664 }
01665 
01666 int ast_dsp_was_muted(struct ast_dsp *dsp)
01667 {
01668    return (dsp->mute_fragments > 0);
01669 }
01670 
01671 int ast_dsp_get_tstate(struct ast_dsp *dsp) 
01672 {
01673    return dsp->tstate;
01674 }
01675 
01676 int ast_dsp_get_tcount(struct ast_dsp *dsp) 
01677 {
01678    return dsp->tcount;
01679 }
01680 
01681 static int _dsp_init(int reload)
01682 {
01683    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
01684    struct ast_config *cfg;
01685 
01686    cfg = ast_config_load2(CONFIG_FILE_NAME, "dsp", config_flags);
01687    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
01688       ast_verb(5, "Can't find dsp config file %s. Assuming default silencethreshold of %d.\n", CONFIG_FILE_NAME, DEFAULT_SILENCE_THRESHOLD);
01689       thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
01690       return 0;
01691    }
01692 
01693    if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
01694       return 0;
01695    }
01696 
01697    if (cfg) {
01698       const char *value;
01699 
01700       value = ast_variable_retrieve(cfg, "default", "silencethreshold");
01701       if (value && sscanf(value, "%30d", &thresholds[THRESHOLD_SILENCE]) != 1) {
01702          ast_verb(5, "%s: '%s' is not a valid silencethreshold value\n", CONFIG_FILE_NAME, value);
01703          thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
01704       } else if (!value) {
01705          thresholds[THRESHOLD_SILENCE] = DEFAULT_SILENCE_THRESHOLD;
01706       }
01707 
01708       ast_config_destroy(cfg);
01709    }
01710    return 0;
01711 }
01712 
01713 int ast_dsp_get_threshold_from_settings(enum threshold which)
01714 {
01715    return thresholds[which];
01716 }
01717 
01718 int ast_dsp_init(void)
01719 {
01720    return _dsp_init(0);
01721 }
01722 
01723 int ast_dsp_reload(void)
01724 {
01725    return _dsp_init(1);
01726 }
01727 

Generated on 30 Aug 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1