Add an option to Record which enables a mode where any DTMF digit will terminate...
[asterisk/asterisk.git] / apps / app_record.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Matthew Fredrickson <creslin@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 Trivial application to record a sound file
22  *
23  * \author Matthew Fredrickson <creslin@digium.com>
24  *
25  * \ingroup applications
26  */
27  
28 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #include "asterisk/file.h"
33 #include "asterisk/pbx.h"
34 #include "asterisk/module.h"
35 #include "asterisk/app.h"
36 #include "asterisk/channel.h"
37 #include "asterisk/dsp.h"       /* use dsp routines for silence detection */
38
39 /*** DOCUMENTATION
40         <application name="Record" language="en_US">
41                 <synopsis>
42                         Record to a file.
43                 </synopsis>
44                 <syntax>
45                         <parameter name="filename" required="true" argsep=".">
46                                 <argument name="filename" required="true" />
47                                 <argument name="format" required="true">
48                                         <para>Is the format of the file type to be recorded (wav, gsm, etc).</para>
49                                 </argument>
50                         </parameter>
51                         <parameter name="silence">
52                                 <para>Is the number of seconds of silence to allow before returning.</para>
53                         </parameter>
54                         <parameter name="maxduration">
55                                 <para>Is the maximum recording duration in seconds. If missing
56                                 or 0 there is no maximum.</para>
57                         </parameter>
58                         <parameter name="options">
59                                 <optionlist>
60                                         <option name="a">
61                                                 <para>Append to existing recording rather than replacing.</para>
62                                         </option>
63                                         <option name="n">
64                                                 <para>Do not answer, but record anyway if line not yet answered.</para>
65                                         </option>
66                                         <option name="q">
67                                                 <para>quiet (do not play a beep tone).</para>
68                                         </option>
69                                         <option name="s">
70                                                 <para>skip recording if the line is not yet answered.</para>
71                                         </option>
72                                         <option name="t">
73                                                 <para>use alternate '*' terminator key (DTMF) instead of default '#'</para>
74                                         </option>
75                                         <option name="x">
76                                                 <para>Ignore all terminator keys (DTMF) and keep recording until hangup.</para>
77                                         </option>
78                                         <option name="k">
79                                                 <para>Keep recording if channel hangs up.</para>
80                                         </option>
81                                         <option name="y">
82                                                 <para>Terminate recording if *any* DTMF digit is received.</para>
83                                         </option>
84                                 </optionlist>
85                         </parameter>
86                 </syntax>
87                 <description>
88                         <para>If filename contains <literal>%d</literal>, these characters will be replaced with a number
89                         incremented by one each time the file is recorded.
90                         Use <astcli>core show file formats</astcli> to see the available formats on your system
91                         User can press <literal>#</literal> to terminate the recording and continue to the next priority.
92                         If the user hangs up during a recording, all data will be lost and the application will terminate.</para>
93                         <variablelist>
94                                 <variable name="RECORDED_FILE">
95                                         <para>Will be set to the final filename of the recording.</para>
96                                 </variable>
97                                 <variable name="RECORD_STATUS">
98                                         <para>This is the final status of the command</para>
99                                         <value name="DTMF">A terminating DTMF was received ('#' or '*', depending upon option 't')</value>
100                                         <value name="SILENCE">The maximum silence occurred in the recording.</value>
101                                         <value name="SKIP">The line was not yet answered and the 's' option was specified.</value>
102                                         <value name="TIMEOUT">The maximum length was reached.</value>
103                                         <value name="HANGUP">The channel was hung up.</value>
104                                         <value name="ERROR">An unrecoverable error occurred, which resulted in a WARNING to the logs.</value>
105                                 </variable>
106                         </variablelist>
107                 </description>
108         </application>
109
110  ***/
111
112 static char *app = "Record";
113
114 enum {
115         OPTION_APPEND = (1 << 0),
116         OPTION_NOANSWER = (1 << 1),
117         OPTION_QUIET = (1 << 2),
118         OPTION_SKIP = (1 << 3),
119         OPTION_STAR_TERMINATE = (1 << 4),
120         OPTION_IGNORE_TERMINATE = (1 << 5),
121         OPTION_KEEP = (1 << 6),
122         FLAG_HAS_PERCENT = (1 << 7),
123         OPTION_ANY_TERMINATE = (1 << 8),
124 };
125
126 AST_APP_OPTIONS(app_opts,{
127         AST_APP_OPTION('a', OPTION_APPEND),
128         AST_APP_OPTION('k', OPTION_KEEP),       
129         AST_APP_OPTION('n', OPTION_NOANSWER),
130         AST_APP_OPTION('q', OPTION_QUIET),
131         AST_APP_OPTION('s', OPTION_SKIP),
132         AST_APP_OPTION('t', OPTION_STAR_TERMINATE),
133         AST_APP_OPTION('y', OPTION_ANY_TERMINATE),
134         AST_APP_OPTION('x', OPTION_IGNORE_TERMINATE),
135 });
136
137 static int record_exec(struct ast_channel *chan, const char *data)
138 {
139         int res = 0;
140         int count = 0;
141         char *ext = NULL, *opts[0];
142         char *parse, *dir, *file;
143         int i = 0;
144         char tmp[256];
145
146         struct ast_filestream *s = NULL;
147         struct ast_frame *f = NULL;
148         
149         struct ast_dsp *sildet = NULL;          /* silence detector dsp */
150         int totalsilence = 0;
151         int dspsilence = 0;
152         int silence = 0;                /* amount of silence to allow */
153         int gotsilence = 0;             /* did we timeout for silence? */
154         int maxduration = 0;            /* max duration of recording in milliseconds */
155         int gottimeout = 0;             /* did we timeout for maxduration exceeded? */
156         int terminator = '#';
157         int rfmt = 0;
158         int ioflags;
159         int waitres;
160         struct ast_silence_generator *silgen = NULL;
161         struct ast_flags flags = { 0, };
162         AST_DECLARE_APP_ARGS(args,
163                 AST_APP_ARG(filename);
164                 AST_APP_ARG(silence);
165                 AST_APP_ARG(maxduration);
166                 AST_APP_ARG(options);
167         );
168         
169         /* The next few lines of code parse out the filename and header from the input string */
170         if (ast_strlen_zero(data)) { /* no data implies no filename or anything is present */
171                 ast_log(LOG_WARNING, "Record requires an argument (filename)\n");
172                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
173                 return -1;
174         }
175
176         parse = ast_strdupa(data);
177         AST_STANDARD_APP_ARGS(args, parse);
178         if (args.argc == 4)
179                 ast_app_parse_options(app_opts, &flags, opts, args.options);
180
181         if (!ast_strlen_zero(args.filename)) {
182                 if (strstr(args.filename, "%d"))
183                         ast_set_flag(&flags, FLAG_HAS_PERCENT);
184                 ext = strrchr(args.filename, '.'); /* to support filename with a . in the filename, not format */
185                 if (!ext)
186                         ext = strchr(args.filename, ':');
187                 if (ext) {
188                         *ext = '\0';
189                         ext++;
190                 }
191         }
192         if (!ext) {
193                 ast_log(LOG_WARNING, "No extension specified to filename!\n");
194                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
195                 return -1;
196         }
197         if (args.silence) {
198                 if ((sscanf(args.silence, "%30d", &i) == 1) && (i > -1)) {
199                         silence = i * 1000;
200                 } else if (!ast_strlen_zero(args.silence)) {
201                         ast_log(LOG_WARNING, "'%s' is not a valid silence duration\n", args.silence);
202                 }
203         }
204         
205         if (args.maxduration) {
206                 if ((sscanf(args.maxduration, "%30d", &i) == 1) && (i > -1))
207                         /* Convert duration to milliseconds */
208                         maxduration = i * 1000;
209                 else if (!ast_strlen_zero(args.maxduration))
210                         ast_log(LOG_WARNING, "'%s' is not a valid maximum duration\n", args.maxduration);
211         }
212
213         if (ast_test_flag(&flags, OPTION_STAR_TERMINATE))
214                 terminator = '*';
215         if (ast_test_flag(&flags, OPTION_IGNORE_TERMINATE))
216                 terminator = '\0';
217
218         /* done parsing */
219
220         /* these are to allow the use of the %d in the config file for a wild card of sort to
221           create a new file with the inputed name scheme */
222         if (ast_test_flag(&flags, FLAG_HAS_PERCENT)) {
223                 AST_DECLARE_APP_ARGS(fname,
224                         AST_APP_ARG(piece)[100];
225                 );
226                 char *tmp2 = ast_strdupa(args.filename);
227                 char countstring[15];
228                 int idx;
229
230                 /* Separate each piece out by the format specifier */
231                 AST_NONSTANDARD_APP_ARGS(fname, tmp2, '%');
232                 do {
233                         int tmplen;
234                         /* First piece has no leading percent, so it's copied verbatim */
235                         ast_copy_string(tmp, fname.piece[0], sizeof(tmp));
236                         tmplen = strlen(tmp);
237                         for (idx = 1; idx < fname.argc; idx++) {
238                                 if (fname.piece[idx][0] == 'd') {
239                                         /* Substitute the count */
240                                         snprintf(countstring, sizeof(countstring), "%d", count);
241                                         ast_copy_string(tmp + tmplen, countstring, sizeof(tmp) - tmplen);
242                                         tmplen += strlen(countstring);
243                                 } else if (tmplen + 2 < sizeof(tmp)) {
244                                         /* Unknown format specifier - just copy it verbatim */
245                                         tmp[tmplen++] = '%';
246                                         tmp[tmplen++] = fname.piece[idx][0];
247                                 }
248                                 /* Copy the remaining portion of the piece */
249                                 ast_copy_string(tmp + tmplen, &(fname.piece[idx][1]), sizeof(tmp) - tmplen);
250                         }
251                         count++;
252                 } while (ast_fileexists(tmp, ext, chan->language) > 0);
253                 pbx_builtin_setvar_helper(chan, "RECORDED_FILE", tmp);
254         } else
255                 ast_copy_string(tmp, args.filename, sizeof(tmp));
256         /* end of routine mentioned */
257
258         if (chan->_state != AST_STATE_UP) {
259                 if (ast_test_flag(&flags, OPTION_SKIP)) {
260                         /* At the user's option, skip if the line is not up */
261                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SKIP");
262                         return 0;
263                 } else if (!ast_test_flag(&flags, OPTION_NOANSWER)) {
264                         /* Otherwise answer unless we're supposed to record while on-hook */
265                         res = ast_answer(chan);
266                 }
267         }
268
269         if (res) {
270                 ast_log(LOG_WARNING, "Could not answer channel '%s'\n", chan->name);
271                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
272                 goto out;
273         }
274
275         if (!ast_test_flag(&flags, OPTION_QUIET)) {
276                 /* Some code to play a nice little beep to signify the start of the record operation */
277                 res = ast_streamfile(chan, "beep", chan->language);
278                 if (!res) {
279                         res = ast_waitstream(chan, "");
280                 } else {
281                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", chan->name);
282                 }
283                 ast_stopstream(chan);
284         }
285
286         /* The end of beep code.  Now the recording starts */
287
288         if (silence > 0) {
289                 rfmt = chan->readformat;
290                 res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
291                 if (res < 0) {
292                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
293                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
294                         return -1;
295                 }
296                 sildet = ast_dsp_new();
297                 if (!sildet) {
298                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
299                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
300                         return -1;
301                 }
302                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
303         } 
304
305         /* Create the directory if it does not exist. */
306         dir = ast_strdupa(tmp);
307         if ((file = strrchr(dir, '/')))
308                 *file++ = '\0';
309         ast_mkdir (dir, 0777);
310
311         ioflags = ast_test_flag(&flags, OPTION_APPEND) ? O_CREAT|O_APPEND|O_WRONLY : O_CREAT|O_TRUNC|O_WRONLY;
312         s = ast_writefile(tmp, ext, NULL, ioflags, 0, AST_FILE_MODE);
313
314         if (!s) {
315                 ast_log(LOG_WARNING, "Could not create file %s\n", args.filename);
316                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
317                 goto out;
318         }
319
320         if (ast_opt_transmit_silence)
321                 silgen = ast_channel_start_silence_generator(chan);
322
323         /* Request a video update */
324         ast_indicate(chan, AST_CONTROL_VIDUPDATE);
325
326         if (maxduration <= 0)
327                 maxduration = -1;
328
329         while ((waitres = ast_waitfor(chan, maxduration)) > -1) {
330                 if (maxduration > 0) {
331                         if (waitres == 0) {
332                                 gottimeout = 1;
333                                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "TIMEOUT");
334                                 break;
335                         }
336                         maxduration = waitres;
337                 }
338
339                 f = ast_read(chan);
340                 if (!f) {
341                         res = -1;
342                         break;
343                 }
344                 if (f->frametype == AST_FRAME_VOICE) {
345                         res = ast_writestream(s, f);
346
347                         if (res) {
348                                 ast_log(LOG_WARNING, "Problem writing frame\n");
349                                 ast_frfree(f);
350                                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
351                                 break;
352                         }
353
354                         if (silence > 0) {
355                                 dspsilence = 0;
356                                 ast_dsp_silence(sildet, f, &dspsilence);
357                                 if (dspsilence) {
358                                         totalsilence = dspsilence;
359                                 } else {
360                                         totalsilence = 0;
361                                 }
362                                 if (totalsilence > silence) {
363                                         /* Ended happily with silence */
364                                         ast_frfree(f);
365                                         gotsilence = 1;
366                                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SILENCE");
367                                         break;
368                                 }
369                         }
370                 } else if (f->frametype == AST_FRAME_VIDEO) {
371                         res = ast_writestream(s, f);
372
373                         if (res) {
374                                 ast_log(LOG_WARNING, "Problem writing frame\n");
375                                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
376                                 ast_frfree(f);
377                                 break;
378                         }
379                 } else if ((f->frametype == AST_FRAME_DTMF) &&
380                            ((f->subclass.integer == terminator) ||
381                             (ast_test_flag(&flags, OPTION_ANY_TERMINATE)))) {
382                         ast_frfree(f);
383                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "DTMF");
384                         break;
385                 }
386                 ast_frfree(f);
387         }
388         if (!f) {
389                 ast_debug(1, "Got hangup\n");
390                 res = -1;
391                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "HANGUP");
392                 if (!ast_test_flag(&flags, OPTION_KEEP)) {
393                         ast_filedelete(args.filename, NULL);
394                 }
395         }
396
397         if (gotsilence) {
398                 ast_stream_rewind(s, silence - 1000);
399                 ast_truncstream(s);
400         } else if (!gottimeout) {
401                 /* Strip off the last 1/4 second of it */
402                 ast_stream_rewind(s, 250);
403                 ast_truncstream(s);
404         }
405         ast_closestream(s);
406
407         if (silgen)
408                 ast_channel_stop_silence_generator(chan, silgen);
409
410 out:
411         if ((silence > 0) && rfmt) {
412                 res = ast_set_read_format(chan, rfmt);
413                 if (res)
414                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", chan->name);
415                 if (sildet)
416                         ast_dsp_free(sildet);
417         }
418
419         return res;
420 }
421
422 static int unload_module(void)
423 {
424         return ast_unregister_application(app);
425 }
426
427 static int load_module(void)
428 {
429         return ast_register_application_xml(app, record_exec);
430 }
431
432 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Trivial Record Application");