app_amd.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. * 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.
  13. *
  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.
  17. *
  18. * A license has been granted to Digium (via disclaimer) for the use of
  19. * this code.
  20. */
  21. /*! \file
  22. *
  23. * \brief Answering machine detection
  24. *
  25. * \author Claude Klimos (claude.klimos@aheeva.com)
  26. */
  27. #include "asterisk.h"
  28. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #include "asterisk/module.h"
  30. #include "asterisk/lock.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. static char *app = "AMD";
  37. static char *synopsis = "Attempts to detect answering machines";
  38. static char *descrip =
  39. " AMD([initialSilence],[greeting],[afterGreetingSilence],[totalAnalysisTime]\n"
  40. " ,[minimumWordLength],[betweenWordsSilence],[maximumNumberOfWords]\n"
  41. " ,[silenceThreshold],[|maximumWordLength])\n"
  42. " This application attempts to detect answering machines at the beginning\n"
  43. " of outbound calls. Simply call this application after the call\n"
  44. " has been answered (outbound only, of course).\n"
  45. " When loaded, AMD reads amd.conf and uses the parameters specified as\n"
  46. " default values. Those default values get overwritten when calling AMD\n"
  47. " with parameters.\n"
  48. "- 'initialSilence' is the maximum silence duration before the greeting. If\n"
  49. " exceeded then MACHINE.\n"
  50. "- 'greeting' is the maximum length of a greeting. If exceeded then MACHINE.\n"
  51. "- 'afterGreetingSilence' is the silence after detecting a greeting.\n"
  52. " If exceeded then HUMAN.\n"
  53. "- 'totalAnalysisTime' is the maximum time allowed for the algorithm to decide\n"
  54. " on a HUMAN or MACHINE.\n"
  55. "- 'minimumWordLength'is the minimum duration of Voice to considered as a word.\n"
  56. "- 'betweenWordsSilence' is the minimum duration of silence after a word to \n"
  57. " consider the audio that follows as a new word.\n"
  58. "- 'maximumNumberOfWords'is the maximum number of words in the greeting. \n"
  59. " If exceeded then MACHINE.\n"
  60. "- 'silenceThreshold' is the silence threshold.\n"
  61. "- 'maximumWordLength' is the maximum duration of a word to accept. If exceeded then MACHINE\n"
  62. "This application sets the following channel variables upon completion:\n"
  63. " AMDSTATUS - This is the status of the answering machine detection.\n"
  64. " Possible values are:\n"
  65. " MACHINE | HUMAN | NOTSURE | HANGUP\n"
  66. " AMDCAUSE - Indicates the cause that led to the conclusion.\n"
  67. " Possible values are:\n"
  68. " TOOLONG-<%d total_time>\n"
  69. " INITIALSILENCE-<%d silenceDuration>-<%d initialSilence>\n"
  70. " HUMAN-<%d silenceDuration>-<%d afterGreetingSilence>\n"
  71. " MAXWORDS-<%d wordsCount>-<%d maximumNumberOfWords>\n"
  72. " LONGGREETING-<%d voiceDuration>-<%d greeting>\n"
  73. " MAXWORDLENGTH-<%d consecutiveVoiceDuration>\n";
  74. #define STATE_IN_WORD 1
  75. #define STATE_IN_SILENCE 2
  76. /* Some default values for the algorithm parameters. These defaults will be overwritten from amd.conf */
  77. static int dfltInitialSilence = 2500;
  78. static int dfltGreeting = 1500;
  79. static int dfltAfterGreetingSilence = 800;
  80. static int dfltTotalAnalysisTime = 5000;
  81. static int dfltMinimumWordLength = 100;
  82. static int dfltBetweenWordsSilence = 50;
  83. static int dfltMaximumNumberOfWords = 3;
  84. static int dfltSilenceThreshold = 256;
  85. static int dfltMaximumWordLength = 5000; /* Setting this to a large default so it is not used unless specify it in the configs or command line */
  86. /* Set to the lowest ms value provided in amd.conf or application parameters */
  87. static int dfltMaxWaitTimeForFrame = 50;
  88. static void isAnsweringMachine(struct ast_channel *chan, void *data)
  89. {
  90. int res = 0;
  91. struct ast_frame *f = NULL;
  92. struct ast_dsp *silenceDetector = NULL;
  93. int dspsilence = 0, readFormat, framelength = 0;
  94. int inInitialSilence = 1;
  95. int inGreeting = 0;
  96. int voiceDuration = 0;
  97. int silenceDuration = 0;
  98. int iTotalTime = 0;
  99. int iWordsCount = 0;
  100. int currentState = STATE_IN_WORD;
  101. int previousState = STATE_IN_SILENCE;
  102. int consecutiveVoiceDuration = 0;
  103. char amdCause[256] = "", amdStatus[256] = "";
  104. char *parse = ast_strdupa(data);
  105. /* Lets set the initial values of the variables that will control the algorithm.
  106. The initial values are the default ones. If they are passed as arguments
  107. when invoking the application, then the default values will be overwritten
  108. by the ones passed as parameters. */
  109. int initialSilence = dfltInitialSilence;
  110. int greeting = dfltGreeting;
  111. int afterGreetingSilence = dfltAfterGreetingSilence;
  112. int totalAnalysisTime = dfltTotalAnalysisTime;
  113. int minimumWordLength = dfltMinimumWordLength;
  114. int betweenWordsSilence = dfltBetweenWordsSilence;
  115. int maximumNumberOfWords = dfltMaximumNumberOfWords;
  116. int silenceThreshold = dfltSilenceThreshold;
  117. int maximumWordLength = dfltMaximumWordLength;
  118. int maxWaitTimeForFrame = dfltMaxWaitTimeForFrame;
  119. AST_DECLARE_APP_ARGS(args,
  120. AST_APP_ARG(argInitialSilence);
  121. AST_APP_ARG(argGreeting);
  122. AST_APP_ARG(argAfterGreetingSilence);
  123. AST_APP_ARG(argTotalAnalysisTime);
  124. AST_APP_ARG(argMinimumWordLength);
  125. AST_APP_ARG(argBetweenWordsSilence);
  126. AST_APP_ARG(argMaximumNumberOfWords);
  127. AST_APP_ARG(argSilenceThreshold);
  128. AST_APP_ARG(argMaximumWordLength);
  129. );
  130. ast_verb(3, "AMD: %s %s %s (Fmt: %d)\n", chan->name ,chan->cid.cid_ani, chan->cid.cid_rdnis, chan->readformat);
  131. /* Lets parse the arguments. */
  132. if (!ast_strlen_zero(parse)) {
  133. /* Some arguments have been passed. Lets parse them and overwrite the defaults. */
  134. AST_STANDARD_APP_ARGS(args, parse);
  135. if (!ast_strlen_zero(args.argInitialSilence))
  136. initialSilence = atoi(args.argInitialSilence);
  137. if (!ast_strlen_zero(args.argGreeting))
  138. greeting = atoi(args.argGreeting);
  139. if (!ast_strlen_zero(args.argAfterGreetingSilence))
  140. afterGreetingSilence = atoi(args.argAfterGreetingSilence);
  141. if (!ast_strlen_zero(args.argTotalAnalysisTime))
  142. totalAnalysisTime = atoi(args.argTotalAnalysisTime);
  143. if (!ast_strlen_zero(args.argMinimumWordLength))
  144. minimumWordLength = atoi(args.argMinimumWordLength);
  145. if (!ast_strlen_zero(args.argBetweenWordsSilence))
  146. betweenWordsSilence = atoi(args.argBetweenWordsSilence);
  147. if (!ast_strlen_zero(args.argMaximumNumberOfWords))
  148. maximumNumberOfWords = atoi(args.argMaximumNumberOfWords);
  149. if (!ast_strlen_zero(args.argSilenceThreshold))
  150. silenceThreshold = atoi(args.argSilenceThreshold);
  151. if (!ast_strlen_zero(args.argMaximumWordLength))
  152. maximumWordLength = atoi(args.argMaximumWordLength);
  153. } else {
  154. ast_debug(1, "AMD using the default parameters.\n");
  155. }
  156. /* Find lowest ms value, that will be max wait time for a frame */
  157. if (maxWaitTimeForFrame > initialSilence)
  158. maxWaitTimeForFrame = initialSilence;
  159. if (maxWaitTimeForFrame > greeting)
  160. maxWaitTimeForFrame = greeting;
  161. if (maxWaitTimeForFrame > afterGreetingSilence)
  162. maxWaitTimeForFrame = afterGreetingSilence;
  163. if (maxWaitTimeForFrame > totalAnalysisTime)
  164. maxWaitTimeForFrame = totalAnalysisTime;
  165. if (maxWaitTimeForFrame > minimumWordLength)
  166. maxWaitTimeForFrame = minimumWordLength;
  167. if (maxWaitTimeForFrame > betweenWordsSilence)
  168. maxWaitTimeForFrame = betweenWordsSilence;
  169. /* Now we're ready to roll! */
  170. ast_verb(3, "AMD: initialSilence [%d] greeting [%d] afterGreetingSilence [%d] "
  171. "totalAnalysisTime [%d] minimumWordLength [%d] betweenWordsSilence [%d] maximumNumberOfWords [%d] silenceThreshold [%d] maximumWordLength [%d] \n",
  172. initialSilence, greeting, afterGreetingSilence, totalAnalysisTime,
  173. minimumWordLength, betweenWordsSilence, maximumNumberOfWords, silenceThreshold, maximumWordLength);
  174. /* Set read format to signed linear so we get signed linear frames in */
  175. readFormat = chan->readformat;
  176. if (ast_set_read_format(chan, AST_FORMAT_SLINEAR) < 0 ) {
  177. ast_log(LOG_WARNING, "AMD: Channel [%s]. Unable to set to linear mode, giving up\n", chan->name );
  178. pbx_builtin_setvar_helper(chan , "AMDSTATUS", "");
  179. pbx_builtin_setvar_helper(chan , "AMDCAUSE", "");
  180. return;
  181. }
  182. /* Create a new DSP that will detect the silence */
  183. if (!(silenceDetector = ast_dsp_new())) {
  184. ast_log(LOG_WARNING, "AMD: Channel [%s]. Unable to create silence detector :(\n", chan->name );
  185. pbx_builtin_setvar_helper(chan , "AMDSTATUS", "");
  186. pbx_builtin_setvar_helper(chan , "AMDCAUSE", "");
  187. return;
  188. }
  189. /* Set silence threshold to specified value */
  190. ast_dsp_set_threshold(silenceDetector, silenceThreshold);
  191. /* Now we go into a loop waiting for frames from the channel */
  192. while ((res = ast_waitfor(chan, 2 * maxWaitTimeForFrame)) > -1) {
  193. /* If we fail to read in a frame, that means they hung up */
  194. if (!(f = ast_read(chan))) {
  195. ast_verb(3, "AMD: Channel [%s]. HANGUP\n", chan->name);
  196. ast_debug(1, "Got hangup\n");
  197. strcpy(amdStatus, "HANGUP");
  198. res = 1;
  199. break;
  200. }
  201. if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_NULL || f->frametype == AST_FRAME_CNG) {
  202. /* If the total time exceeds the analysis time then give up as we are not too sure */
  203. if (f->frametype == AST_FRAME_VOICE)
  204. framelength = (ast_codec_get_samples(f) / DEFAULT_SAMPLES_PER_MS);
  205. else
  206. framelength += 2 * maxWaitTimeForFrame;
  207. iTotalTime += framelength;
  208. if (iTotalTime >= totalAnalysisTime) {
  209. ast_verb(3, "AMD: Channel [%s]. Too long...\n", chan->name );
  210. ast_frfree(f);
  211. strcpy(amdStatus , "NOTSURE");
  212. sprintf(amdCause , "TOOLONG-%d", iTotalTime);
  213. break;
  214. }
  215. /* Feed the frame of audio into the silence detector and see if we get a result */
  216. if (f->frametype != AST_FRAME_VOICE)
  217. dspsilence += 2 * maxWaitTimeForFrame;
  218. else {
  219. dspsilence = 0;
  220. ast_dsp_silence(silenceDetector, f, &dspsilence);
  221. }
  222. if (dspsilence > 0) {
  223. silenceDuration = dspsilence;
  224. if (silenceDuration >= betweenWordsSilence) {
  225. if (currentState != STATE_IN_SILENCE ) {
  226. previousState = currentState;
  227. ast_verb(3, "AMD: Channel [%s]. Changed state to STATE_IN_SILENCE\n", chan->name);
  228. }
  229. /* Find words less than word duration */
  230. if (consecutiveVoiceDuration < minimumWordLength && consecutiveVoiceDuration > 0){
  231. ast_verb(3, "AMD: Channel [%s]. Short Word Duration: %d\n", chan->name, consecutiveVoiceDuration);
  232. }
  233. currentState = STATE_IN_SILENCE;
  234. consecutiveVoiceDuration = 0;
  235. }
  236. if (inInitialSilence == 1 && silenceDuration >= initialSilence) {
  237. ast_verb(3, "AMD: Channel [%s]. ANSWERING MACHINE: silenceDuration:%d initialSilence:%d\n",
  238. chan->name, silenceDuration, initialSilence);
  239. ast_frfree(f);
  240. strcpy(amdStatus , "MACHINE");
  241. sprintf(amdCause , "INITIALSILENCE-%d-%d", silenceDuration, initialSilence);
  242. res = 1;
  243. break;
  244. }
  245. if (silenceDuration >= afterGreetingSilence && inGreeting == 1) {
  246. ast_verb(3, "AMD: Channel [%s]. HUMAN: silenceDuration:%d afterGreetingSilence:%d\n",
  247. chan->name, silenceDuration, afterGreetingSilence);
  248. ast_frfree(f);
  249. strcpy(amdStatus , "HUMAN");
  250. sprintf(amdCause , "HUMAN-%d-%d", silenceDuration, afterGreetingSilence);
  251. res = 1;
  252. break;
  253. }
  254. } else {
  255. consecutiveVoiceDuration += framelength;
  256. voiceDuration += framelength;
  257. /* If I have enough consecutive voice to say that I am in a Word, I can only increment the
  258. number of words if my previous state was Silence, which means that I moved into a word. */
  259. if (consecutiveVoiceDuration >= minimumWordLength && currentState == STATE_IN_SILENCE) {
  260. iWordsCount++;
  261. ast_verb(3, "AMD: Channel [%s]. Word detected. iWordsCount:%d\n", chan->name, iWordsCount);
  262. previousState = currentState;
  263. currentState = STATE_IN_WORD;
  264. }
  265. if (consecutiveVoiceDuration >= maximumWordLength){
  266. ast_verb(3, "AMD: Channel [%s]. Maximum Word Length detected. [%d]\n", chan->name, consecutiveVoiceDuration);
  267. ast_frfree(f);
  268. strcpy(amdStatus , "MACHINE");
  269. sprintf(amdCause , "MAXWORDLENGTH-%d", consecutiveVoiceDuration);
  270. break;
  271. }
  272. if (iWordsCount >= maximumNumberOfWords) {
  273. ast_verb(3, "AMD: Channel [%s]. ANSWERING MACHINE: iWordsCount:%d\n", chan->name, iWordsCount);
  274. ast_frfree(f);
  275. strcpy(amdStatus , "MACHINE");
  276. sprintf(amdCause , "MAXWORDS-%d-%d", iWordsCount, maximumNumberOfWords);
  277. res = 1;
  278. break;
  279. }
  280. if (inGreeting == 1 && voiceDuration >= greeting) {
  281. ast_verb(3, "AMD: Channel [%s]. ANSWERING MACHINE: voiceDuration:%d greeting:%d\n", chan->name, voiceDuration, greeting);
  282. ast_frfree(f);
  283. strcpy(amdStatus , "MACHINE");
  284. sprintf(amdCause , "LONGGREETING-%d-%d", voiceDuration, greeting);
  285. res = 1;
  286. break;
  287. }
  288. if (voiceDuration >= minimumWordLength ) {
  289. if (silenceDuration > 0)
  290. ast_verb(3, "AMD: Channel [%s]. Detected Talk, previous silence duration: %d\n", chan->name, silenceDuration);
  291. silenceDuration = 0;
  292. }
  293. if (consecutiveVoiceDuration >= minimumWordLength && inGreeting == 0) {
  294. /* Only go in here once to change the greeting flag when we detect the 1st word */
  295. if (silenceDuration > 0)
  296. ast_verb(3, "AMD: Channel [%s]. Before Greeting Time: silenceDuration: %d voiceDuration: %d\n", chan->name, silenceDuration, voiceDuration);
  297. inInitialSilence = 0;
  298. inGreeting = 1;
  299. }
  300. }
  301. }
  302. ast_frfree(f);
  303. }
  304. if (!res) {
  305. /* It took too long to get a frame back. Giving up. */
  306. ast_verb(3, "AMD: Channel [%s]. Too long...\n", chan->name);
  307. strcpy(amdStatus , "NOTSURE");
  308. sprintf(amdCause , "TOOLONG-%d", iTotalTime);
  309. }
  310. /* Set the status and cause on the channel */
  311. pbx_builtin_setvar_helper(chan , "AMDSTATUS" , amdStatus);
  312. pbx_builtin_setvar_helper(chan , "AMDCAUSE" , amdCause);
  313. /* Restore channel read format */
  314. if (readFormat && ast_set_read_format(chan, readFormat))
  315. ast_log(LOG_WARNING, "AMD: Unable to restore read format on '%s'\n", chan->name);
  316. /* Free the DSP used to detect silence */
  317. ast_dsp_free(silenceDetector);
  318. return;
  319. }
  320. static int amd_exec(struct ast_channel *chan, void *data)
  321. {
  322. isAnsweringMachine(chan, data);
  323. return 0;
  324. }
  325. static int load_config(int reload)
  326. {
  327. struct ast_config *cfg = NULL;
  328. char *cat = NULL;
  329. struct ast_variable *var = NULL;
  330. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  331. dfltSilenceThreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
  332. if (!(cfg = ast_config_load("amd.conf", config_flags))) {
  333. ast_log(LOG_ERROR, "Configuration file amd.conf missing.\n");
  334. return -1;
  335. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED)
  336. return 0;
  337. cat = ast_category_browse(cfg, NULL);
  338. while (cat) {
  339. if (!strcasecmp(cat, "general") ) {
  340. var = ast_variable_browse(cfg, cat);
  341. while (var) {
  342. if (!strcasecmp(var->name, "initial_silence")) {
  343. dfltInitialSilence = atoi(var->value);
  344. } else if (!strcasecmp(var->name, "greeting")) {
  345. dfltGreeting = atoi(var->value);
  346. } else if (!strcasecmp(var->name, "after_greeting_silence")) {
  347. dfltAfterGreetingSilence = atoi(var->value);
  348. } else if (!strcasecmp(var->name, "silence_threshold")) {
  349. dfltSilenceThreshold = atoi(var->value);
  350. } else if (!strcasecmp(var->name, "total_analysis_time")) {
  351. dfltTotalAnalysisTime = atoi(var->value);
  352. } else if (!strcasecmp(var->name, "min_word_length")) {
  353. dfltMinimumWordLength = atoi(var->value);
  354. } else if (!strcasecmp(var->name, "between_words_silence")) {
  355. dfltBetweenWordsSilence = atoi(var->value);
  356. } else if (!strcasecmp(var->name, "maximum_number_of_words")) {
  357. dfltMaximumNumberOfWords = atoi(var->value);
  358. } else if (!strcasecmp(var->name, "maximum_word_length")) {
  359. dfltMaximumWordLength = atoi(var->value);
  360. } else {
  361. ast_log(LOG_WARNING, "%s: Cat:%s. Unknown keyword %s at line %d of amd.conf\n",
  362. app, cat, var->name, var->lineno);
  363. }
  364. var = var->next;
  365. }
  366. }
  367. cat = ast_category_browse(cfg, cat);
  368. }
  369. ast_config_destroy(cfg);
  370. ast_verb(3, "AMD defaults: initialSilence [%d] greeting [%d] afterGreetingSilence [%d] "
  371. "totalAnalysisTime [%d] minimumWordLength [%d] betweenWordsSilence [%d] maximumNumberOfWords [%d] silenceThreshold [%d] maximumWordLength [%d]\n",
  372. dfltInitialSilence, dfltGreeting, dfltAfterGreetingSilence, dfltTotalAnalysisTime,
  373. dfltMinimumWordLength, dfltBetweenWordsSilence, dfltMaximumNumberOfWords, dfltSilenceThreshold, dfltMaximumWordLength);
  374. return 0;
  375. }
  376. static int unload_module(void)
  377. {
  378. return ast_unregister_application(app);
  379. }
  380. static int load_module(void)
  381. {
  382. if (load_config(0))
  383. return AST_MODULE_LOAD_DECLINE;
  384. if (ast_register_application(app, amd_exec, synopsis, descrip))
  385. return AST_MODULE_LOAD_FAILURE;
  386. return AST_MODULE_LOAD_SUCCESS;
  387. }
  388. static int reload(void)
  389. {
  390. if (load_config(1))
  391. return AST_MODULE_LOAD_DECLINE;
  392. return AST_MODULE_LOAD_SUCCESS;
  393. }
  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,
  398. );