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