Merge "astobj2: Create function to copy weak proxied objects from container."
[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 #include "asterisk/file.h"
35 #include "asterisk/pbx.h"
36 #include "asterisk/module.h"
37 #include "asterisk/app.h"
38 #include "asterisk/channel.h"
39 #include "asterisk/dsp.h"       /* use dsp routines for silence detection */
40 #include "asterisk/format_cache.h"
41 #include "asterisk/paths.h"
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="u">
84                                                 <para>Don't truncate recorded silence.</para>
85                                         </option>
86                                         <option name="x">
87                                                 <para>Ignore all terminator keys (DTMF) and keep recording until hangup.</para>
88                                         </option>
89                                         <option name="k">
90                                                 <para>Keep recorded file upon hangup.</para>
91                                         </option>
92                                         <option name="y">
93                                                 <para>Terminate recording if *any* DTMF digit is received.</para>
94                                         </option>
95                                 </optionlist>
96                         </parameter>
97                 </syntax>
98                 <description>
99                         <para>If filename contains <literal>%d</literal>, these characters will be replaced with a number
100                         incremented by one each time the file is recorded.
101                         Use <astcli>core show file formats</astcli> to see the available formats on your system
102                         User can press <literal>#</literal> to terminate the recording and continue to the next priority.
103                         If the user hangs up during a recording, all data will be lost and the application will terminate.</para>
104                         <variablelist>
105                                 <variable name="RECORDED_FILE">
106                                         <para>Will be set to the final filename of the recording, without an extension.</para>
107                                 </variable>
108                                 <variable name="RECORD_STATUS">
109                                         <para>This is the final status of the command</para>
110                                         <value name="DTMF">A terminating DTMF was received ('#' or '*', depending upon option 't')</value>
111                                         <value name="SILENCE">The maximum silence occurred in the recording.</value>
112                                         <value name="SKIP">The line was not yet answered and the 's' option was specified.</value>
113                                         <value name="TIMEOUT">The maximum length was reached.</value>
114                                         <value name="HANGUP">The channel was hung up.</value>
115                                         <value name="ERROR">An unrecoverable error occurred, which resulted in a WARNING to the logs.</value>
116                                 </variable>
117                         </variablelist>
118                 </description>
119         </application>
120
121  ***/
122
123 #define OPERATOR_KEY '0'
124
125 static char *app = "Record";
126
127 enum {
128         OPTION_APPEND = (1 << 0),
129         OPTION_NOANSWER = (1 << 1),
130         OPTION_QUIET = (1 << 2),
131         OPTION_SKIP = (1 << 3),
132         OPTION_STAR_TERMINATE = (1 << 4),
133         OPTION_IGNORE_TERMINATE = (1 << 5),
134         OPTION_KEEP = (1 << 6),
135         OPTION_ANY_TERMINATE = (1 << 7),
136         OPTION_OPERATOR_EXIT = (1 << 8),
137         OPTION_NO_TRUNCATE = (1 << 9),
138 };
139
140 enum dtmf_response {
141         RESPONSE_NO_MATCH = 0,
142         RESPONSE_OPERATOR,
143         RESPONSE_DTMF,
144 };
145
146 AST_APP_OPTIONS(app_opts,{
147         AST_APP_OPTION('a', OPTION_APPEND),
148         AST_APP_OPTION('k', OPTION_KEEP),
149         AST_APP_OPTION('n', OPTION_NOANSWER),
150         AST_APP_OPTION('o', OPTION_OPERATOR_EXIT),
151         AST_APP_OPTION('q', OPTION_QUIET),
152         AST_APP_OPTION('s', OPTION_SKIP),
153         AST_APP_OPTION('t', OPTION_STAR_TERMINATE),
154         AST_APP_OPTION('u', OPTION_NO_TRUNCATE),
155         AST_APP_OPTION('y', OPTION_ANY_TERMINATE),
156         AST_APP_OPTION('x', OPTION_IGNORE_TERMINATE),
157 });
158
159 /*!
160  * \internal
161  * \brief Used to determine what action to take when DTMF is received while recording
162  * \since 13.0.0
163  *
164  * \param chan channel being recorded
165  * \param flags option flags in use by the record application
166  * \param dtmf_integer the integer value of the DTMF key received
167  * \param terminator key currently set to be pressed for normal termination
168  *
169  * \returns One of enum dtmf_response
170  */
171 static enum dtmf_response record_dtmf_response(struct ast_channel *chan,
172         struct ast_flags *flags, int dtmf_integer, int terminator)
173 {
174         if ((dtmf_integer == OPERATOR_KEY) &&
175                 (ast_test_flag(flags, OPTION_OPERATOR_EXIT))) {
176                 return RESPONSE_OPERATOR;
177         }
178
179         if ((dtmf_integer == terminator) ||
180                 (ast_test_flag(flags, OPTION_ANY_TERMINATE))) {
181                 return RESPONSE_DTMF;
182         }
183
184         return RESPONSE_NO_MATCH;
185 }
186
187 static int create_destination_directory(const char *path)
188 {
189         int res;
190         char directory[PATH_MAX], *file_sep;
191
192         if (!(file_sep = strrchr(path, '/'))) {
193                 /* No directory to create */
194                 return 0;
195         }
196
197         /* Overwrite temporarily */
198         *file_sep = '\0';
199
200         /* Absolute path? */
201         if (path[0] == '/') {
202                 res = ast_mkdir(path, 0777);
203                 *file_sep = '/';
204                 return res;
205         }
206
207         /* Relative path */
208         res = snprintf(directory, sizeof(directory), "%s/sounds/%s",
209                                    ast_config_AST_DATA_DIR, path);
210
211         *file_sep = '/';
212
213         if (res >= sizeof(directory)) {
214                 /* We truncated, so we fail */
215                 return -1;
216         }
217
218         return ast_mkdir(directory, 0777);
219 }
220
221 static int record_exec(struct ast_channel *chan, const char *data)
222 {
223         int res = 0;
224         char *ext = NULL, *opts[0];
225         char *parse;
226         int i = 0;
227         char tmp[PATH_MAX];
228
229         struct ast_filestream *s = NULL;
230         struct ast_frame *f = NULL;
231
232         struct ast_dsp *sildet = NULL;          /* silence detector dsp */
233         int totalsilence = 0;
234         int dspsilence = 0;
235         int silence = 0;                /* amount of silence to allow */
236         int gotsilence = 0;             /* did we timeout for silence? */
237         int truncate_silence = 1;       /* truncate on complete silence recording */
238         int maxduration = 0;            /* max duration of recording in milliseconds */
239         int gottimeout = 0;             /* did we timeout for maxduration exceeded? */
240         int terminator = '#';
241         RAII_VAR(struct ast_format *, rfmt, NULL, ao2_cleanup);
242         int ioflags;
243         struct ast_silence_generator *silgen = NULL;
244         struct ast_flags flags = { 0, };
245         AST_DECLARE_APP_ARGS(args,
246                 AST_APP_ARG(filename);
247                 AST_APP_ARG(silence);
248                 AST_APP_ARG(maxduration);
249                 AST_APP_ARG(options);
250         );
251         int ms;
252         struct timeval start;
253         const char *status_response = "ERROR";
254
255         /* The next few lines of code parse out the filename and header from the input string */
256         if (ast_strlen_zero(data)) { /* no data implies no filename or anything is present */
257                 ast_log(LOG_WARNING, "Record requires an argument (filename)\n");
258                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
259                 return -1;
260         }
261
262         parse = ast_strdupa(data);
263         AST_STANDARD_APP_ARGS(args, parse);
264         if (args.argc == 4)
265                 ast_app_parse_options(app_opts, &flags, opts, args.options);
266
267         if (!ast_strlen_zero(args.filename)) {
268                 ext = strrchr(args.filename, '.'); /* to support filename with a . in the filename, not format */
269                 if (!ext)
270                         ext = strchr(args.filename, ':');
271                 if (ext) {
272                         *ext = '\0';
273                         ext++;
274                 }
275         }
276         if (!ext) {
277                 ast_log(LOG_WARNING, "No extension specified to filename!\n");
278                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
279                 return -1;
280         }
281         if (args.silence) {
282                 if ((sscanf(args.silence, "%30d", &i) == 1) && (i > -1)) {
283                         silence = i * 1000;
284                 } else if (!ast_strlen_zero(args.silence)) {
285                         ast_log(LOG_WARNING, "'%s' is not a valid silence duration\n", args.silence);
286                 }
287         }
288
289         if (ast_test_flag(&flags, OPTION_NO_TRUNCATE))
290                 truncate_silence = 0;
291
292         if (args.maxduration) {
293                 if ((sscanf(args.maxduration, "%30d", &i) == 1) && (i > -1))
294                         /* Convert duration to milliseconds */
295                         maxduration = i * 1000;
296                 else if (!ast_strlen_zero(args.maxduration))
297                         ast_log(LOG_WARNING, "'%s' is not a valid maximum duration\n", args.maxduration);
298         }
299
300         if (ast_test_flag(&flags, OPTION_STAR_TERMINATE))
301                 terminator = '*';
302         if (ast_test_flag(&flags, OPTION_IGNORE_TERMINATE))
303                 terminator = '\0';
304
305         /*
306           If a '%d' is specified as part of the filename, we replace that token with
307           sequentially incrementing numbers until we find a unique filename.
308         */
309         if (strchr(args.filename, '%')) {
310                 size_t src, dst, count = 0;
311                 size_t src_len = strlen(args.filename);
312                 size_t dst_len = sizeof(tmp) - 1;
313
314                 do {
315                         for (src = 0, dst = 0; src < src_len && dst < dst_len; src++) {
316                                 if (!strncmp(&args.filename[src], "%d", 2)) {
317                                         int s = snprintf(&tmp[dst], PATH_MAX - dst, "%zu", count);
318                                         if (s >= PATH_MAX - dst) {
319                                                 /* We truncated, so we need to bail */
320                                                 ast_log(LOG_WARNING, "Failed to create unique filename from template: %s\n", args.filename);
321                                                 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
322                                                 return -1;
323                                         }
324                                         dst += s;
325                                         src++;
326                                 } else {
327                                         tmp[dst] = args.filename[src];
328                                         tmp[++dst] = '\0';
329                                 }
330                         }
331                         count++;
332                 } while (ast_fileexists(tmp, ext, ast_channel_language(chan)) > 0);
333         } else
334                 ast_copy_string(tmp, args.filename, sizeof(tmp));
335
336         pbx_builtin_setvar_helper(chan, "RECORDED_FILE", tmp);
337
338         if (ast_channel_state(chan) != AST_STATE_UP) {
339                 if (ast_test_flag(&flags, OPTION_SKIP)) {
340                         /* At the user's option, skip if the line is not up */
341                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SKIP");
342                         return 0;
343                 } else if (!ast_test_flag(&flags, OPTION_NOANSWER)) {
344                         /* Otherwise answer unless we're supposed to record while on-hook */
345                         res = ast_answer(chan);
346                 }
347         }
348
349         if (res) {
350                 ast_log(LOG_WARNING, "Could not answer channel '%s'\n", ast_channel_name(chan));
351                 status_response = "ERROR";
352                 goto out;
353         }
354
355         if (!ast_test_flag(&flags, OPTION_QUIET)) {
356                 /* Some code to play a nice little beep to signify the start of the record operation */
357                 res = ast_streamfile(chan, "beep", ast_channel_language(chan));
358                 if (!res) {
359                         res = ast_waitstream(chan, "");
360                 } else {
361                         ast_log(LOG_WARNING, "ast_streamfile failed on %s\n", ast_channel_name(chan));
362                 }
363                 ast_stopstream(chan);
364         }
365
366         /* The end of beep code.  Now the recording starts */
367
368         if (silence > 0) {
369                 rfmt = ao2_bump(ast_channel_readformat(chan));
370                 res = ast_set_read_format(chan, ast_format_slin);
371                 if (res < 0) {
372                         ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
373                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
374                         return -1;
375                 }
376                 sildet = ast_dsp_new();
377                 if (!sildet) {
378                         ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
379                         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
380                         return -1;
381                 }
382                 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
383         }
384
385         if (create_destination_directory(tmp)) {
386                 ast_log(LOG_WARNING, "Could not create directory for file %s\n", args.filename);
387                 status_response = "ERROR";
388                 goto out;
389         }
390
391         ioflags = ast_test_flag(&flags, OPTION_APPEND) ? O_CREAT|O_APPEND|O_WRONLY : O_CREAT|O_TRUNC|O_WRONLY;
392         s = ast_writefile(tmp, ext, NULL, ioflags, 0, AST_FILE_MODE);
393
394         if (!s) {
395                 ast_log(LOG_WARNING, "Could not create file %s\n", args.filename);
396                 status_response = "ERROR";
397                 goto out;
398         }
399
400         if (ast_opt_transmit_silence)
401                 silgen = ast_channel_start_silence_generator(chan);
402
403         /* Request a video update */
404         ast_indicate(chan, AST_CONTROL_VIDUPDATE);
405
406         if (maxduration <= 0)
407                 maxduration = -1;
408
409         start = ast_tvnow();
410         while ((ms = ast_remaining_ms(start, maxduration))) {
411                 ms = ast_waitfor(chan, ms);
412                 if (ms < 0) {
413                         break;
414                 }
415
416                 if (maxduration > 0 && ms == 0) {
417                         break;
418                 }
419
420                 f = ast_read(chan);
421                 if (!f) {
422                         res = -1;
423                         break;
424                 }
425                 if (f->frametype == AST_FRAME_VOICE) {
426                         res = ast_writestream(s, f);
427
428                         if (res) {
429                                 ast_log(LOG_WARNING, "Problem writing frame\n");
430                                 ast_frfree(f);
431                                 status_response = "ERROR";
432                                 break;
433                         }
434
435                         if (silence > 0) {
436                                 dspsilence = 0;
437                                 ast_dsp_silence(sildet, f, &dspsilence);
438                                 if (dspsilence) {
439                                         totalsilence = dspsilence;
440                                 } else {
441                                         totalsilence = 0;
442                                 }
443                                 if (totalsilence > silence) {
444                                         /* Ended happily with silence */
445                                         ast_frfree(f);
446                                         gotsilence = 1;
447                                         status_response = "SILENCE";
448                                         break;
449                                 }
450                         }
451                 } else if (f->frametype == AST_FRAME_VIDEO) {
452                         res = ast_writestream(s, f);
453
454                         if (res) {
455                                 ast_log(LOG_WARNING, "Problem writing frame\n");
456                                 status_response = "ERROR";
457                                 ast_frfree(f);
458                                 break;
459                         }
460                 } else if (f->frametype == AST_FRAME_DTMF) {
461                         enum dtmf_response rc =
462                                 record_dtmf_response(chan, &flags, f->subclass.integer, terminator);
463                         switch(rc)      {
464                         case RESPONSE_NO_MATCH:
465                                 break;
466                         case RESPONSE_OPERATOR:
467                                 status_response = "OPERATOR";
468                                 ast_debug(1, "Got OPERATOR\n");
469                                 break;
470                         case RESPONSE_DTMF:
471                                 status_response = "DTMF";
472                                 ast_debug(1, "Got DTMF\n");
473                                 break;
474                         }
475                         if (rc != RESPONSE_NO_MATCH) {
476                                 ast_frfree(f);
477                                 break;
478                         }
479                 }
480                 ast_frfree(f);
481         }
482
483         if (maxduration > 0 && !ms) {
484                 gottimeout = 1;
485                 status_response = "TIMEOUT";
486         }
487
488         if (!f) {
489                 ast_debug(1, "Got hangup\n");
490                 res = -1;
491                 status_response = "HANGUP";
492                 if (!ast_test_flag(&flags, OPTION_KEEP)) {
493                         ast_filedelete(args.filename, NULL);
494                 }
495         }
496
497         if (gotsilence && truncate_silence) {
498                 ast_stream_rewind(s, silence - 1000);
499                 ast_truncstream(s);
500         } else if (!gottimeout && f) {
501                 /*
502                  * Strip off the last 1/4 second of it, if we didn't end because of a timeout,
503                  * or a hangup.  This must mean we ended because of a DTMF tone and while this
504                  * 1/4 second stripping is very old code the most likely explanation is that it
505                  * relates to stripping a partial DTMF tone.
506                  */
507                 ast_stream_rewind(s, 250);
508                 ast_truncstream(s);
509         }
510         ast_closestream(s);
511
512         if (silgen)
513                 ast_channel_stop_silence_generator(chan, silgen);
514
515 out:
516         if ((silence > 0) && rfmt) {
517                 res = ast_set_read_format(chan, rfmt);
518                 if (res) {
519                         ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
520                 }
521         }
522
523         if (sildet) {
524                 ast_dsp_free(sildet);
525         }
526
527         pbx_builtin_setvar_helper(chan, "RECORD_STATUS", status_response);
528
529         return res;
530 }
531
532 static int unload_module(void)
533 {
534         return ast_unregister_application(app);
535 }
536
537 static int load_module(void)
538 {
539         return ast_register_application_xml(app, record_exec);
540 }
541
542 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Trivial Record Application");