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