use the proper type for storing group number bits so that if someone specifies 'group...
[asterisk-bristuff.git] / apps / app_amd.c
blobe5dee1efc528fa7c8341846ff153e12ffe95be44
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2003 - 2006, Aheeva Technology.
6 * Claude Klimos (claude.klimos@aheeva.com)
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
18 * A license has been granted to Digium (via disclaimer) for the use of
19 * this code.
22 #include "asterisk.h"
24 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
26 #include <stdio.h>
27 #include <stdlib.h>
29 #include "asterisk/module.h"
30 #include "asterisk/lock.h"
31 #include "asterisk/options.h"
32 #include "asterisk/channel.h"
33 #include "asterisk/dsp.h"
34 #include "asterisk/pbx.h"
35 #include "asterisk/config.h"
36 #include "asterisk/app.h"
39 static char *app = "AMD";
40 static char *synopsis = "Attempts to detect answering machines";
41 static char *descrip =
42 " AMD([initialSilence][|greeting][|afterGreetingSilence][|totalAnalysisTime]\n"
43 " [|minimumWordLength][|betweenWordsSilence][|maximumNumberOfWords]\n"
44 " [|silenceThreshold])\n"
45 " This application attempts to detect answering machines at the beginning\n"
46 " of outbound calls. Simply call this application after the call\n"
47 " has been answered (outbound only, of course).\n"
48 " When loaded, AMD reads amd.conf and uses the parameters specified as\n"
49 " default values. Those default values get overwritten when calling AMD\n"
50 " with parameters.\n"
51 "- 'initialSilence' is the maximum silence duration before the greeting. If\n"
52 " exceeded then MACHINE.\n"
53 "- 'greeting' is the maximum length of a greeting. If exceeded then MACHINE.\n"
54 "- 'afterGreetingSilence' is the silence after detecting a greeting.\n"
55 " If exceeded then HUMAN.\n"
56 "- 'totalAnalysisTime' is the maximum time allowed for the algorithm to decide\n"
57 " on a HUMAN or MACHINE.\n"
58 "- 'minimumWordLength'is the minimum duration of Voice to considered as a word.\n"
59 "- 'betweenWordsSilence' is the minimum duration of silence after a word to \n"
60 " consider the audio that follows as a new word.\n"
61 "- 'maximumNumberOfWords'is the maximum number of words in the greeting. \n"
62 " If exceeded then MACHINE.\n"
63 "- 'silenceThreshold' is the silence threshold.\n"
64 "This application sets the following channel variable upon completion:\n"
65 " AMDSTATUS - This is the status of the answering machine detection.\n"
66 " Possible values are:\n"
67 " MACHINE | HUMAN | NOTSURE | HANGUP\n"
68 " AMDCAUSE - Indicates the cause that led to the conclusion.\n"
69 " Possible values are:\n"
70 " TOOLONG-<%d total_time>\n"
71 " INITIALSILENCE-<%d silenceDuration>-<%d initialSilence>\n"
72 " HUMAN-<%d silenceDuration>-<%d afterGreetingSilence>\n"
73 " MAXWORDS-<%d wordsCount>-<%d maximumNumberOfWords>\n"
74 " LONGGREETING-<%d voiceDuration>-<%d greeting>\n";
76 #define STATE_IN_WORD 1
77 #define STATE_IN_SILENCE 2
79 /* Some default values for the algorithm parameters. These defaults will be overwritten from amd.conf */
80 static int dfltInitialSilence = 2500;
81 static int dfltGreeting = 1500;
82 static int dfltAfterGreetingSilence = 800;
83 static int dfltTotalAnalysisTime = 5000;
84 static int dfltMinimumWordLength = 100;
85 static int dfltBetweenWordsSilence = 50;
86 static int dfltMaximumNumberOfWords = 3;
87 static int dfltSilenceThreshold = 256;
89 static void isAnsweringMachine(struct ast_channel *chan, void *data)
91 int res = 0;
92 struct ast_frame *f = NULL;
93 struct ast_dsp *silenceDetector = NULL;
94 int dspsilence = 0, readFormat, framelength;
95 int inInitialSilence = 1;
96 int inGreeting = 0;
97 int voiceDuration = 0;
98 int silenceDuration = 0;
99 int iTotalTime = 0;
100 int iWordsCount = 0;
101 int currentState = STATE_IN_SILENCE;
102 int previousState = STATE_IN_SILENCE;
103 int consecutiveVoiceDuration = 0;
104 char amdCause[256] = "", amdStatus[256] = "";
105 char *parse = ast_strdupa(data);
107 /* Lets set the initial values of the variables that will control the algorithm.
108 The initial values are the default ones. If they are passed as arguments
109 when invoking the application, then the default values will be overwritten
110 by the ones passed as parameters. */
111 int initialSilence = dfltInitialSilence;
112 int greeting = dfltGreeting;
113 int afterGreetingSilence = dfltAfterGreetingSilence;
114 int totalAnalysisTime = dfltTotalAnalysisTime;
115 int minimumWordLength = dfltMinimumWordLength;
116 int betweenWordsSilence = dfltBetweenWordsSilence;
117 int maximumNumberOfWords = dfltMaximumNumberOfWords;
118 int silenceThreshold = dfltSilenceThreshold;
120 AST_DECLARE_APP_ARGS(args,
121 AST_APP_ARG(argInitialSilence);
122 AST_APP_ARG(argGreeting);
123 AST_APP_ARG(argAfterGreetingSilence);
124 AST_APP_ARG(argTotalAnalysisTime);
125 AST_APP_ARG(argMinimumWordLength);
126 AST_APP_ARG(argBetweenWordsSilence);
127 AST_APP_ARG(argMaximumNumberOfWords);
128 AST_APP_ARG(argSilenceThreshold);
131 if (option_verbose > 2)
132 ast_verbose(VERBOSE_PREFIX_3 "AMD: %s %s %s (Fmt: %d)\n", chan->name ,chan->cid.cid_ani, chan->cid.cid_rdnis, chan->readformat);
134 /* Lets parse the arguments. */
135 if (!ast_strlen_zero(parse)) {
136 /* Some arguments have been passed. Lets parse them and overwrite the defaults. */
137 AST_STANDARD_APP_ARGS(args, parse);
138 if (!ast_strlen_zero(args.argInitialSilence))
139 initialSilence = atoi(args.argInitialSilence);
140 if (!ast_strlen_zero(args.argGreeting))
141 greeting = atoi(args.argGreeting);
142 if (!ast_strlen_zero(args.argAfterGreetingSilence))
143 afterGreetingSilence = atoi(args.argAfterGreetingSilence);
144 if (!ast_strlen_zero(args.argTotalAnalysisTime))
145 totalAnalysisTime = atoi(args.argTotalAnalysisTime);
146 if (!ast_strlen_zero(args.argMinimumWordLength))
147 minimumWordLength = atoi(args.argMinimumWordLength);
148 if (!ast_strlen_zero(args.argBetweenWordsSilence))
149 betweenWordsSilence = atoi(args.argBetweenWordsSilence);
150 if (!ast_strlen_zero(args.argMaximumNumberOfWords))
151 maximumNumberOfWords = atoi(args.argMaximumNumberOfWords);
152 if (!ast_strlen_zero(args.argSilenceThreshold))
153 silenceThreshold = atoi(args.argSilenceThreshold);
154 } else if (option_debug)
155 ast_log(LOG_DEBUG, "AMD using the default parameters.\n");
157 /* Now we're ready to roll! */
158 if (option_verbose > 2)
159 ast_verbose(VERBOSE_PREFIX_3 "AMD: initialSilence [%d] greeting [%d] afterGreetingSilence [%d] "
160 "totalAnalysisTime [%d] minimumWordLength [%d] betweenWordsSilence [%d] maximumNumberOfWords [%d] silenceThreshold [%d] \n",
161 initialSilence, greeting, afterGreetingSilence, totalAnalysisTime,
162 minimumWordLength, betweenWordsSilence, maximumNumberOfWords, silenceThreshold );
164 /* Set read format to signed linear so we get signed linear frames in */
165 readFormat = chan->readformat;
166 if (ast_set_read_format(chan, AST_FORMAT_SLINEAR) < 0 ) {
167 ast_log(LOG_WARNING, "AMD: Channel [%s]. Unable to set to linear mode, giving up\n", chan->name );
168 pbx_builtin_setvar_helper(chan , "AMDSTATUS", "");
169 pbx_builtin_setvar_helper(chan , "AMDCAUSE", "");
170 return;
173 /* Create a new DSP that will detect the silence */
174 if (!(silenceDetector = ast_dsp_new())) {
175 ast_log(LOG_WARNING, "AMD: Channel [%s]. Unable to create silence detector :(\n", chan->name );
176 pbx_builtin_setvar_helper(chan , "AMDSTATUS", "");
177 pbx_builtin_setvar_helper(chan , "AMDCAUSE", "");
178 return;
181 /* Set silence threshold to specified value */
182 ast_dsp_set_threshold(silenceDetector, silenceThreshold);
184 /* Now we go into a loop waiting for frames from the channel */
185 while ((res = ast_waitfor(chan, totalAnalysisTime)) > -1) {
186 /* If we fail to read in a frame, that means they hung up */
187 if (!(f = ast_read(chan))) {
188 if (option_verbose > 2)
189 ast_verbose(VERBOSE_PREFIX_3 "AMD: HANGUP\n");
190 if (option_debug)
191 ast_log(LOG_DEBUG, "Got hangup\n");
192 strcpy(amdStatus, "HANGUP");
193 break;
196 if (f->frametype == AST_FRAME_VOICE) {
197 /* If the total time exceeds the analysis time then give up as we are not too sure */
198 framelength = (ast_codec_get_samples(f) / DEFAULT_SAMPLES_PER_MS);
199 iTotalTime += framelength;
200 if (iTotalTime >= totalAnalysisTime) {
201 if (option_verbose > 2)
202 ast_verbose(VERBOSE_PREFIX_3 "AMD: Channel [%s]. Too long...\n", chan->name );
203 ast_frfree(f);
204 strcpy(amdStatus , "NOTSURE");
205 sprintf(amdCause , "TOOLONG-%d", iTotalTime);
206 break;
209 /* Feed the frame of audio into the silence detector and see if we get a result */
210 dspsilence = 0;
211 ast_dsp_silence(silenceDetector, f, &dspsilence);
212 if (dspsilence) {
213 silenceDuration = dspsilence;
215 if (silenceDuration >= betweenWordsSilence) {
216 if (currentState != STATE_IN_SILENCE ) {
217 previousState = currentState;
218 if (option_verbose > 2)
219 ast_verbose(VERBOSE_PREFIX_3 "AMD: Changed state to STATE_IN_SILENCE\n");
221 currentState = STATE_IN_SILENCE;
222 consecutiveVoiceDuration = 0;
225 if (inInitialSilence == 1 && silenceDuration >= initialSilence) {
226 if (option_verbose > 2)
227 ast_verbose(VERBOSE_PREFIX_3 "AMD: ANSWERING MACHINE: silenceDuration:%d initialSilence:%d\n",
228 silenceDuration, initialSilence);
229 ast_frfree(f);
230 strcpy(amdStatus , "MACHINE");
231 sprintf(amdCause , "INITIALSILENCE-%d-%d", silenceDuration, initialSilence);
232 break;
235 if (silenceDuration >= afterGreetingSilence && inGreeting == 1) {
236 if (option_verbose > 2)
237 ast_verbose(VERBOSE_PREFIX_3 "AMD: HUMAN: silenceDuration:%d afterGreetingSilence:%d\n",
238 silenceDuration, afterGreetingSilence);
239 ast_frfree(f);
240 strcpy(amdStatus , "HUMAN");
241 sprintf(amdCause , "HUMAN-%d-%d", silenceDuration, afterGreetingSilence);
242 break;
245 } else {
246 consecutiveVoiceDuration += framelength;
247 voiceDuration += framelength;
249 /* If I have enough consecutive voice to say that I am in a Word, I can only increment the
250 number of words if my previous state was Silence, which means that I moved into a word. */
251 if (consecutiveVoiceDuration >= minimumWordLength && currentState == STATE_IN_SILENCE) {
252 iWordsCount++;
253 if (option_verbose > 2)
254 ast_verbose(VERBOSE_PREFIX_3 "AMD: Word detected. iWordsCount:%d\n", iWordsCount);
255 previousState = currentState;
256 currentState = STATE_IN_WORD;
259 if (iWordsCount >= maximumNumberOfWords) {
260 if (option_verbose > 2)
261 ast_verbose(VERBOSE_PREFIX_3 "AMD: ANSWERING MACHINE: iWordsCount:%d\n", iWordsCount);
262 ast_frfree(f);
263 strcpy(amdStatus , "MACHINE");
264 sprintf(amdCause , "MAXWORDS-%d-%d", iWordsCount, maximumNumberOfWords);
265 break;
268 if (inGreeting == 1 && voiceDuration >= greeting) {
269 if (option_verbose > 2)
270 ast_verbose(VERBOSE_PREFIX_3 "AMD: ANSWERING MACHINE: voiceDuration:%d greeting:%d\n", voiceDuration, greeting);
271 ast_frfree(f);
272 strcpy(amdStatus , "MACHINE");
273 sprintf(amdCause , "LONGGREETING-%d-%d", voiceDuration, greeting);
274 break;
277 if (voiceDuration >= minimumWordLength ) {
278 silenceDuration = 0;
279 inInitialSilence = 0;
280 inGreeting = 1;
285 ast_frfree(f);
288 if (!res) {
289 /* It took too long to get a frame back. Giving up. */
290 if (option_verbose > 2)
291 ast_verbose(VERBOSE_PREFIX_3 "AMD: Channel [%s]. Too long...\n", chan->name);
292 strcpy(amdStatus , "NOTSURE");
293 sprintf(amdCause , "TOOLONG-%d", iTotalTime);
296 /* Set the status and cause on the channel */
297 pbx_builtin_setvar_helper(chan , "AMDSTATUS" , amdStatus);
298 pbx_builtin_setvar_helper(chan , "AMDCAUSE" , amdCause);
300 /* Restore channel read format */
301 if (readFormat && ast_set_read_format(chan, readFormat))
302 ast_log(LOG_WARNING, "AMD: Unable to restore read format on '%s'\n", chan->name);
304 /* Free the DSP used to detect silence */
305 ast_dsp_free(silenceDetector);
307 return;
311 static int amd_exec(struct ast_channel *chan, void *data)
313 struct ast_module_user *u = NULL;
315 u = ast_module_user_add(chan);
316 isAnsweringMachine(chan, data);
317 ast_module_user_remove(u);
319 return 0;
322 static void load_config(void)
324 struct ast_config *cfg = NULL;
325 char *cat = NULL;
326 struct ast_variable *var = NULL;
328 if (!(cfg = ast_config_load("amd.conf"))) {
329 ast_log(LOG_ERROR, "Configuration file amd.conf missing.\n");
330 return;
333 cat = ast_category_browse(cfg, NULL);
335 while (cat) {
336 if (!strcasecmp(cat, "general") ) {
337 var = ast_variable_browse(cfg, cat);
338 while (var) {
339 if (!strcasecmp(var->name, "initial_silence")) {
340 dfltInitialSilence = atoi(var->value);
341 } else if (!strcasecmp(var->name, "greeting")) {
342 dfltGreeting = atoi(var->value);
343 } else if (!strcasecmp(var->name, "after_greeting_silence")) {
344 dfltAfterGreetingSilence = atoi(var->value);
345 } else if (!strcasecmp(var->name, "silence_threshold")) {
346 dfltSilenceThreshold = atoi(var->value);
347 } else if (!strcasecmp(var->name, "total_analysis_time")) {
348 dfltTotalAnalysisTime = atoi(var->value);
349 } else if (!strcasecmp(var->name, "min_word_length")) {
350 dfltMinimumWordLength = atoi(var->value);
351 } else if (!strcasecmp(var->name, "between_words_silence")) {
352 dfltBetweenWordsSilence = atoi(var->value);
353 } else if (!strcasecmp(var->name, "maximum_number_of_words")) {
354 dfltMaximumNumberOfWords = atoi(var->value);
355 } else {
356 ast_log(LOG_WARNING, "%s: Cat:%s. Unknown keyword %s at line %d of amd.conf\n",
357 app, cat, var->name, var->lineno);
359 var = var->next;
362 cat = ast_category_browse(cfg, cat);
365 ast_config_destroy(cfg);
367 if (option_verbose > 2)
368 ast_verbose(VERBOSE_PREFIX_3 "AMD defaults: initialSilence [%d] greeting [%d] afterGreetingSilence [%d] "
369 "totalAnalysisTime [%d] minimumWordLength [%d] betweenWordsSilence [%d] maximumNumberOfWords [%d] silenceThreshold [%d] \n",
370 dfltInitialSilence, dfltGreeting, dfltAfterGreetingSilence, dfltTotalAnalysisTime,
371 dfltMinimumWordLength, dfltBetweenWordsSilence, dfltMaximumNumberOfWords, dfltSilenceThreshold );
373 return;
376 static int unload_module(void)
378 ast_module_user_hangup_all();
379 return ast_unregister_application(app);
382 static int load_module(void)
384 load_config();
385 return ast_register_application(app, amd_exec, synopsis, descrip);
388 static int reload(void)
390 load_config();
391 return 0;
394 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Answering Machine Detection Application",
395 .load = load_module,
396 .unload = unload_module,
397 .reload = reload,