Debian Codegraph @

apps/app_record.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2005, Digium, Inc.
5 *
6 * Matthew Fredrickson <[email protected]>
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 <[email protected]>
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 <since>
46 <version>0.1.8</version>
47 </since>
48 <synopsis>
49 Record to a file.
50 </synopsis>
51 <syntax>
52 <parameter name="filename" required="true" argsep=".">
53 <argument name="filename" required="true" />
54 <argument name="format" required="true">
55 <para>Is the format of the file type to be recorded (wav, gsm, etc).</para>
56 </argument>
57 </parameter>
58 <parameter name="silence">
59 <para>Is the number of seconds of silence to allow before returning.</para>
60 </parameter>
61 <parameter name="maxduration">
62 <para>Is the maximum recording duration in seconds. If missing
63 or 0 there is no maximum.</para>
64 </parameter>
65 <parameter name="options">
66 <optionlist>
67 <option name="a">
68 <para>Append to existing recording rather than replacing.</para>
69 </option>
70 <option name="n">
71 <para>Do not answer, but record anyway if line not yet answered.</para>
72 </option>
73 <option name="o">
74 <para>Exit when 0 is pressed, setting the variable <variable>RECORD_STATUS</variable>
75 to <literal>OPERATOR</literal> instead of <literal>DTMF</literal></para>
76 </option>
77 <option name="q">
78 <para>quiet (do not play a beep tone).</para>
79 </option>
80 <option name="s">
81 <para>skip recording if the line is not yet answered.</para>
82 </option>
83 <option name="t">
84 <para>use alternate '*' terminator key (DTMF) instead of default '#'</para>
85 </option>
86 <option name="u">
87 <para>Don't truncate recorded silence.</para>
88 </option>
89 <option name="x">
90 <para>Ignore all terminator keys (DTMF) and keep recording until hangup.</para>
91 </option>
92 <option name="k">
93 <para>Keep recorded file upon hangup.</para>
94 </option>
95 <option name="y">
96 <para>Terminate recording if *any* DTMF digit is received.</para>
97 </option>
98 </optionlist>
99 </parameter>
100 </syntax>
101 <description>
102 <para>If filename contains <literal>%d</literal>, these characters will be replaced with a number
103 incremented by one each time the file is recorded.
104 Use <astcli>core show file formats</astcli> to see the available formats on your system
105 User can press <literal>#</literal> to terminate the recording and continue to the next priority.
106 If the user hangs up during a recording, all data will be lost and the application will terminate.</para>
107 <variablelist>
108 <variable name="RECORDED_FILE">
109 <para>Will be set to the final filename of the recording, without an extension.</para>
110 </variable>
111 <variable name="RECORD_STATUS">
112 <para>This is the final status of the command</para>
113 <value name="DTMF">A terminating DTMF was received ('#' or '*', depending upon option 't')</value>
114 <value name="SILENCE">The maximum silence occurred in the recording.</value>
115 <value name="SKIP">The line was not yet answered and the 's' option was specified.</value>
116 <value name="TIMEOUT">The maximum length was reached.</value>
117 <value name="HANGUP">The channel was hung up.</value>
118 <value name="ERROR">An unrecoverable error occurred, which resulted in a WARNING to the logs.</value>
119 </variable>
120 </variablelist>
121 </description>
122 <see-also>
123 <ref type="function">RECORDING_INFO</ref>
124 </see-also>
125 </application>
126 <function name="RECORDING_INFO" language="en_US">
127 <synopsis>
128 Retrieve information about a recording previously created using the Record application
129 </synopsis>
130 <syntax>
131 <parameter name="property" required="true">
132 <para>The property about the recording to retrieve.</para>
133 <enumlist>
134 <enum name="duration">
135 <para>The duration, in milliseconds, of the recording.</para>
136 </enum>
137 </enumlist>
138 </parameter>
139 </syntax>
140 <description>
141 <para>Returns information about the previous recording created by <literal>Record</literal>.
142 This function cannot be used if no recordings have yet been completed.</para>
143 </description>
144 <see-also>
145 <ref type="application">Record</ref>
146 </see-also>
147 </function>
148 ***/
149
150 #define OPERATOR_KEY '0'
151
152 static char *app = "Record";
153
154 enum {
155 OPTION_APPEND = (1 << 0),
156 OPTION_NOANSWER = (1 << 1),
157 OPTION_QUIET = (1 << 2),
158 OPTION_SKIP = (1 << 3),
159 OPTION_STAR_TERMINATE = (1 << 4),
160 OPTION_IGNORE_TERMINATE = (1 << 5),
161 OPTION_KEEP = (1 << 6),
162 OPTION_ANY_TERMINATE = (1 << 7),
163 OPTION_OPERATOR_EXIT = (1 << 8),
164 OPTION_NO_TRUNCATE = (1 << 9),
165 };
166
167 enum dtmf_response {
168 RESPONSE_NO_MATCH = 0,
169 RESPONSE_OPERATOR,
170 RESPONSE_DTMF,
171 };
172
173 AST_APP_OPTIONS(app_opts,{
174 AST_APP_OPTION('a', OPTION_APPEND),
175 AST_APP_OPTION('k', OPTION_KEEP),
176 AST_APP_OPTION('n', OPTION_NOANSWER),
177 AST_APP_OPTION('o', OPTION_OPERATOR_EXIT),
178 AST_APP_OPTION('q', OPTION_QUIET),
179 AST_APP_OPTION('s', OPTION_SKIP),
180 AST_APP_OPTION('t', OPTION_STAR_TERMINATE),
181 AST_APP_OPTION('u', OPTION_NO_TRUNCATE),
182 AST_APP_OPTION('y', OPTION_ANY_TERMINATE),
183 AST_APP_OPTION('x', OPTION_IGNORE_TERMINATE),
184 });
185
186 /*!
187 * \internal
188 * \brief Used to determine what action to take when DTMF is received while recording
189 * \since 13.0.0
190 *
191 * \param chan channel being recorded
192 * \param flags option flags in use by the record application
193 * \param dtmf_integer the integer value of the DTMF key received
194 * \param terminator key currently set to be pressed for normal termination
195 *
196 * \returns One of enum dtmf_response
197 */
198 static enum dtmf_response record_dtmf_response(struct ast_channel *chan,
199 struct ast_flags *flags, int dtmf_integer, int terminator)
200 {
201 if ((dtmf_integer == OPERATOR_KEY) &&
202 (ast_test_flag(flags, OPTION_OPERATOR_EXIT))) {
203 return RESPONSE_OPERATOR;
204 }
205
206 if ((dtmf_integer == terminator) ||
207 (ast_test_flag(flags, OPTION_ANY_TERMINATE))) {
208 return RESPONSE_DTMF;
209 }
210
211 return RESPONSE_NO_MATCH;
212 }
213
214 static int create_destination_directory(const char *path)
215 {
216 int res;
217 char *path_copy = ast_strdupa(path), directory[PATH_MAX], *file_sep;
218
219 if (!(file_sep = strrchr(path_copy, '/'))) {
220 /* No directory to create */
221 return 0;
222 }
223
224 /* Overwrite temporarily */
225 *file_sep = '\0';
226
227 /* Absolute path? */
228 if (path_copy[0] == '/') {
229 res = ast_mkdir(path_copy, 0777);
230 *file_sep = '/';
231 return res;
232 }
233
234 /* Relative path */
235 res = snprintf(directory, sizeof(directory), "%s/sounds/%s",
236 ast_config_AST_DATA_DIR, path);
237
238 *file_sep = '/';
239
240 if (res >= sizeof(directory)) {
241 /* We truncated, so we fail */
242 return -1;
243 }
244
245 return ast_mkdir(directory, 0777);
246 }
247
248 struct recording_data {
249 unsigned long duration; /* Duration, in ms */
250 };
251
252 static void recording_data_free(void *data)
253 {
254 ast_free(data);
255 }
256
257 static const struct ast_datastore_info recording_data_info = {
258 .type = "RECORDING_INFO",
259 .destroy = recording_data_free,
260 };
261
262 static int recording_info_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
263 {
264 struct ast_datastore *ds;
265 struct recording_data *recdata;
266
267 *buf = '\0';
268
269 if (!chan) {
270 ast_log(LOG_ERROR, "%s() can only be executed on a channel\n", cmd);
271 return -1;
272 } else if (ast_strlen_zero(data)) {
273 ast_log(LOG_ERROR, "%s() requires an argument\n", cmd);
274 return -1;
275 }
276
277 ast_channel_lock(chan);
278 ds = ast_channel_datastore_find(chan, &recording_data_info, NULL);
279 ast_channel_unlock(chan);
280
281 if (!ds) {
282 ast_log(LOG_ERROR, "No recordings have completed on channel %s\n", ast_channel_name(chan));
283 return -1;
284 }
285
286 recdata = ds->data;
287
288 if (!strcasecmp(data, "duration")) {
289 snprintf(buf, len, "%ld", recdata->duration);
290 } else {
291 ast_log(LOG_ERROR, "Invalid property type: %s\n", data);
292 return -1;
293 }
294
295 return 0;
296 }
297
298 static int record_exec(struct ast_channel *chan, const char *data)
299 {
300 struct ast_datastore *ds;
301 int res = 0;
302 char *ext = NULL, *opts[0];
303 char *parse;
304 int i = 0;
305 char tmp[PATH_MAX];
306 struct recording_data *recdata;
307
308 struct ast_filestream *s = NULL;
309 struct ast_frame *f = NULL;
310
311 struct ast_dsp *sildet = NULL; /* silence detector dsp */
312 int totalsilence = 0;
313 int dspsilence = 0;
314 int silence = 0; /* amount of silence to allow */
315 int gotsilence = 0; /* did we timeout for silence? */
316 int truncate_silence = 1; /* truncate on complete silence recording */
317 int maxduration = 0; /* max duration of recording in milliseconds */
318 int gottimeout = 0; /* did we timeout for maxduration exceeded? */
319 int terminator = '#';
320 RAII_VAR(struct ast_format *, rfmt, NULL, ao2_cleanup);
321 int ioflags;
322 struct ast_silence_generator *silgen = NULL;
323 struct ast_flags flags = { 0, };
324 AST_DECLARE_APP_ARGS(args,
325 AST_APP_ARG(filename);
326 AST_APP_ARG(silence);
327 AST_APP_ARG(maxduration);
328 AST_APP_ARG(options);
329 );
330 int ms;
331 struct timeval start;
332 const char *status_response = "ERROR";
333
334 /* Retrieve or create the datastore */
335 ast_channel_lock(chan);
336 if (!(ds = ast_channel_datastore_find(chan, &recording_data_info, NULL))) {
337 if (!(ds = ast_datastore_alloc(&recording_data_info, NULL))) {
338 ast_log(LOG_ERROR, "Unable to allocate new datastore.\n");
339 ast_channel_unlock(chan);
340 return -1;
341 }
342
343 if (!(recdata = ast_calloc(1, sizeof(*recdata)))) {
344 ast_datastore_free(ds);
345 ast_channel_unlock(chan);
346 return -1;
347 }
348
349 ds->data = recdata;
350 ast_channel_datastore_add(chan, ds);
351 } else {
352 recdata = ds->data;
353 }
354 ast_channel_unlock(chan);
355
356 /* Reset, in case already set */
357 recdata->duration = 0;
358
359 /* The next few lines of code parse out the filename and header from the input string */
360 if (ast_strlen_zero(data)) { /* no data implies no filename or anything is present */
361 ast_log(LOG_WARNING, "Record requires an argument (filename)\n");
362 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
363 return -1;
364 }
365
366 parse = ast_strdupa(data);
367 AST_STANDARD_APP_ARGS(args, parse);
368 if (args.argc == 4)
369 ast_app_parse_options(app_opts, &flags, opts, args.options);
370
371 if (!ast_strlen_zero(args.filename)) {
372 ext = strrchr(args.filename, '.'); /* to support filename with a . in the filename, not format */
373 if (!ext)
374 ext = strchr(args.filename, ':');
375 if (ext) {
376 *ext = '\0';
377 ext++;
378 }
379 }
380 if (!ext) {
381 ast_log(LOG_WARNING, "No extension specified to filename!\n");
382 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
383 return -1;
384 }
385 if (args.silence) {
386 if ((sscanf(args.silence, "%30d", &i) == 1) && (i > -1)) {
387 silence = i * 1000;
388 } else if (!ast_strlen_zero(args.silence)) {
389 ast_log(LOG_WARNING, "'%s' is not a valid silence duration\n", args.silence);
390 }
391 }
392
393 if (ast_test_flag(&flags, OPTION_NO_TRUNCATE))
394 truncate_silence = 0;
395
396 if (args.maxduration) {
397 if ((sscanf(args.maxduration, "%30d", &i) == 1) && (i > -1))
398 /* Convert duration to milliseconds */
399 maxduration = i * 1000;
400 else if (!ast_strlen_zero(args.maxduration))
401 ast_log(LOG_WARNING, "'%s' is not a valid maximum duration\n", args.maxduration);
402 }
403
404 if (ast_test_flag(&flags, OPTION_STAR_TERMINATE))
405 terminator = '*';
406 if (ast_test_flag(&flags, OPTION_IGNORE_TERMINATE))
407 terminator = '\0';
408
409 /*
410 If a '%d' is specified as part of the filename, we replace that token with
411 sequentially incrementing numbers until we find a unique filename.
412 */
413 if (strchr(args.filename, '%')) {
414 size_t src, dst, count = 0;
415 size_t src_len = strlen(args.filename);
416 size_t dst_len = sizeof(tmp) - 1;
417
418 do {
419 for (src = 0, dst = 0; src < src_len && dst < dst_len; src++) {
420 if (!strncmp(&args.filename[src], "%d", 2)) {
421 int s = snprintf(&tmp[dst], PATH_MAX - dst, "%zu", count);
422 if (s >= PATH_MAX - dst) {
423 /* We truncated, so we need to bail */
424 ast_log(LOG_WARNING, "Failed to create unique filename from template: %s\n", args.filename);
425 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
426 return -1;
427 }
428 dst += s;
429 src++;
430 } else {
431 tmp[dst] = args.filename[src];
432 tmp[++dst] = '\0';
433 }
434 }
435 count++;
436 } while (ast_fileexists(tmp, ext, ast_channel_language(chan)) > 0);
437 } else
438 ast_copy_string(tmp, args.filename, sizeof(tmp));
439
440 pbx_builtin_setvar_helper(chan, "RECORDED_FILE", tmp);
441
442 if (ast_channel_state(chan) != AST_STATE_UP) {
443 if (ast_test_flag(&flags, OPTION_SKIP)) {
444 /* At the user's option, skip if the line is not up */
445 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "SKIP");
446 return 0;
447 } else if (!ast_test_flag(&flags, OPTION_NOANSWER)) {
448 /* Otherwise answer unless we're supposed to record while on-hook */
449 res = ast_answer(chan);
450 }
451 }
452
453 if (res) {
454 ast_log(LOG_WARNING, "Could not answer channel '%s'\n", ast_channel_name(chan));
455 status_response = "ERROR";
456 goto out;
457 }
458
459 if (!ast_test_flag(&flags, OPTION_QUIET)) {
460 /* Play a beep to signify the start of the record operation */
461 if (ast_stream_and_wait(chan, "beep", "")) {
462 status_response = "HANGUP";
463 goto out;
464 }
465 }
466
467 /* The end of beep code. Now the recording starts */
468
469 if (silence > 0) {
470 rfmt = ao2_bump(ast_channel_readformat(chan));
471 res = ast_set_read_format(chan, ast_format_slin);
472 if (res < 0) {
473 ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
474 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
475 return -1;
476 }
477 sildet = ast_dsp_new();
478 if (!sildet) {
479 ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
480 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", "ERROR");
481 return -1;
482 }
483 ast_dsp_set_threshold(sildet, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE));
484 }
485
486 if (create_destination_directory(tmp)) {
487 ast_log(LOG_WARNING, "Could not create directory for file %s\n", args.filename);
488 status_response = "ERROR";
489 goto out;
490 }
491
492 ioflags = ast_test_flag(&flags, OPTION_APPEND) ? O_CREAT|O_APPEND|O_WRONLY : O_CREAT|O_TRUNC|O_WRONLY;
493 s = ast_writefile(tmp, ext, NULL, ioflags, 0, AST_FILE_MODE);
494
495 if (!s) {
496 ast_log(LOG_WARNING, "Could not create file %s\n", args.filename);
497 status_response = "ERROR";
498 goto out;
499 }
500
501 if (ast_opt_transmit_silence)
502 silgen = ast_channel_start_silence_generator(chan);
503
504 /* Request a video update */
505 ast_indicate(chan, AST_CONTROL_VIDUPDATE);
506
507 if (maxduration <= 0)
508 maxduration = -1;
509
510 start = ast_tvnow();
511 while ((ms = ast_remaining_ms(start, maxduration))) {
512 ms = ast_waitfor(chan, ms);
513 if (ms < 0) {
514 break;
515 }
516
517 if (maxduration > 0 && ms == 0) {
518 break;
519 }
520
521 f = ast_read(chan);
522 if (!f) {
523 res = -1;
524 break;
525 }
526 if (f->frametype == AST_FRAME_VOICE) {
527 res = ast_writestream(s, f);
528
529 if (res) {
530 ast_log(LOG_WARNING, "Problem writing frame\n");
531 ast_frfree(f);
532 status_response = "ERROR";
533 break;
534 }
535
536 if (silence > 0) {
537 dspsilence = 0;
538 ast_dsp_silence(sildet, f, &dspsilence);
539 if (dspsilence) {
540 totalsilence = dspsilence;
541 } else {
542 totalsilence = 0;
543 }
544 if (totalsilence > silence) {
545 /* Ended happily with silence */
546 ast_frfree(f);
547 gotsilence = 1;
548 status_response = "SILENCE";
549 break;
550 }
551 }
552 } else if (f->frametype == AST_FRAME_VIDEO) {
553 res = ast_writestream(s, f);
554
555 if (res) {
556 ast_log(LOG_WARNING, "Problem writing frame\n");
557 status_response = "ERROR";
558 ast_frfree(f);
559 break;
560 }
561 } else if (f->frametype == AST_FRAME_DTMF) {
562 enum dtmf_response rc =
563 record_dtmf_response(chan, &flags, f->subclass.integer, terminator);
564 switch(rc) {
565 case RESPONSE_NO_MATCH:
566 break;
567 case RESPONSE_OPERATOR:
568 status_response = "OPERATOR";
569 ast_debug(1, "Got OPERATOR\n");
570 break;
571 case RESPONSE_DTMF:
572 status_response = "DTMF";
573 ast_debug(1, "Got DTMF\n");
574 break;
575 }
576 if (rc != RESPONSE_NO_MATCH) {
577 ast_frfree(f);
578 break;
579 }
580 }
581 ast_frfree(f);
582 }
583
584 if (maxduration > 0 && !ms) {
585 gottimeout = 1;
586 status_response = "TIMEOUT";
587 }
588
589 if (!f) {
590 ast_debug(1, "Got hangup\n");
591 res = -1;
592 status_response = "HANGUP";
593 if (!ast_test_flag(&flags, OPTION_KEEP)) {
594 ast_filedelete(args.filename, NULL);
595 }
596 }
597
598 if (gotsilence && truncate_silence) {
599 ast_stream_rewind(s, silence - 1000);
600 ast_truncstream(s);
601 } else if (!gottimeout && f) {
602 /*
603 * Strip off the last 1/4 second of it, if we didn't end because of a timeout,
604 * or a hangup. This must mean we ended because of a DTMF tone and while this
605 * 1/4 second stripping is very old code the most likely explanation is that it
606 * relates to stripping a partial DTMF tone.
607 */
608 ast_stream_rewind(s, 250);
609 ast_truncstream(s);
610 }
611 ast_closestream(s);
612
613 if (silgen)
614 ast_channel_stop_silence_generator(chan, silgen);
615
616 out:
617 recdata->duration = ast_tvdiff_ms(ast_tvnow(), start);
618
619 if ((silence > 0) && rfmt) {
620 res = ast_set_read_format(chan, rfmt);
621 if (res) {
622 ast_log(LOG_WARNING, "Unable to restore read format on '%s'\n", ast_channel_name(chan));
623 }
624 }
625
626 if (sildet) {
627 ast_dsp_free(sildet);
628 }
629
630 pbx_builtin_setvar_helper(chan, "RECORD_STATUS", status_response);
631
632 return res;
633 }
634
635 static struct ast_custom_function acf_recording_info = {
636 .name = "RECORDING_INFO",
637 .read = recording_info_read,
638 };
639
640 static int unload_module(void)
641 {
642 int res;
643 res = ast_custom_function_unregister(&acf_recording_info);
644 res |= ast_unregister_application(app);
645 return res;
646 }
647
648 static int load_module(void)
649 {
650 int res;
651 res = ast_register_application_xml(app, record_exec);
652 res |= ast_custom_function_register(&acf_recording_info);
653 return res;
654 }
655
656 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Trivial Record Application");