Asterisk data retrieval API.
[asterisk/asterisk.git] / apps / app_talkdetect.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.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
19 /*! \file
20  *
21  * \brief Playback a file with audio detect
22  *
23  * \author Mark Spencer <markster@digium.com>
24  * 
25  * \ingroup applications
26  */
27  
28 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #include "asterisk/lock.h"
33 #include "asterisk/file.h"
34 #include "asterisk/channel.h"
35 #include "asterisk/pbx.h"
36 #include "asterisk/module.h"
37 #include "asterisk/translate.h"
38 #include "asterisk/utils.h"
39 #include "asterisk/dsp.h"
40 #include "asterisk/app.h"
41
42 /*** DOCUMENTATION
43         <application name="BackgroundDetect" language="en_US">
44                 <synopsis>
45                         Background a file with talk detect.
46                 </synopsis>
47                 <syntax>
48                         <parameter name="filename" required="true" />
49                         <parameter name="sil">
50                                 <para>If not specified, defaults to <literal>1000</literal>.</para>
51                         </parameter>
52                         <parameter name="min">
53                                 <para>If not specified, defaults to <literal>100</literal>.</para>
54                         </parameter>
55                         <parameter name="max">
56                                 <para>If not specified, defaults to <literal>infinity</literal>.</para>
57                         </parameter>
58                         <parameter name="analysistime">
59                                 <para>If not specified, defaults to <literal>infinity</literal>.</para>
60                         </parameter>
61                 </syntax>
62                 <description>
63                         <para>Plays back <replaceable>filename</replaceable>, waiting for interruption from a given digit (the digit
64                         must start the beginning of a valid extension, or it will be ignored). During
65                         the playback of the file, audio is monitored in the receive direction, and if
66                         a period of non-silence which is greater than <replaceable>min</replaceable> ms yet less than
67                         <replaceable>max</replaceable> ms is followed by silence for at least <replaceable>sil</replaceable> ms,
68                         which occurs during the first <replaceable>analysistime</replaceable> ms, then the audio playback is
69                         aborted and processing jumps to the <replaceable>talk</replaceable> extension, if available.</para>
70                 </description>
71         </application>
72  ***/
73
74 static char *app = "BackgroundDetect";
75
76 static int background_detect_exec(struct ast_channel *chan, const char *data)
77 {
78         int res = 0;
79         char *tmp;
80         struct ast_frame *fr;
81         int notsilent = 0;
82         struct timeval start = { 0, 0 };
83         struct timeval detection_start = { 0, 0 };
84         int sil = 1000;
85         int min = 100;
86         int max = -1;
87         int analysistime = -1;
88         int continue_analysis = 1;
89         int x;
90         int origrformat = 0;
91         struct ast_dsp *dsp = NULL;
92         AST_DECLARE_APP_ARGS(args,
93                 AST_APP_ARG(filename);
94                 AST_APP_ARG(silence);
95                 AST_APP_ARG(min);
96                 AST_APP_ARG(max);
97                 AST_APP_ARG(analysistime);
98         );
99         
100         if (ast_strlen_zero(data)) {
101                 ast_log(LOG_WARNING, "BackgroundDetect requires an argument (filename)\n");
102                 return -1;
103         }
104
105         tmp = ast_strdupa(data);
106         AST_STANDARD_APP_ARGS(args, tmp);
107
108         if (!ast_strlen_zero(args.silence) && (sscanf(args.silence, "%30d", &x) == 1) && (x > 0)) {
109                 sil = x;
110         }
111         if (!ast_strlen_zero(args.min) && (sscanf(args.min, "%30d", &x) == 1) && (x > 0)) {
112                 min = x;
113         }
114         if (!ast_strlen_zero(args.max) && (sscanf(args.max, "%30d", &x) == 1) && (x > 0)) {
115                 max = x;
116         }
117         if (!ast_strlen_zero(args.analysistime) && (sscanf(args.analysistime, "%30d", &x) == 1) && (x > 0)) {
118                 analysistime = x;
119         }
120
121         ast_debug(1, "Preparing detect of '%s', sil=%d, min=%d, max=%d, analysistime=%d\n", args.filename, sil, min, max, analysistime);
122         do {
123                 if (chan->_state != AST_STATE_UP) {
124                         if ((res = ast_answer(chan))) {
125                                 break;
126                         }
127                 }
128
129                 origrformat = chan->readformat;
130                 if ((ast_set_read_format(chan, AST_FORMAT_SLINEAR))) {
131                         ast_log(LOG_WARNING, "Unable to set read format to linear!\n");
132                         res = -1;
133                         break;
134                 }
135
136                 if (!(dsp = ast_dsp_new())) {
137                         ast_log(LOG_WARNING, "Unable to allocate DSP!\n");
138                         res = -1;
139                         break;
140                 }
141                 ast_stopstream(chan);
142                 if (ast_streamfile(chan, tmp, chan->language)) {
143                         ast_log(LOG_WARNING, "ast_streamfile failed on %s for %s\n", chan->name, (char *)data);
144                         break;
145                 }
146                 detection_start = ast_tvnow();
147                 while (chan->stream) {
148                         res = ast_sched_wait(chan->sched);
149                         if ((res < 0) && !chan->timingfunc) {
150                                 res = 0;
151                                 break;
152                         }
153                         if (res < 0) {
154                                 res = 1000;
155                         }
156                         res = ast_waitfor(chan, res);
157                         if (res < 0) {
158                                 ast_log(LOG_WARNING, "Waitfor failed on %s\n", chan->name);
159                                 break;
160                         } else if (res > 0) {
161                                 fr = ast_read(chan);
162                                 if (continue_analysis && analysistime >= 0) {
163                                         /* If we have a limit for the time to analyze voice
164                                          * frames and the time has not expired */
165                                         if (ast_tvdiff_ms(ast_tvnow(), detection_start) >= analysistime) {
166                                                 continue_analysis = 0;
167                                                 ast_verb(3, "BackgroundDetect: Talk analysis time complete on %s.\n", chan->name);
168                                         }
169                                 }
170                                 
171                                 if (!fr) {
172                                         res = -1;
173                                         break;
174                                 } else if (fr->frametype == AST_FRAME_DTMF) {
175                                         char t[2];
176                                         t[0] = fr->subclass.integer;
177                                         t[1] = '\0';
178                                         if (ast_canmatch_extension(chan, chan->context, t, 1, chan->cid.cid_num)) {
179                                                 /* They entered a valid  extension, or might be anyhow */
180                                                 res = fr->subclass.integer;
181                                                 ast_frfree(fr);
182                                                 break;
183                                         }
184                                 } else if ((fr->frametype == AST_FRAME_VOICE) && (fr->subclass.codec == AST_FORMAT_SLINEAR) && continue_analysis) {
185                                         int totalsilence;
186                                         int ms;
187                                         res = ast_dsp_silence(dsp, fr, &totalsilence);
188                                         if (res && (totalsilence > sil)) {
189                                                 /* We've been quiet a little while */
190                                                 if (notsilent) {
191                                                         /* We had heard some talking */
192                                                         ms = ast_tvdiff_ms(ast_tvnow(), start);
193                                                         ms -= sil;
194                                                         if (ms < 0)
195                                                                 ms = 0;
196                                                         if ((ms > min) && ((max < 0) || (ms < max))) {
197                                                                 char ms_str[12];
198                                                                 ast_debug(1, "Found qualified token of %d ms\n", ms);
199
200                                                                 /* Save detected talk time (in milliseconds) */ 
201                                                                 snprintf(ms_str, sizeof(ms_str), "%d", ms);     
202                                                                 pbx_builtin_setvar_helper(chan, "TALK_DETECTED", ms_str);
203
204                                                                 ast_goto_if_exists(chan, chan->context, "talk", 1);
205                                                                 res = 0;
206                                                                 ast_frfree(fr);
207                                                                 break;
208                                                         } else {
209                                                                 ast_debug(1, "Found unqualified token of %d ms\n", ms);
210                                                         }
211                                                         notsilent = 0;
212                                                 }
213                                         } else {
214                                                 if (!notsilent) {
215                                                         /* Heard some audio, mark the begining of the token */
216                                                         start = ast_tvnow();
217                                                         ast_debug(1, "Start of voice token!\n");
218                                                         notsilent = 1;
219                                                 }
220                                         }
221                                 }
222                                 ast_frfree(fr);
223                         }
224                         ast_sched_runq(chan->sched);
225                 }
226                 ast_stopstream(chan);
227         } while (0);
228
229         if (res > -1) {
230                 if (origrformat && ast_set_read_format(chan, origrformat)) {
231                         ast_log(LOG_WARNING, "Failed to restore read format for %s to %s\n", 
232                                 chan->name, ast_getformatname(origrformat));
233                 }
234         }
235         if (dsp) {
236                 ast_dsp_free(dsp);
237         }
238         return res;
239 }
240
241 static int unload_module(void)
242 {
243         return ast_unregister_application(app);
244 }
245
246 static int load_module(void)
247 {
248         return ast_register_application_xml(app, background_detect_exec);
249 }
250
251 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Playback with Talk Detection");