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