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