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