More code optimizations. Thanks kpfleming!
[asterisk/asterisk.git] / apps / app_amd.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2003 - 2006, Aheeva Technology.
5  *
6  * Claude Klimos (claude.klimos@aheeva.com)
7  *
8  * Disclaimed to Digium
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23
24 #include "asterisk.h"
25  
26 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
27
28 #include "asterisk/module.h"
29 #include "asterisk/lock.h"
30 #include "asterisk/options.h"
31 #include "asterisk/channel.h"
32 #include "asterisk/dsp.h"
33 #include "asterisk/pbx.h"
34 #include "asterisk/config.h"
35 #include "asterisk/app.h"
36
37
38 static char *tdesc = "Answering Machine Detection Application";
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";
75
76
77 LOCAL_USER_DECL;
78
79 #define STATE_IN_WORD       1
80 #define STATE_IN_SILENCE    2
81
82 /* Some default values for the algorithm parameters. These defaults will be overwritten from amd.conf */
83 static int dfltInitialSilence       = 2500;
84 static int dfltGreeting             = 1500;
85 static int dfltAfterGreetingSilence = 800;
86 static int dfltTotalAnalysisTime    = 5000;
87 static int dfltMinimumWordLength    = 100;
88 static int dfltBetweenWordsSilence  = 50;
89 static int dfltMaximumNumberOfWords = 3;
90 static int dfltSilenceThreshold     = 256;
91
92 static void isAnsweringMachine(struct ast_channel *chan, void *data)
93 {
94         int res = 0, ret = 0;
95
96         struct ast_frame *f = NULL;
97
98         struct ast_dsp *silenceDetector;         /* silence detector dsp */
99         int dspsilence = 0;
100         int readFormat;
101         int framelength;
102
103         int inInitialSilence         = 1;
104         int inGreeting               = 0;
105         int voiceDuration            = 0;
106         int silenceDuration          = 0;
107         int iTotalTime               = 0;
108         int iWordsCount              = 0;
109         int currentState             = STATE_IN_SILENCE;
110         int previousState            = STATE_IN_SILENCE;
111         int consecutiveVoiceDuration = 0;
112         char amdCause[256]           = "";
113         char amdStatus[256]          = "";
114
115         /* Lets set the initial values of the variables that will control the algorithm.
116            The initial values are the default ones. If they are passed as arguments
117            when invoking the application, then the default values will be overwritten
118            by the ones passed as parameters. */
119         int initialSilence       = dfltInitialSilence;
120         int greeting             = dfltGreeting;
121         int afterGreetingSilence = dfltAfterGreetingSilence;
122         int totalAnalysisTime    = dfltTotalAnalysisTime;
123         int minimumWordLength    = dfltMinimumWordLength;
124         int betweenWordsSilence  = dfltBetweenWordsSilence;
125         int maximumNumberOfWords = dfltMaximumNumberOfWords;
126         int silenceThreshold     = dfltSilenceThreshold;
127
128         char *parse;
129         AST_DECLARE_APP_ARGS(args,
130                              AST_APP_ARG(argInitialSilence);
131                              AST_APP_ARG(argGreeting);
132                              AST_APP_ARG(argAfterGreetingSilence);
133                              AST_APP_ARG(argTotalAnalysisTime);
134                              AST_APP_ARG(argMinimumWordLength);
135                              AST_APP_ARG(argBetweenWordsSilence);
136                              AST_APP_ARG(argMaximumNumberOfWords);
137                              AST_APP_ARG(argSilenceThreshold);
138         );
139         if (option_verbose > 2)
140                 ast_verbose(VERBOSE_PREFIX_3 "AMD: %s %s %s (Fmt: %d)\n", chan->name ,chan->cid.cid_ani, chan->cid.cid_rdnis, chan->readformat);
141
142         /* Lets parse the arguments. */
143         if (ast_strlen_zero(data)) {
144                 ast_log(LOG_NOTICE, "AMD using the default parameters.\n");
145         } else {
146                 /* Some arguments have been passed. Lets parse them and overwrite the defaults. */
147                 if (!(parse = ast_strdupa(data))) {
148                         ast_log(LOG_WARNING, "Memory allocation failure\n");
149                         pbx_builtin_setvar_helper(chan , "AMDSTATUS" , "" );
150                         pbx_builtin_setvar_helper(chan , "AMDCAUSE" , "" );
151                         return;
152                 }
153
154                 AST_STANDARD_APP_ARGS(args, parse);
155
156                 if (!ast_strlen_zero(args.argInitialSilence)) {
157                         initialSilence = atoi(args.argInitialSilence);
158                 }
159                 if (!ast_strlen_zero(args.argGreeting)) {
160                         greeting = atoi(args.argGreeting);
161                 }
162                 if (!ast_strlen_zero(args.argAfterGreetingSilence)) {
163                         afterGreetingSilence = atoi(args.argAfterGreetingSilence);
164                 }
165                 if (!ast_strlen_zero(args.argTotalAnalysisTime)) {
166                         totalAnalysisTime = atoi(args.argTotalAnalysisTime);
167                 }
168                 if (!ast_strlen_zero(args.argMinimumWordLength)) {
169                         minimumWordLength = atoi(args.argMinimumWordLength);
170                 }
171                 if (!ast_strlen_zero(args.argBetweenWordsSilence)) {
172                         betweenWordsSilence = atoi(args.argBetweenWordsSilence);
173                 }
174                 if (!ast_strlen_zero(args.argMaximumNumberOfWords)) {
175                         maximumNumberOfWords = atoi(args.argMaximumNumberOfWords);
176                 }
177                 if (!ast_strlen_zero(args.argSilenceThreshold)) {
178                         silenceThreshold = atoi(args.argSilenceThreshold);
179                 }
180         }
181
182         /* Now we're ready to roll! */
183         
184         if (option_verbose > 2)
185                 ast_verbose(VERBOSE_PREFIX_3 "AMD: initialSilence [%d] greeting [%d] afterGreetingSilence [%d] "
186                 "totalAnalysisTime [%d] minimumWordLength [%d] betweenWordsSilence [%d] maximumNumberOfWords [%d] silenceThreshold [%d] \n",
187                                 initialSilence, greeting, afterGreetingSilence, totalAnalysisTime,
188                                 minimumWordLength, betweenWordsSilence, maximumNumberOfWords, silenceThreshold );
189
190         readFormat = chan->readformat;
191         res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
192         if (res < 0 ) {
193                 ast_log(LOG_WARNING, "AMD: Channel [%s]. Unable to set to linear mode, giving up\n", chan->name );
194                 pbx_builtin_setvar_helper(chan , "AMDSTATUS" , "" );
195                 pbx_builtin_setvar_helper(chan , "AMDCAUSE" , "" );
196                 return;
197         }
198
199         silenceDetector = ast_dsp_new();
200         if (!silenceDetector ) {
201                 ast_log(LOG_WARNING, "AMD: Channel [%s]. Unable to create silence detector :(\n", chan->name );
202                 pbx_builtin_setvar_helper(chan , "AMDSTATUS" , "" );
203                 pbx_builtin_setvar_helper(chan , "AMDCAUSE" , "" );
204                 return;
205         }
206         ast_dsp_set_threshold(silenceDetector, silenceThreshold );
207
208         while ((ret = ast_waitfor(chan, totalAnalysisTime)))
209         {
210                 if (ret < 0 || !(f = ast_read(chan))) {
211                         /* No Frame OR Error on ast_waitfor : Called Party Must Have Dropped */
212                         if (option_verbose > 2)
213                                 ast_verbose(VERBOSE_PREFIX_3 "AMD: HANGUP\n");
214                         if (option_debug)
215                                 ast_log(LOG_DEBUG, "Got hangup\n");
216                         strcpy(amdStatus , "HANGUP" );
217                         strcpy(amdCause , "" );
218                         break;
219                 }
220                 if (f->frametype == AST_FRAME_VOICE ) {
221                         framelength = (ast_codec_get_samples(f) / DEFAULT_SAMPLES_PER_MS);
222                         iTotalTime += framelength;
223                         if (iTotalTime >= totalAnalysisTime ) {
224                                 if (option_verbose > 2) 
225                                         ast_verbose(VERBOSE_PREFIX_3 "AMD: Channel [%s]. Too long...\n", chan->name );
226                                 ast_frfree(f);
227                                 strcpy(amdStatus , "NOTSURE" );
228                                 sprintf(amdCause , "TOOLONG-%d", iTotalTime );
229                                 break;
230                         }
231                         dspsilence = 0;
232                         ast_dsp_silence(silenceDetector, f, &dspsilence);
233                         if (dspsilence ) {
234                                 silenceDuration = dspsilence;
235                                 if (silenceDuration >= betweenWordsSilence ) {
236                                         if (currentState != STATE_IN_SILENCE ) {
237                                                 previousState = currentState;
238                                                 if (option_verbose > 2)
239                                                         ast_verbose(VERBOSE_PREFIX_3 "AMD: Changed state to STATE_IN_SILENCE\n");
240                                         }
241                                         currentState  = STATE_IN_SILENCE;
242                                         consecutiveVoiceDuration = 0;
243                                 }
244                                 if (inInitialSilence == 1  && silenceDuration >= initialSilence ) {
245                                         if (option_verbose > 2)
246                                                 ast_verbose(VERBOSE_PREFIX_3 "AMD: ANSWERING MACHINE: silenceDuration:%d initialSilence:%d\n",
247                                                         silenceDuration, initialSilence );
248                                         ast_frfree(f);
249                                         strcpy(amdStatus , "MACHINE" );
250                                         sprintf(amdCause , "INITIALSILENCE-%d-%d", silenceDuration, initialSilence );
251                                         break;
252                                 }
253
254                                 if (silenceDuration >= afterGreetingSilence  &&  inGreeting == 1 ) {
255                                         if (option_verbose > 2)
256                                                 ast_verbose(VERBOSE_PREFIX_3 "AMD: HUMAN: silenceDuration:%d afterGreetingSilence:%d\n",
257                                                         silenceDuration, afterGreetingSilence );
258                                         ast_frfree(f);
259                                         strcpy(amdStatus , "HUMAN" );
260                                         sprintf(amdCause , "HUMAN-%d-%d", silenceDuration, afterGreetingSilence );
261                                         break;
262                                 }
263                         } else {
264                                 consecutiveVoiceDuration += framelength;
265                                 voiceDuration += framelength;
266
267                                 /* If I have enough consecutive voice to say that I am in a Word, I can only increment the
268                                         number of words if my previous state was Silence, which means that I moved into a word. */
269                                 if (consecutiveVoiceDuration >= minimumWordLength ) {
270                                         if (currentState == STATE_IN_SILENCE ) {
271                                                 iWordsCount++;
272                                                 if (option_verbose > 2)
273                                                         ast_verbose(VERBOSE_PREFIX_3 "AMD: Word detected. iWordsCount:%d\n", iWordsCount );
274                                                 previousState = currentState;
275                                                 currentState = STATE_IN_WORD;
276                                         }
277                                 }
278
279                                 if (iWordsCount >= maximumNumberOfWords ) {
280                                         if (option_verbose > 2)
281                                                 ast_verbose(VERBOSE_PREFIX_3 "AMD: ANSWERING MACHINE: iWordsCount:%d\n", iWordsCount );
282                                         ast_frfree(f);
283                                         strcpy(amdStatus , "MACHINE" );
284                                         sprintf(amdCause , "MAXWORDS-%d-%d", iWordsCount, maximumNumberOfWords );
285                                         break;
286                                 }
287
288                                 if (inGreeting == 1  &&  voiceDuration >= greeting ) {
289                                         if (option_verbose > 2)
290                                         ast_verbose(VERBOSE_PREFIX_3 "AMD: ANSWERING MACHINE: voiceDuration:%d greeting:%d\n", voiceDuration, greeting);
291                                          ast_frfree(f);
292                                         strcpy(amdStatus , "MACHINE" );
293                                         sprintf(amdCause , "LONGGREETING-%d-%d", voiceDuration, greeting );
294                                         break;
295                                 }
296                                 if (voiceDuration >= minimumWordLength ) {
297                                         silenceDuration = 0;
298                                         inInitialSilence = 0;
299                                         inGreeting = 1;
300                                 }
301                         }
302                 }
303                 ast_frfree(f);
304         }
305         if (!ret) {
306                 /* It took too long to get a frame back. Giving up. */
307                 if (option_verbose > 2)
308                         ast_verbose(VERBOSE_PREFIX_3 "AMD: Channel [%s]. Too long...\n", chan->name );
309                 strcpy(amdStatus , "NOTSURE" );
310                 sprintf(amdCause , "TOOLONG-%d", iTotalTime );
311         }
312
313         pbx_builtin_setvar_helper(chan , "AMDSTATUS" , amdStatus );
314         pbx_builtin_setvar_helper(chan , "AMDCAUSE" , amdCause );
315
316         /* If We Started With A Valid Read Format, Return To It... */
317         if (readFormat && chan->_state == AST_STATE_UP) {
318                 res = ast_set_read_format(chan, readFormat );
319                 if (res)
320                         ast_log(LOG_WARNING, "AMD: Unable to restore read format on '%s'\n", chan->name);
321         }
322
323         /* Free The Silence Detector DSP */
324         ast_dsp_free(silenceDetector );
325
326         return;
327 }
328
329
330 static int amd_exec(struct ast_channel *chan, void *data)
331 {
332         struct localuser *u;
333
334         LOCAL_USER_ADD(u);
335         isAnsweringMachine(chan, data);
336         LOCAL_USER_REMOVE(u);
337
338         return 0;
339 }
340
341 static void load_config(void)
342 {
343         struct ast_config *cfg;
344         char *cat;
345         struct ast_variable *var;
346
347         cfg = ast_config_load("amd.conf");
348
349         if (!cfg) {
350                 ast_log(LOG_ERROR, "Configuration file amd.conf missing.\n");
351                 return;
352         }
353
354         cat = ast_category_browse(cfg, NULL);
355
356         while (cat) {
357                 if (!strcasecmp(cat, "amd") ) {
358                         var = ast_variable_browse(cfg, cat);
359                         while (var) {
360                                 if (!strcasecmp(var->name, "initial_silence")) {
361                                         dfltInitialSilence = atoi(var->value);
362                                 } else if (!strcasecmp(var->name, "greeting")) {
363                                         dfltGreeting = atoi(var->value);
364                                 } else if (!strcasecmp(var->name, "after_greeting_silence")) {
365                                         dfltAfterGreetingSilence = atoi(var->value);
366                                 } else if (!strcasecmp(var->name, "silence_threshold")) {
367                                         dfltSilenceThreshold = atoi(var->value);
368                                 } else if (!strcasecmp(var->name, "total_analysis_time")) {
369                                         dfltTotalAnalysisTime = atoi(var->value);
370                                 } else if (!strcasecmp(var->name, "min_word_length")) {
371                                         dfltMinimumWordLength = atoi(var->value);
372                                 } else if (!strcasecmp(var->name, "between_words_silence")) {
373                                         dfltBetweenWordsSilence = atoi(var->value);
374                                 } else if (!strcasecmp(var->name, "maximum_number_of_words")) {
375                                         dfltMaximumNumberOfWords = atoi(var->value);
376                                 } else {
377                                         ast_log(LOG_WARNING, "%s: Cat:%s. Unknown keyword %s at line %d of amd.conf\n",
378                                                 app, cat, var->name, var->lineno);
379                                 }
380                                 var = var->next;
381                         }
382                 }
383                 cat = ast_category_browse(cfg, cat);
384         }
385         ast_config_destroy(cfg);
386
387         if (option_verbose > 2)
388                 ast_verbose(VERBOSE_PREFIX_3 "AMD defaults: initialSilence [%d] greeting [%d] afterGreetingSilence [%d] "
389                 "totalAnalysisTime [%d] minimumWordLength [%d] betweenWordsSilence [%d] maximumNumberOfWords [%d] silenceThreshold [%d] \n",
390                                 dfltInitialSilence, dfltGreeting, dfltAfterGreetingSilence, dfltTotalAnalysisTime,
391                                 dfltMinimumWordLength, dfltBetweenWordsSilence, dfltMaximumNumberOfWords, dfltSilenceThreshold );
392
393         return;
394 }
395
396 int unload_module(void)
397 {
398         STANDARD_HANGUP_LOCALUSERS;
399         return ast_unregister_application(app);
400 }
401
402 int load_module(void)
403 {
404         load_config();
405         return ast_register_application(app, amd_exec, synopsis, descrip);
406 }
407
408 int reload(void)
409 {
410         load_config();
411         return 0;
412 }
413
414 char *description(void)
415 {
416         return tdesc;
417 }
418
419 int usecount(void)
420 {
421         int res;
422         STANDARD_USECOUNT(res);
423         return res;
424 }
425
426 char *key()
427 {
428         return ASTERISK_GPL_KEY;
429 }
430