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