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