res_pjsip_t38: Don't pass T.38 control frames through to other hooks.
[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         struct ast_silence_generator *silgen = NULL;
164         struct ast_flags flags = { 0, };
165         AST_DECLARE_APP_ARGS(args,
166                 AST_APP_ARG(filename);
167                 AST_APP_ARG(silence);
168                 AST_APP_ARG(maxduration);
169                 AST_APP_ARG(options);
170         );
171         int ms;
172         struct timeval start;
173
174         ast_format_clear(&rfmt);
175
176         /* The next few lines of code parse out the filename and header from the input string */
177         if (ast_strlen_zero(data)) { /* no data implies no filename or anything is present */
178                 ast_log(LOG_WARNING, "Record requires an argument (filename)\n");
179                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
180                 return -1;
181         }
182
183         parse = ast_strdupa(data);
184         AST_STANDARD_APP_ARGS(args, parse);
185         if (args.argc == 4)
186                 ast_app_parse_options(app_opts, &flags, opts, args.options);
187
188         if (!ast_strlen_zero(args.filename)) {
189                 if (strstr(args.filename, "%d"))
190                         ast_set_flag(&flags, FLAG_HAS_PERCENT);
191                 ext = strrchr(args.filename, '.'); /* to support filename with a . in the filename, not format */
192                 if (!ext)
193                         ext = strchr(args.filename, ':');
194                 if (ext) {
195                         *ext = '\0';
196                         ext++;
197                 }
198         }
199         if (!ext) {
200                 ast_log(LOG_WARNING, "No extension specified to filename!\n");
201                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
202                 return -1;
203         }
204         if (args.silence) {
205                 if ((sscanf(args.silence, "%30d", &i) == 1) && (i > -1)) {
206                         silence = i * 1000;
207                 } else if (!ast_strlen_zero(args.silence)) {
208                         ast_log(LOG_WARNING, "'%s' is not a valid silence duration\n", args.silence);
209                 }
210         }
211         
212         if (args.maxduration) {
213                 if ((sscanf(args.maxduration, "%30d", &i) == 1) && (i > -1))
214                         /* Convert duration to milliseconds */
215                         maxduration = i * 1000;
216                 else if (!ast_strlen_zero(args.maxduration))
217                         ast_log(LOG_WARNING, "'%s' is not a valid maximum duration\n", args.maxduration);
218         }
219
220         if (ast_test_flag(&flags, OPTION_STAR_TERMINATE))
221                 terminator = '*';
222         if (ast_test_flag(&flags, OPTION_IGNORE_TERMINATE))
223                 terminator = '\0';
224
225         /* done parsing */
226
227         /* these are to allow the use of the %d in the config file for a wild card of sort to
228           create a new file with the inputed name scheme */
229         if (ast_test_flag(&flags, FLAG_HAS_PERCENT)) {
230                 AST_DECLARE_APP_ARGS(fname,
231                         AST_APP_ARG(piece)[100];
232                 );
233                 char *tmp2 = ast_strdupa(args.filename);
234                 char countstring[15];
235                 int idx;
236
237                 /* Separate each piece out by the format specifier */
238                 AST_NONSTANDARD_APP_ARGS(fname, tmp2, '%');
239                 do {
240                         int tmplen;
241                         /* First piece has no leading percent, so it's copied verbatim */
242                         ast_copy_string(tmp, fname.piece[0], sizeof(tmp));
243                         tmplen = strlen(tmp);
244                         for (idx = 1; idx < fname.argc; idx++) {
245                                 if (fname.piece[idx][0] == 'd') {
246                                         /* Substitute the count */
247                                         snprintf(countstring, sizeof(countstring), "%d", count);
248                                         ast_copy_string(tmp + tmplen, countstring, sizeof(tmp) - tmplen);
249                                         tmplen += strlen(countstring);
250                                 } else if (tmplen + 2 < sizeof(tmp)) {
251                                         /* Unknown format specifier - just copy it verbatim */
252                                         tmp[tmplen++] = '%';
253                                         tmp[tmplen++] = fname.piece[idx][0];
254                                 }
255                                 /* Copy the remaining portion of the piece */
256                                 ast_copy_string(tmp + tmplen, &(fname.piece[idx][1]), sizeof(tmp) - tmplen);
257                         }
258                         count++;
259                 } while (ast_fileexists(tmp, ext, ast_channel_language(chan)) > 0);
260                 pbx_builtin_setvar_helper(chan, "RECORDED_FILE", tmp);
261         } else
262                 ast_copy_string(tmp, args.filename, sizeof(tmp));
263         /* end of routine mentioned */
264
265         if (ast_channel_state(chan) != AST_STATE_UP) {
266                 if (ast_test_flag(&flags, OPTION_SKIP)) {
267                         /* At the user's option, skip if the line is not up */
268                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SKIP");
269                         return 0;
270                 } else if (!ast_test_flag(&flags, OPTION_NOANSWER)) {
271                         /* Otherwise answer unless we're supposed to record while on-hook */
272                         res = ast_answer(chan);
273                 }
274         }
275
276         if (res) {
277                 ast_log(LOG_WARNING, "Could not answer channel '%s'\n", ast_channel_name(chan));
278                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
279                 goto out;
280         }
281
282         if (!ast_test_flag(&flags, OPTION_QUIET)) {
283                 /* Some code to play a nice little beep to signify the start of the record operation */
284                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
285                 if (!res) {
286                         res = ast_waitstream(chan, "");
287                 } else {
288                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", ast_channel_name(chan));
289                 }
290                 ast_stopstream(chan);
291         }
292
293         /* The end of beep code.  Now the recording starts */
294
295         if (silence > 0) {
296                 ast_format_copy(&rfmt, ast_channel_readformat(chan));
297                 res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
298                 if (res < 0) {
299                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
300                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
301                         return -1;
302                 }
303                 sildet = ast_dsp_new();
304                 if (!sildet) {
305                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
306                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
307                         return -1;
308                 }
309                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
310         } 
311
312         /* Create the directory if it does not exist. */
313         dir = ast_strdupa(tmp);
314         if ((file = strrchr(dir, '/')))
315                 *file++ = '\0';
316         ast_mkdir (dir, 0777);
317
318         ioflags = ast_test_flag(&flags, OPTION_APPEND) ? O_CREAT|O_APPEND|O_WRONLY : O_CREAT|O_TRUNC|O_WRONLY;
319         s = ast_writefile(tmp, ext, NULL, ioflags, 0, AST_FILE_MODE);
320
321         if (!s) {
322                 ast_log(LOG_WARNING, "Could not create file %s\n", args.filename);
323                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
324                 goto out;
325         }
326
327         if (ast_opt_transmit_silence)
328                 silgen = ast_channel_start_silence_generator(chan);
329
330         /* Request a video update */
331         ast_indicate(chan, AST_CONTROL_VIDUPDATE);
332
333         if (maxduration <= 0)
334                 maxduration = -1;
335
336         start = ast_tvnow();
337         while ((ms = ast_remaining_ms(start, maxduration))) {
338                 ms = ast_waitfor(chan, ms);
339                 if (ms < 0) {
340                         break;
341                 }
342
343                 if (maxduration > 0 && ms == 0) {
344                         break;
345                 }
346
347                 f = ast_read(chan);
348                 if (!f) {
349                         res = -1;
350                         break;
351                 }
352                 if (f->frametype == AST_FRAME_VOICE) {
353                         res = ast_writestream(s, f);
354
355                         if (res) {
356                                 ast_log(LOG_WARNING, "Problem writing frame\n");
357                                 ast_frfree(f);
358                                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
359                                 break;
360                         }
361
362                         if (silence > 0) {
363                                 dspsilence = 0;
364                                 ast_dsp_silence(sildet, f, &dspsilence);
365                                 if (dspsilence) {
366                                         totalsilence = dspsilence;
367                                 } else {
368                                         totalsilence = 0;
369                                 }
370                                 if (totalsilence > silence) {
371                                         /* Ended happily with silence */
372                                         ast_frfree(f);
373                                         gotsilence = 1;
374                                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SILENCE");
375                                         break;
376                                 }
377                         }
378                 } else if (f->frametype == AST_FRAME_VIDEO) {
379                         res = ast_writestream(s, f);
380
381                         if (res) {
382                                 ast_log(LOG_WARNING, "Problem writing frame\n");
383                                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
384                                 ast_frfree(f);
385                                 break;
386                         }
387                 } else if ((f->frametype == AST_FRAME_DTMF) &&
388                            ((f->subclass.integer == terminator) ||
389                             (ast_test_flag(&flags, OPTION_ANY_TERMINATE)))) {
390                         ast_frfree(f);
391                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "DTMF");
392                         break;
393                 }
394                 ast_frfree(f);
395         }
396
397         if (maxduration > 0 && !ms) {
398                 gottimeout = 1;
399                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "TIMEOUT");
400         }
401
402         if (!f) {
403                 ast_debug(1, "Got hangup\n");
404                 res = -1;
405                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "HANGUP");
406                 if (!ast_test_flag(&flags, OPTION_KEEP)) {
407                         ast_filedelete(args.filename, NULL);
408                 }
409         }
410
411         if (gotsilence) {
412                 ast_stream_rewind(s, silence - 1000);
413                 ast_truncstream(s);
414         } else if (!gottimeout) {
415                 /* Strip off the last 1/4 second of it */
416                 ast_stream_rewind(s, 250);
417                 ast_truncstream(s);
418         }
419         ast_closestream(s);
420
421         if (silgen)
422                 ast_channel_stop_silence_generator(chan, silgen);
423
424 out:
425         if ((silence > 0) && rfmt.id) {
426                 res = ast_set_read_format(chan, &rfmt);
427                 if (res) {
428                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
429                 }
430         }
431
432         if (sildet) {
433                 ast_dsp_free(sildet);
434         }
435         return res;
436 }
437
438 static int unload_module(void)
439 {
440         return ast_unregister_application(app);
441 }
442
443 static int load_module(void)
444 {
445         return ast_register_application_xml(app, record_exec);
446 }
447
448 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Trivial Record Application");